using FCOMMON;
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_AddAI : fBase
    {
        dsPRJ.EETGW_JobReport_AutoInputRow dr;
        Boolean copyMOde = false;
        Boolean bInit = false;
        public fJobReport_AddAI(dsPRJ.EETGW_JobReport_AutoInputRow 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.panel1.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)
        {
            EnsureVisibleAndUsableSize();

            //사용자목록
            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.cmbGrp26.DisplayMember = "Value";
            this.cmbGrp26.ValueMember = "Value";
            this.cmbGrp26.DataSource = stateList;
            this.cmbGrp26.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.cmbjobtype.DisplayMember = "Value";
            this.cmbjobtype.ValueMember = "Value";
            this.cmbjobtype.DataSource = dt_type;

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

            //근무형태
            var dt_kunmu = FCOMMON.DBM.getCodeTable("26");
            this.cmbGrp26.DisplayMember = "Value";
            this.cmbGrp26.ValueMember = "Value";
            this.cmbGrp26.DataSource = dt_kunmu;

            if (dr.autoinput == "L") radLogin.Checked = true;
            else radAuto.Checked = true;

            //사용여부
            chkEnable.Checked = dr.enable;

            //담당자목록

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

            // tbWW.Text = dr.ww;
            dts.Value = DateTime.Parse(dr.pdate);   //일자선택

            this.checkBox1.Checked = !String.IsNullOrEmpty(dr.edate);
            if (checkBox1.Checked) dte.Value = DateTime.Parse(dr.edate);
            dte.Enabled = checkBox1.Checked;
            checkBox1.CheckedChanged += (s1, e1) => {
                dte.Enabled = checkBox1.Checked;
            };

            cmbUser.SelectedValue = dr.uid;
            tbProject.Text = dr.projectName;
            cmbRequest.SelectedValue = dr.requestpart;
            cmbPackage.SelectedValue = dr.package;
            cmbjobtype.SelectedValue = dr.type;
            cmbjobproc.SelectedValue = dr.process;
            cmbjobgrp.SelectedValue = dr.jobgrp;
       
            tbTag.Text = dr.tag;

            //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 (string.IsNullOrEmpty(dr.description2))
            {
                this.richTextBoxEx1.Text = dr.description;
            }
            else
            {
                try
                {
                    this.richTextBoxEx1.Rtf = dr.description2;
                }
                catch 
                {
                    this.richTextBoxEx1.Text = dr.description;
                }
            }

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

            if (this.richTextBoxEx1.Text.Trim() != "")
            {
                this.richTextBoxEx1.Focus();
            }
            else
            {
                tbProject.Focus();
                tbProject.SelectAll();
            }
            tbProject.Tag = tbProject.Text;


            bInit = true;
        }
        //    editform.editor ed;
        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 "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.tbProject.Tag = f.Title;
                                this.tbProjectIndex.Text = f.Index.ToString();
                             

                                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.cmbjobtype.Text = predr["type"].ToString(); //190506

                                        if (predr["process"] != DBNull.Value)
                                            cmbjobproc.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.dts.Value.ToString("yyyy-MM-dd"));
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            dts.Value = f.dtSelect;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Invalidate();
            if (tbProject.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("프로젝트(아이템) 명칭이 없습니다.");
                tbProject.Focus();
                return;
            }
            if (cmbjobtype.Text != "휴가" && string.IsNullOrEmpty(this.richTextBoxEx1.Text) == true)
            {
                FCOMMON.Util.MsgE("진행 내용이 없습니다.");
                this.richTextBoxEx1.Focus();
                return;
            }
            float hour = 8f;

            if (cmbjobtype.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("업무형태를 선택하세요");
                cmbjobtype.Focus();
                return;
            }
            if (cmbjobproc.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("공정을 선택하세요");
                cmbjobproc.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";
            }

            if (radAuto.Checked) dr.autoinput = "A"; //항상자동
            else dr.autoinput = "L"; //로그인자동

            dr.enable = chkEnable.Checked;

            this.dr.uid = this.cmbUser.SelectedValue.ToString();
            this.dr.pdate = dts.Value.ToString("yyyy-MM-dd");
            this.dr.status = cmbGrp26.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 = cmbjobtype.Text;
            this.dr.process = cmbjobproc.Text;
            this.dr.jobgrp = cmbjobgrp.Text;
            this.dr.tag = tbTag.Text.Trim();
            this.dr.hrs = 8f;
            this.dr.SetotNull();

            //완료일자 적용 - 210803 chi  <= 김윤선p
            if (checkBox1.Checked) dr.edate = dte.Value.ToString("yyyy-MM-dd");
            else dr.SetedateNull();

            //MessageBox.Show(richTextBox1.Text);
            this.dr.description = richTextBoxEx1.Text;
            this.dr.description2 = richTextBoxEx1.Rtf; // ef.DocumentText;//  richTextBox1.Rtf;
            this.bs.EndEdit();
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

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

        }

   
        private void dte_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(dte.Value, myCWR, myFirstDOW);
            this.tbWeekE.Text = "ww" + dat.ToString();

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            this.dte.Enabled = this.checkBox1.Checked;
        }
    }
}
