using AR;
using arCtl;
using FCM0000;
using FCOMMON;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FPJ0000.JobReport_
{
    public partial class fJobReport_Add : fBase
    {
        dsPRJ.JobReportRow dr;
        Boolean copyMOde = false;
        Boolean bInit = false;
        bool ReadMode = false;
        public fJobReport_Add(dsPRJ.JobReportRow dr_, Boolean copy = false, Boolean read = false)
        {
            InitializeComponent();
            dr = dr_;
            ReadMode = read;
            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;
            this.grpkisul.Visible = getKisulInput;

            //개발자상태에서만 표시한다
            var bDev = System.Diagnostics.Debugger.IsAttached;
            tbJobType.Visible = bDev;
            tbJobGrp.Visible = bDev;
        }

        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 bool getKisulInput
        {
            get
            {
                return FCOMMON.Util.getBit(
                FCOMMON.info.Login.gpermission,
                (int)FCOMMON.eGroupPermission.jobreport_kisul);
            }
        }
        private void fJobReport_Add_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            //사용자목록
            this.bs.DataSource = dr;
            this.dtOtStart.CustomFormat = "yyyy-MM-dd HH:mm.ss";
            this.dtOtEnd.CustomFormat = "yyyy-MM-dd HH:mm.ss";

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

            //상태
            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", "code,memo,svalue");
            //this.cmbType.DisplayMember = "Value";
            //this.cmbType.ValueMember = "Value";
            //this.cmbType.DataSource = dt_type;

            //공정
            var dt_jobprocess = FCOMMON.DBM.getCodeTable("16", "code,memo,svalue");
            tbJobProcess.Items.Clear();
            foreach (DataRow item in dt_jobprocess.Rows)
            {
                tbJobProcess.Items.Add(item["Value"].ToString());
            }

            ////업무분류
            //var dt_process = FCOMMON.DBM.getCodeTable("16", "code,memo,svalue");
            //this.tbJobProcess.DisplayMember = "Value";
            //this.tbJobProcess.ValueMember = "Value";
            //this.tbJobProcess.DataSource = dt_process;

            if (getKisulInput)
            {
                //기술분류
                var dt_kisuldiv = FCOMMON.DBM.getCodeTable("50");
                this.cmb_kisuldiv.DisplayMember = "Value";
                this.cmb_kisuldiv.ValueMember = "Value";
                this.cmb_kisuldiv.DataSource = dt_kisuldiv;

                //기술레벨
                var dt_kisullv = FCOMMON.DBM.getCodeTable("51");
                this.cmb_kisullv.Items.Clear();
                this.cmb_kisullv.Items.Add("0");
                foreach (DataRow dr in dt_kisullv.Rows)
                {
                    var v = dr["fvalue"];
                    if (v == null || string.IsNullOrWhiteSpace(v.ToString())) continue;
                    if (this.cmb_kisullv.Items.Contains(v.ToString()) == false)
                        this.cmb_kisullv.Items.Add(v.ToString());
                }
                //this.cmb_kisullv.DisplayMember = "Value";
                //this.cmb_kisullv.ValueMember = "Value";
                //this.cmb_kisullv.DataSource = dt_kisullv;
            }

            //담당자목록

            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;
            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;

            tbJobProcess.SelectedValue = dr.process;
            tbJobProcess.Text = dr.process;
            if (dr.IsjobgrpNull() || dr.jobgrp.isEmpty())
            {
                //공용코드에서 가져온다
                var cdr = FCOMMON.DBM.getCodeByMemo("15", dr.type);
                if (cdr.svalue.isEmpty() == false)
                    tbJobGrp.Text = cdr.svalue;
                else
                    tbJobGrp.Text = string.Empty;

                //this.cmbType.DisplayMember = "Value";
                //this.cmbType.ValueMember = "Value";
                //this.cmbType.DataSource = dt_type;

            }
            else tbJobGrp.Text = dr.jobgrp;

            tbJobType.Text = dr.type;

            tbTag.Text = dr.tag;

            RefreshJobTypeFull();

            //if (dr.process.isEmpty() && tbJobProcess.SelectedIndex < 0)	//기본값을 찾는다
            //{
            //    var dts = dt_process.AsEnumerable().Where(t => t.IsNull("SValue") == false).ToList();
            //    foreach (var dr in dts)
            //    {
            //        if (dr["Svalue"].ToString().Equals("O"))
            //        {
            //            tbJobProcess.Text = dr["Value"].ToString();
            //            break;
            //        }
            //    }
            //}


            if (dr.ot > 0)
            {
                if (dr.ot2 == 0)
                {
                    lbOt2.Text = "관리자 연장/휴일 근무 승인이 완료되지 않았습니다";
                    lbOt2.ForeColor = Color.Blue;
                    lbotReason.Visible = false;
                }
                else
                {
                    lbOt2.Text = $"승인시간:{dr.ot2}";
                    lbotReason.Text = $"사유:{dr.otReason}";
                }

            }
            else
            {
                lbOt2.Visible = false;
                lbotReason.Visible = false;
            }


            if (getKisulInput)
            {
                cmb_kisuldiv.Text = dr.kisuldiv;
                cmb_kisullv.Text = dr.kisullv;
                textBox1.Text = dr.kisulamt.ToString();
            }

            if (dr.IsotStartNull()) dtOtStart.Value = DateTime.Now;
            else dtOtStart.Value = dr.otStart;
            if (dr.IsotEndNull()) dtOtEnd.Value = DateTime.Now;
            else dtOtEnd.Value = dr.otEnd;

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

            if (dr.ot != 0)
            {
                dtOtStart.Enabled = true;
                dtOtEnd.Enabled = true;
            }
            else
            {
                dtOtStart.Enabled = false;
                dtOtEnd.Enabled = false;
            }

            //프로젝트 번호 확인(프로젝트번호가 바뀌면 데이터를 업데이트 해준다)
            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;


            if (string.IsNullOrEmpty(dr.description2))
            {
                this.richTextBoxEx1.Text = dr.description;
            }
            else
            {
                try
                {
                    this.richTextBoxEx1.Rtf = dr.description2;
                }
                catch
                {
                    this.richTextBoxEx1.Text = dr.description;
                }
            }

            //231026
            if (tbJobProcess.Text.isEmpty())
            {
                if (tbJobProcess.Items.Count == 1)
                    tbJobProcess.SelectedIndex = 0;
            }

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



            var MaxVerstion = FCOMMON.DBM.GetMaxVersion();
            if (string.IsNullOrEmpty(MaxVerstion) == false)
            {
                var curversion = Application.ProductVersion;
                var verchk = curversion.CompareTo(MaxVerstion);
                if (verchk < 0)
                {
                    //내버젼이 낮다
                    FCOMMON.Util.MsgE("현재 구 버젼을 사용하고 있습니다.\n업데이트를 진행 하고 사용하시기 바랍니다");
                }
            }




            if (dr.ot > 0 && dr.ot2 > 0)
            {
                tbOt.Enabled = false;
                FCOMMON.Util.MsgE("휴일/연장 근무시간이 관리자에의해 확정되었으므로 초과시간을 변경할 수 없습니다");
            }

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

            //  if (string.IsNullOrEmpty(richTextBox1.Text)) richTextBox1.Text = dr.description;

            //editor
            // ed = new editform.editor();
            //ed.AllowDiscAccess = true;
            //ed.WindowTitle = "Quick Edit";
            //ed.StartingFont = new Font("Courier New", 12.0f, FontStyle.Regular);

            //ed.DisplayEditForm(this.panel1);
            //ed.AllowRtf = true;

            //관리자
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));


            if (ReadMode)
            {
                //개인정보패치 251111
                label2.Visible = false;
                tbOt.Visible = false;   


                panel1.Enabled = false;
                this.Text += "(읽기전용)";
            }
            else if (dr.RowState != DataRowState.Detached && curLevel < 5)
            {
                //신규자료가 아니라면 7일간만 편집을 허용한다
                var enableBlock = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.jobreport_editblock);
                if (enableBlock)
                {
                    var writedate = DateTime.Now - DateTime.Parse(dr.pdate);
                    if (writedate.TotalDays > 7)
                    {
                        panel1.Enabled = false;
                        this.Text += "(7일초과)";
                    }
                }
            }

            //신규데이터라면 양식을 처리한다.
            if (copyMOde == false && dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Added)
            {
                //해당 데이터의 메일 양식을 검사해서 데이터를 적용해준다.
                var db = new dsPRJTableAdapters.EETGW_DocuFormTableAdapter();//.  EEEntities();
                var dr0 = db.GetData(FCOMMON.info.Login.gcode, "J0").FirstOrDefault();//.EETGW_DocuForm.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.cate == "J0").FirstOrDefault();
                if (dr0 != null)
                {
                    if (dr0.IsbodyNull() == false) richTextBoxEx1.Rtf = dr0.body;
                }
                db.Dispose();
            }


            bInit = true;
        }

        void RefreshJobTypeFull()
        {
            var jprc = tbJobProcess.Text.Trim();
            if (jprc.isEmpty()) jprc = "N/A";
            if (jprc.Equals("(N/A)")) jprc = "N/A";

            var jgrp = tbJobGrp.Text.Trim();
            var jtype = tbJobType.Text.Trim();

            var fullname = $"{jtype} ← {jgrp}";

            if (jtype.isEmpty())
            {
                cmbTypeFull.Text = "업무형태를 선택하세요";
            }
            else cmbTypeFull.Text = fullname;



            cmbTypeFull.BackColor = jtype.isEmpty() ? Color.HotPink : Color.White;
        }
        //    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 "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.tbProject.Tag = 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.tbJobType.Text = predr["type"].ToString(); //190506

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

                                        if (predr["process"] != DBNull.Value)
                                            tbJobProcess.Text = predr["process"].ToString(); //190506

                                        RefreshJobTypeFull(); //update fullname
                                    }
                                }
                            }
                            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.ToString("yyyy-MM-dd"));
            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;
            }

            //시작일 마감여부
            var smon = this.dtPdate.Value.ToString("yyyy-MM");
            if (FCOMMON.DBM.GetMagamStatus(smon))
            {
                FCOMMON.Util.MsgE("등록일이 속한 월이 마감되었습니다\n마감된 월에는 [추가/변경/삭제] 를 할 수 없습니다");
                return;
            }

            if (tbJobType.Text.ToString() != "휴가" && string.IsNullOrEmpty(this.richTextBoxEx1.Text) == true)
            {
                FCOMMON.Util.MsgE("진행 내용이 없습니다.");
                this.richTextBoxEx1.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 (dr.RowState == DataRowState.Added || dr.RowState == DataRowState.Detached)
            {
                if (FCOMMON.info.Disable_8hourover)
                {
                    var h = Single.Parse(tbHrs.Text);
                    if (h > 8)
                    {
                        FCOMMON.Util.MsgE("근무시간은 8시간을 초과할 수 없습니다. 초과 근무는 [초과시간] 을 사용하세요");
                        tbHrs.Focus();
                        tbHrs.SelectAll();
                        return;
                    }
                }
            }

            if (cmbState.Text.isEmpty())
            {
                AR.UTIL.MsgE("상태를 선택하세요");
                cmbState.Focus();
                return;
            }
            if (tbJobType.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("업무형태를 선택하세요");
                cmbTypeFull.Focus();
                return;
            }
            if (tbJobProcess.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("업무프로세스를 선택하세요");
                tbJobProcess.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.ToString("yyyy-MM-dd"));
            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.ToString("yyyy-MM-dd"), this.richTextBoxEx1.Text, this.richTextBoxEx1.Rtf);
                }
            }

            double hrs2 = 0.0;
            if (double.TryParse(tbHrs.Text, out hrs2) == false)
            {
                FCOMMON.Util.MsgE("근무시간을 숫자로 입력하세요");
                tbHrs.Focus();
                tbHrs.SelectAll();
                return;
            }

            if (double.TryParse(tbOt.Text, out double ot))
            {
                var timeterm = dtOtEnd.Value - dtOtStart.Value;
                if ((timeterm.TotalMinutes + 1) * 60 <= ot)
                {
                    FCOMMON.Util.MsgE($"OT시간이 지정된 시간대보다 부족합니다.\nOT시간정보를 확인하세요\n" +
                        $"\n입력시간범위 : {dtOtStart.Value.ToString("HH:mm:ss")}~{dtOtEnd.Value.ToString("HH:mm:ss")}" +
                        $"\n입력시간(시) : {timeterm.TotalMinutes * 60}");
                    dtOtStart.Focus();
                    return;
                }

                if (ot == 0)
                {
                    dr.SetotNull();
                    dr.SetotStartNull();
                    dr.SetotEndNull();
                }
                else
                {
                    dr.ot = ot;
                    dr.otStart = dtOtStart.Value;
                    dr.otEnd = dtOtEnd.Value;
                }
            }
            else
            {
                dr.SetotNull();
                dr.SetotStartNull();
                dr.SetotEndNull();
            }

            //var MaxVerstion = FCOMMON.DBM.GetMaxVersion();
            //if (string.IsNullOrEmpty(MaxVerstion) == false)
            //{
            //	var curversion = Application.ProductVersion;
            //	var verchk = curversion.CompareTo(MaxVerstion);
            //	if (verchk < 0)
            //	{
            //		//내버젼이 낮다
            //		FCOMMON.Util.MsgE("현재 구 버젼을 사용하고 있습니다.\n업데이트를 진행 하고 사용하시기 바랍니다");
            //	}
            //}
            ////if(hrs2 > 8)
            //{
            //    FCOMMON.Util.MsgE("1일 최대근무시간은 8시간을 초과할 수 없습니다\n초과시간을 사용하세요");
            //    tbHrs.SelectAll();
            //    tbHrs.Focus();
            //    return;
            //}

            this.dr.uid = this.cmbUser.SelectedValue.ToString();
            this.dr.pdate = dtPdate.Value.ToString("yyyy-MM-dd");
            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 = tbJobType.Text.Trim();
            this.dr.process = tbJobProcess.Text.Trim();
            this.dr.jobgrp = tbJobGrp.Text.Trim();
            this.dr.tag = tbTag.Text.Trim();


            if (tbHrs.Text != "") this.dr.hrs = double.Parse(tbHrs.Text);
            else this.dr.hrs = 0;


            if (getKisulInput)
            {
                //기술금액을 계산해야함
                double amt = 0;
                if (float.TryParse(cmb_kisullv.Text, out float price))
                {
                    //var price = FCOMMON.DBM.getCodeFvalue("51", cmb_kisullv.Text);
                    amt = (dr.hrs + dr.ot) * price;
                    this.dr.kisuldiv = cmb_kisuldiv.Text;
                    this.dr.kisullv = cmb_kisullv.Text;
                    this.dr.kisulamt = (Decimal)amt; // Decimal.Parse(textBox1.Text);
                }
                else
                {
                    dr.kisulamt = 0;
                }
                textBox1.Text = amt.ToString();
            }

            //this.dr.description = richTextBox1.Text.Trim();

            //MessageBox.Show(richTextBox1.Text);
            this.dr.description = richTextBoxEx1.Text;
            this.dr.description2 = richTextBoxEx1.Rtf; // ef.DocumentText;//  richTextBox1.Rtf;
            this.bs.EndEdit();

            if (chkManagerAlert.Checked)
            {
                var dlg = FCOMMON.Util.MsgQ("관리자 메일을 전송할까요?\n업무일지 작성 내용이 전달 됩니다");
                if (dlg == DialogResult.Yes)
                {
                    var taMData = new dsMailTableAdapters.MailDataTableAdapter();
                    var taForm = new dsMailTableAdapters.MailFormTableAdapter();// EEEntities();
                    var mf = taForm.GetData(FCOMMON.info.Login.gcode, "MA").FirstOrDefault();//)  .MailForm.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.cate == "MA").FirstOrDefault();
                    if (mf != null)
                    {
                        try
                        {
                            var dtdata = new FPJ0000.dsMail.MailDataDataTable();
                            var mbody = dtdata.NewMailDataRow();
                            mbody.tolist = maildataupdate(mf.tolist);
                            mbody.bcc = maildataupdate(mf.bcc);
                            mbody.cc = maildataupdate(mf.cc);
                            mbody.project = dr.pidx;
                            mbody.gcode = FCOMMON.info.Login.gcode;
                            mbody.cate = mf.cate;
                            mbody.fromlist = "gw@amkor.co.kr";
                            mbody.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                            mbody.subject = maildataupdate(mf.subject);
                            mbody.body = maildataupdate(mf.body);
                            mbody.wuid = FCOMMON.info.Login.no;
                            mbody.wdate = DateTime.Now;
                            dtdata.AddMailDataRow(mbody);
                            taMData.Update(dtdata);
                        }
                        catch (Exception ex)
                        {
                            FCOMMON.Util.MsgE("업무일지 알림 메일 전송 실패" + ex.Message);
                        }
                    }
                    else FCOMMON.Util.MsgE("관리자메일양식 MA가 등록되지 않았습니다. 메일 양식을 확인하세요");
                }

            }

            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        string maildataupdate(string org)
        {
            if (string.IsNullOrEmpty(org)) return string.Empty;
            org = org.Replace("{pname}", tbProject.Text);
            org = org.Replace("{pidx}", tbProjectIndex.Text);
            org = org.Replace("{sdate}", dtPdate.Value.ToString("yyyy-MM-dd"));
            org = org.Replace("{edate}", dtPdate.Value.ToString("yyyy-MM-dd"));
            org = org.Replace("{pdate}", dtPdate.Value.ToString("yyyy-MM-dd"));
            org = org.Replace("{DATE}", dtPdate.Value.ToString("yyyy-MM-dd"));
            org = org.Replace("{NAME}", cmbUser.Text);
            org = org.Replace("{HR}", tbHrs.Text);
            org = org.Replace("{OT}", tbOt.Text);
            org = org.Replace("{PROJECT}", tbProject.Text);
            org = org.Replace("{REMARK}", richTextBoxEx1.Text);
            org = org.Replace("{SENDER}", FCOMMON.info.Login.email);


            return org;
        }



        //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
        //        }

        //    }
        //    chkform_indexchan(sender, e);

        //}

        void chkform_indexchan(object sender, EventArgs e)
        {
            if (tbJobType.Text.isEmpty() == false)
            {
                if (cmbState.Text.isEmpty())
                {
                    UTIL.MsgE("상태가 선택되어 있지 않습니다. 문서서식을 적용하려면 상태를 선택해야 합니다");
                    cmbState.Focus();
                    return;
                }

                //해당 데이터의 메일 양식을 검사해서 데이터를 적용해준다.
                var formname = tbJobType.Text.Trim() + "|" + cmbState.Text.Trim();
                var taDocuForm = new dsPRJTableAdapters.EETGW_DocuFormTableAdapter();// EEEntities();

                //프로젝트 제목 서포트
                var dr0 = taDocuForm.GetByTitle(FCOMMON.info.Login.gcode, "J2", formname).FirstOrDefault();//.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.cate == "J2" && t.title == formname).FirstOrDefault();
                if (dr0 != null)
                {
                    var rtx = new RichTextBox();
                    rtx.Rtf = dr0.body;
                    lbTitleTip.Text = rtx.Text;
                    rtx.Dispose();
                }
                else
                {
                    lbTitleTip.Text = "프로젝트가 있다면 해당 프로젝트 명을 입력한 후 Enter 키를 눌러서 연결 해주세요";
                }

                var dr = taDocuForm.GetByTitle(FCOMMON.info.Login.gcode, "J1", formname).FirstOrDefault();
                if (dr != null)
                {

                    if (String.IsNullOrEmpty(this.richTextBoxEx1.Text))
                    {
                        this.richTextBoxEx1.Rtf = dr.body;
                    }
                    else
                    {
                        //뭔가 자료가 있는가?                            
                        var header = string.Empty;


                        var rt = new RichTextBoxEx.RichTextBoxEx();
                        rt.Rtf = dr.body;
                        if (rt.Text.Length > 10) header = rt.Text.Substring(0, 10).Trim();
                        else header = rt.Text.Trim();
                        rt.Dispose();

                        if (this.richTextBoxEx1.Text.StartsWith(header) == false)
                        {
                            //if (FCOMMON.Util.MsgQ("등록된 작성 양식이 있습니다. 적용할까요?") == DialogResult.Yes)
                            {
                                var oldtext = this.richTextBoxEx1.Text;
                                this.richTextBoxEx1.Rtf = dr.body;
                                if (String.IsNullOrEmpty(this.richTextBoxEx1.Text) == false)
                                {
                                    this.richTextBoxEx1.rtb.AppendText("\n\n");
                                    this.richTextBoxEx1.rtb.SelectionLength = 1;
                                    this.richTextBoxEx1.rtb.SelectionStart = this.richTextBoxEx1.rtb.TextLength;
                                    this.richTextBoxEx1.rtb.ForeColor = Color.Black;
                                    this.richTextBoxEx1.rtb.AppendText(oldtext);
                                }
                                //this.richTextBoxEx1.Text += oldtext;

                                //this.richTextBoxEx1.Text += oldtext;

                            }
                        }
                    }
                }

            }
        }

        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, 금월 초과시간 : {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(); ;
        }

        private void tbOt_Validated(object sender, EventArgs e)
        {
            if (double.TryParse(tbOt.Text, out double ot))
            {
                if (ot != 0)
                {

                    dtOtStart.Enabled = true;
                    dtOtEnd.Enabled = true;

                    //신규데이터라면 자동으로 시간을 설정해준다
                    if (dr.RowState == DataRowState.Added || dr.RowState == DataRowState.Detached)
                    {
                        if (dtOtStart.Value == dtOtEnd.Value)
                        {
                            dtOtStart.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd" + " 18:00:00"));
                            dtOtEnd.Value = dtOtStart.Value.AddHours(ot);
                        }
                    }
                }
                else
                {
                    dtOtStart.Enabled = false;
                    dtOtEnd.Enabled = false;
                }

            }
            else
            {
                dtOtStart.Enabled = false;
                dtOtEnd.Enabled = false;

            }
        }

        private void tbProjectIndex_Click(object sender, EventArgs e)
        {
            if (int.TryParse(tbProjectIndex.Text, out int pidx))
            {
                if (pidx < 1) return;

                var ta = new dsPRJTableAdapters.ProjectsTableAdapter();
                var dr = ta.GetbyIDX(pidx).First();
                var f = new fProjectData(dr, false);
                f.Show();
                //if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //{
                //	this.Validate();
                //	dr.EndEdit();
                //	try
                //	{
                //		var cnt = ta.Update(this.dsPRJ.Projects);//.UpdateAll(this.dsMSSQL.Projects);
                //		dsPRJ.Projects.AcceptChanges();
                //		if(cnt != 1)
                //                    {
                //			FCOMMON.Util.MsgE("저장 실패");
                //                    }
                //	}
                //	catch (Exception ex)
                //	{
                //		FCOMMON.Util.MsgE(ex.Message);
                //	}
                //}
            }
        }

        private void cmbRequest_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cmbType_Click(object sender, EventArgs e)
        {
            var jobtype = tbJobType.Text.Trim();
            var jobprc = tbJobProcess.Text.Trim();
            var jobgrp = tbJobGrp.Text.Trim();
            var fullname = $"{jobprc}|{jobgrp}|{jobtype}";
            var auth = FCOMMON.info.Login.level >= 5;
            using (var f = new FPJ0000.JobReport_.fJobProcessSelect(fullname, auth))
                if (f.ShowDialog() == DialogResult.OK)
                {
                    //선택되면해야할일들
                    var data = f.SelectedValue.Split('|');
                    if (data.Length != 3) return;
                    var prc = data[0].Trim();
                    var grp = data[1].Trim();
                    var itm = data[2].Trim();
                    if (grp.isEmpty() || grp.Equals("(N/A)")) grp = "N/A";
                    this.tbJobType.Text = itm;
                    this.tbJobGrp.Text = grp;
                    this.tbJobProcess.Text = prc;
                    RefreshJobTypeFull();

                    chkform_indexchan(null, null);
                }
        }
    }
}
