using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FPJ0000.JobReport
{
    public partial class fJobReport_Add : Form
    {
        dsPRJ.JobReportRow dr;
        Boolean copyMOde = false;
        Boolean bInit = false;
        public fJobReport_Add(dsPRJ.JobReportRow dr_,Boolean copy=false)
        {
            InitializeComponent();
            dr = dr_;
            this.KeyPreview = true;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };

            foreach (Control ctl in this.Controls)
            {
                if (ctl.GetType() == typeof(TextBox) || ctl.GetType() == typeof(ComboBox))
                {
                    ctl.KeyDown += ctl_KeyDown;
                }
            }
            copyMOde = copy;
            this.tbProject.SelectedIndexChanged += tbProject_SelectedIndexChanged;
        }

        void tbProject_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bInit==false || this.tbProject.SelectedIndex < 0) return;
            var data = this.tbProject.SelectedValue;
            if (data == null) return;
            if(data.GetType() == typeof(DataRowView))
            {
                var drv = data as DataRowView;
                var idx = int.Parse(drv["Code"].ToString());
                tbProjectIndex.Text = idx.ToString();
                tbProject.Tag = tbProject.Text;
                Console.WriteLine(string.Format("Project Select #1 {0}:{1}",idx,tbProject.Text));
            }
            else
            {
                var idx = int.Parse(data.ToString());
                tbProjectIndex.Text = idx.ToString();
                tbProject.Tag = tbProject.Text;
                Console.WriteLine(string.Format("Project Select #2 {0}:{1}", idx, tbProject.Text));
            }

        }

        private void fJobReport_Add_Load(object sender, EventArgs e)
        {
            //사용자목록
            this.bs.DataSource = dr;

            //해당 사용자에 걸린 프로젝트 목록 가져오기
            var userProject = FCOMMON.DBM.getUserProjectList(FCOMMON.info.Login.nameK);
            this.tbProject.DataSource = userProject;
            this.tbProject.ValueMember = "Code";
            this.tbProject.DisplayMember = "Value";

            //상태
            var stateList = FCOMMON.DBM.getCodeTable("12");
            this.cmbState.DisplayMember = "Value";
            this.cmbState.ValueMember = "Value";
            this.cmbState.DataSource = stateList;
            this.cmbState.Text = dr.status;

            //요청부서
            var dt_request = FCOMMON.DBM.getCodeTable("13");
            this.cmbRequest.DisplayMember = "Value";
            this.cmbRequest.ValueMember = "Value";
            this.cmbRequest.DataSource = dt_request;

            //패키지
            var dt_package = FCOMMON.DBM.getCodeTable("14");
            this.cmbPackage.DisplayMember = "Value";
            this.cmbPackage.ValueMember = "Value";
            this.cmbPackage.DataSource = dt_package;

            //타입
            var dt_type = FCOMMON.DBM.getCodeTable("15");
            this.cmbType.DisplayMember = "Value";
            this.cmbType.ValueMember = "Value";
            this.cmbType.DataSource = dt_type;

            //공정
            var dt_process = FCOMMON.DBM.getCodeTable("16");
            this.cmbProcess.DisplayMember = "Value";
            this.cmbProcess.ValueMember = "Value";
            this.cmbProcess.DataSource = dt_process;

            //담당자목록

            var dt_users = FCOMMON.DBM.getUserTable();// getGroupList("name + '(' + id + ')'", "Users", "[level] > 0 and [level] < 10", false, false);
            this.cmbUser.DisplayMember = "dispName";
            this.cmbUser.ValueMember = "id";
            this.cmbUser.DataSource = dt_users;
            if (FCOMMON.info.Login.level < 5) cmbUser.Enabled = false;

            // tbWW.Text = dr.ww;
            dtPdate.Value = DateTime.Parse(dr.pdate);   //일자선택
            cmbUser.SelectedValue = dr.uid;
            tbProject.Text = dr.projectName;
            cmbRequest.SelectedValue = dr.requestpart;
            cmbPackage.SelectedValue = dr.package;
            cmbType.SelectedValue = dr.type;
            cmbProcess.SelectedValue = dr.process;

            if (cmbRequest.Text == "") cmbRequest.Text = "EE1";
            if (cmbPackage.Text == "") cmbPackage.Text = "Common";

            //프로젝트 번호 확인(프로젝트번호가 바뀌면 데이터를 업데이트 해준다)
            if (dr.IspidxNull())
            {
                tbProjectIndex.Tag = -1;
                tbProjectIndex.Text = "-1";
            }
            else
            {
                tbProjectIndex.Tag = dr.pidx;
                tbProjectIndex.Text = dr.pidx.ToString();
            }

            //신규일때만 사용가능 함
            if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Added) chkAutoAdd.Enabled = true;
            else chkAutoAdd.Enabled = false;

            this.Show();
            Application.DoEvents();

            if(tbDescription.Text.Trim() != "")
            {
                tbDescription.Focus();
                tbDescription.SelectAll();
            }
            else
            {
                tbProject.Focus();
                tbProject.SelectAll();
            }
            tbProject.Tag = tbProject.Text;
            bInit = true;
        }

        void ctl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Control ctl = sender as Control;
                string nm = ctl.Name.ToLower();
                string search = ctl.Text.Trim();

                Console.WriteLine("inner keydown " + nm + ":" + search);

                switch (nm)
                {
                    //case "cmbrequest":

                    //    //요청자가 마지막으로 입력한 자료의 process 를 찾아서 기입해준다.
                    //    var lastprocess = FCOMMON.DBM.getFirstValue("process", "purchase", "request like '%" + this.cmbUser.Text + "%'", "pdate desc");
                    //    if (lastprocess != "") cbProcess.Text = lastprocess;
                    //    tbSID.Focus();
                    //    break;
                    case "tbdescription":
                        if (e.Control)
                        {
                            btSave.Focus();
                        }
                        break;
                    case "tbproject":
                        if (search != "")
                        {
                            var f = new fLovProject("%" + search + "%");
                            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                this.tbProject.Text = f.Title;
                                this.tbProjectIndex.Text = f.Index.ToString();
                                tbHrs.Focus();
                                tbHrs.SelectAll();

                                if (tbProjectIndex.Tag.ToString() != f.Index.ToString() || f.Index == -1)
                                {
                                    //마지막 데이터를 찾아서 공정등의 정보를 업데이트한다.
                                    var uid = cmbUser.SelectedValue.ToString();
                                    DataTable lastDt = null;

                                    if (f.Index != -1) lastDt = FCOMMON.DBM.getLastJobReportData(uid, f.Index);
                                    else lastDt = FCOMMON.DBM.getLastJobReportDatabyProjectName(uid, f.Title);

                                    if (lastDt != null && lastDt.Rows.Count > 0)
                                    {
                                        var predr = lastDt.Rows[0];

                                        if (predr["requestpart"] != DBNull.Value)
                                            this.cmbRequest.Text = predr["requestpart"].ToString(); //190506

                                        if (predr["package"] != DBNull.Value)
                                            this.cmbPackage.Text = predr["package"].ToString(); //190506

                                        if (predr["type"] != DBNull.Value)
                                            this.cmbType.Text = predr["type"].ToString(); //190506

                                        if (predr["process"] != DBNull.Value)
                                            cmbProcess.Text = predr["process"].ToString(); //190506
                                    }
                                }
                            }
                            else
                            {
                                //이름만 사용한다.
                                tbProjectIndex.Text = "-1";
                                cmbRequest.Focus();
                            }
                        }
                        else
                        {
                            FCOMMON.Util.MsgE("프로젝트 혹은 아이템이름은 반드시 입력되어야 합니다.");
                            var tb = sender as ComboBox;
                            tb.SelectAll();
                            tb.Focus();
                        }
                        break;

                    default:
                        SendKeys.Send("{TAB}");
                        break;
                }
            }
        }
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FCM0000.fSelectDate f = new FCM0000.fSelectDate(this.dtPdate.Value.ToShortDateString());
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            dtPdate.Value = f.dtSelect;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Invalidate();
            if(tbProject.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("프로젝트(아이템) 명칭이 없습니다.");
                tbProject.Focus();                
                return;
            }
            if (cmbType.Text != "휴가" && tbDescription.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("진행 내용이 없습니다.");
                tbDescription.Focus();
                return;
            }
            float hour = Single.Parse(tbHrs.Text) + Single.Parse(tbOt.Text);
            if (hour == 0)
            {
                FCOMMON.Util.MsgE("근무시간/초과시간이 입력되지 않았습니다.");
                if (tbHrs.Enabled) tbHrs.Focus();
                else tbOt.Focus();
                return;
            }

            if (cmbType.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("업무형태를 선택하세요");
                cmbType.Focus();
                return;
            }
            if (cmbProcess.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("공정을 선택하세요");
                cmbProcess.Focus();
                return;
            }
            if (cmbUser.SelectedIndex < 0)
            {
                FCOMMON.Util.MsgE("담당자가 선택되지 않았습니다.");
                cmbUser.Focus();
                return;
            }

            if(tbProject.Tag.ToString() != tbProject.Text && tbProjectIndex.Text != "" && tbProjectIndex.Text != "-1")
            {
                FCOMMON.Util.MsgE("프로젝트가 선택되었으나 이름이 임의 수정되어 프로젝트 연결을 해제 합니다\n\n" +
                    "잘못된 프로젝트명은 프로젝트 관리화면에서 변경하시기 바랍니다.\n\n"+
                    "원본 : " + tbProject.Tag.ToString() + "\n" + 
                    "현재 : " + tbProject.Text);
                tbProjectIndex.Text = "-1";
            }

            ///휴일체크
            var taQ = new dsQueryTableAdapters.QueriesTableAdapter();
            var freeday = taQ.CheckHoliday(dtPdate.Value.ToShortDateString());
            if (freeday != null && freeday == true)
            {
                var hrs = float.Parse(tbHrs.Text);
                if (hrs > 0)
                {
                    FCOMMON.Util.MsgI("입력일자는 휴일로 등록되어 있습니다.\n\n근무시간은 OT에 입력하시기 바랍니다.");
                    //tbOt.Text = tbHrs.Text;
                    dr.hrs = 0;
                    tbHrs.Text = "0";
                    tbHrs.Focus();
                    return;
                }
            }

            if(chkAutoAdd.Checked && (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Added))
            {
                if(tbProjectIndex.Text == "" || tbProjectIndex.Text == "-1")
                {
                    FCOMMON.Util.MsgE("프로젝트 주간내역을 등록하려면 프로젝트가 지정되어야 합니다");
                    tbProject.Focus();
                    tbProject.SelectAll();
                    return;
                }
                else
                {
                    //190906
                    FCOMMON.DBM.addProjectHistory(int.Parse(tbProjectIndex.Text), dtPdate.Value.ToShortDateString(), tbDescription.Text.Trim());
                }
            }

            this.dr.uid = this.cmbUser.SelectedValue.ToString();
            this.dr.pdate = dtPdate.Value.ToShortDateString();
            this.dr.status = cmbState.Text;
            this.dr.projectName = tbProject.Text;
            if (tbProjectIndex.Text != "") dr.pidx = int.Parse(tbProjectIndex.Text);
            else dr.SetpidxNull();
            this.dr.requestpart = cmbRequest.Text;
            this.dr.package = cmbPackage.Text;
            this.dr.type = cmbType.Text;
            this.dr.process = cmbProcess.Text;
            if (tbHrs.Text != "") this.dr.hrs = double.Parse(tbHrs.Text);
            else this.dr.hrs = 0;
            if (tbOt.Text != "") this.dr.ot = double.Parse(tbOt.Text);
            else this.dr.ot = 0;
            this.dr.description = tbDescription.Text.Trim();
            this.bs.EndEdit();
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbType.Text.Trim() != "" &&
                cmbType.SelectedIndex >= 0 &&
                cmbProcess.SelectedIndex < 0 &&
                cmbUser.SelectedValue != null)
            {
                //공정을 자동선택해준다.
                //마지막 데이터를 찾아서 공정등의 정보를 업데이트한다.
                var uid = cmbUser.SelectedValue.ToString();
                var lastDt = FCOMMON.DBM.getLastJobReportData(uid, cmbType.Text.Trim());
                if (lastDt != null && lastDt.Rows.Count > 0)
                {
                    var predr = lastDt.Rows[0];// as dsPRJ.JobReportRow;
                    if (predr["process"] != DBNull.Value)
                        cmbProcess.Text = predr["process"].ToString(); //190506

                }
            }
        }

        private void dtPdate_ValueChanged(object sender, EventArgs e)
        {
            var myCI = new System.Globalization.CultureInfo("ko-KR");
            var myCal = myCI.Calendar;
            var myCWR = myCI.DateTimeFormat.CalendarWeekRule;
            DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;
            var dat = myCal.GetWeekOfYear(dtPdate.Value, myCWR, myFirstDOW);
            tbWW.Text = "ww" + dat.ToString();
            UpdateWOrkTime();

            //공휴일이면 시간을 초기화한다.
            if (tbHrs.Text == "") tbHrs.Text = "0";
            if (tbOt.Text == "") tbOt.Text = "0";
            float hrs = float.Parse(tbHrs.Text);
            if (dtPdate.Value.DayOfWeek == DayOfWeek.Saturday || dtPdate.Value.DayOfWeek == DayOfWeek.Sunday)
            {
                tbHrs.Enabled = false;
                if (hrs != 0)
                {
                    FCOMMON.Util.MsgI("공휴일에는 근무시간을 입력할 수 없습니다.\n초과시간에 입력하세요.\n\n해당 값은 삭제 됩니다.");
                    dr.hrs = 0;                    
                    tbHrs.Text = "0";
                    if (hrs != 8) tbOt.Text = hrs.ToString();
                    tbOt.Focus();
                }
            }
            else tbHrs.Enabled = true;
        }
        void UpdateWOrkTime()
        {
            //이번달 근무시간 및 초과시간 구하기
            if (cmbUser.SelectedValue != null)
            {
                float work, ot;
                int total;
                FCOMMON.DBM.getWorkTime(cmbUser.SelectedValue.ToString(), dtPdate.Value.ToString("yyyy-MM"), out work, out total, out ot);
                string msg = "금월 근무시간 : {0:N1}h / {1:N0}h\n금월 초과시간 : {2:N1}h";
                lbSummary.Text = string.Format(msg, work, total, ot);
            }
            else
            {
                lbSummary.Text = "--";
            }
        }
        private void cmbUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbUser.SelectedIndex >= 0)
                UpdateWOrkTime(); ;
        }

    }
}
