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;
using util = FCOMMON.Util;

namespace FPJ0000
{
    public partial class fJobReport : FCOMMON.fBase
    {
        int curLevel = 0;// Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));
        string fn_fpcolsize = "";
        public fJobReport()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsMSSQL.JobReport.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;

            dtSD.KeyDown += dtSD_KeyDown;
            dtED.KeyDown += dtSD_KeyDown;
             curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        Boolean binit = false;

        void UpdateUserList()
        {
            //담당자목록 - 사용자목록으로 처리한다.  
            this.cmbUser.Items.Clear();
            this.cmbUser.Items.Add("-- 전체 --");
            var taUserList = new dsReportTableAdapters.ProcessUserListTableAdapter();

            var prclist = this.tbProcess.Tag as List<string>;
            if (prclist.Count < 1)
            {
                var processStr = "%";
                var dtUserList = taUserList.GetData(processStr, FCOMMON.info.Login.gcode);
                foreach (dsReport.ProcessUserListRow dr in dtUserList.OrderBy(t=>t.name))
                {
                    if (String.IsNullOrEmpty(dr.outdate) == false)
                    {
                        var odt = DateTime.Parse(dr.outdate);
                        if (odt <= DateTime.Now) continue; //퇴사자제외  211221
                    }
                    string cmbdata = string.Format("{1}({0})", dr.id, dr.name);
                    this.cmbUser.Items.Add(cmbdata);
                }
            }
            else
            {
                foreach (var prc in prclist)
                {
                    var processStr = prc;// cmbProcess.Text;
                    var dtUserList = taUserList.GetData(processStr, FCOMMON.info.Login.gcode);
                    foreach (dsReport.ProcessUserListRow dr in dtUserList.OrderBy(t=>t.name))
                    {
                        if (String.IsNullOrEmpty(dr.outdate) == false)
                        {
                            var odt = DateTime.Parse(dr.outdate);
                            if (odt <= DateTime.Now) continue; //퇴사자제외  211221
                        }
                        string cmbdata = string.Format("{1}({0})", dr.id, dr.name);
                        this.cmbUser.Items.Add(cmbdata);
                    }
                }

            }



        }

        private bool getKisulInput
        {
            get
            {
                return FCOMMON.Util.getBit(
                FCOMMON.info.Login.gpermission,
                (int)FCOMMON.eGroupPermission.jobreport_kisul);
            }
        }
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.dtSD.Text = DateTime.Now.ToString("yyyy-MM-01");
            var sdate = DateTime.Parse(dtSD.Text);
            this.dtED.Text = sdate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");

            //공정목록
            //var taProc = new dsReportTableAdapters.ProcessListTableAdapter();
            //var dtProcList = taProc.GetData(FCOMMON.info.Login.gcode);
            //cmbProcess.Items.Clear();
            //cmbProcess.Items.Add("--전체--");
            //foreach (dsReport.ProcessListRow dr in dtProcList)
            //{
            //    cmbProcess.Items.Add(dr.processs);
            //}
            //cmbProcess.Text = FCOMMON.info.Login.process;
            //if (cmbProcess.SelectedIndex < 0) cmbProcess.SelectedIndex = 0; //공정이 없는 사람은 전체보기로 함

            tbProcess.Text = FCOMMON.info.Login.process;
            tbProcess.Tag = new List<string>(new string[] { FCOMMON.info.Login.process });

            //담당자목록 - 사용자목록으로 처리한다.    
            string namestr = string.Format("{0}({1})", FCOMMON.info.Login.nameK, FCOMMON.info.Login.no);
            // if (FCOMMON.info.Login.no == "dev") namestr = "김치균(395552)";
            // this.cmbUser.Items.Add(namestr);
            UpdateUserList(); //현재사용자의 이름을 반환한다
            cmbUser.Text = namestr;

            if (cmbUser.SelectedIndex < 0)
            {
                //내 아이템이 없다면, 목록을 추가해서 선택해줘야 한다
                this.cmbUser.Items.Add(namestr);
                cmbUser.Text = namestr;
            }


            //var userList = FCOMMON.DBM.getGroupList("name + '(' + id + ')'", "Users", "[level] > 0 and [level] < 10", false, false);
            //foreach (var user in userList)
            //{
            //    this.cmbUser.Items.Add(user);
            //}


            //state list
            //var stList = FCOMMON.DBM.getCodeList("05");
            //this.cmbState.Items.Clear();
            //cmbState.Items.Add("-- All --");
            //// cmbState.Items.Add("-- incomplete --");
            //foreach (var item in stList)
            //    cmbState.Items.Add(item);
            //this.cmbState.SelectedIndex = 0;


            //일반사용자의경우에는 상태를 변경하지 못한다.
          
            if (curLevel >= 5)
            {
                btSave.Visible = true;
                btImport.Visible = true;
            }
            else
            {
                btImport.Visible = false;
                btSave.Visible = false;
                //btViewDel.Visible = false;
                fpSpread1.EditMode = false;
                //fpSpread1.Sheets[0].SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Row;
                
                fpSpread1.EditModePermanent = false;
                fpSpread1.EditModeReplace = false;

                foreach (FarPoint.Win.Spread.Column col in fpSpread1.ActiveSheet.Columns)
                    col.Locked = true;
            }
            //fpSpread1.SelectionBlockOptions = FarPoint.Win.Spread.SelectionBlockOptions.Cells;
            fpSpread1.ActiveSheet.SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Cell;
            fpSpread1.ActiveSheet.SelectionPolicy = FarPoint.Win.Spread.Model.SelectionPolicy.MultiRange;
            fpSpread1.ActiveSheet.OperationMode = FarPoint.Win.Spread.OperationMode.Normal;



            //210930-
            if (FCOMMON.info.NotShowJobReportview)
                this.splitContainer1.Panel2Collapsed = true;

            refreshData();
            binit = true;


        }

        private void cmbProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (binit == false) return;
            UpdateUserList();
        }
        private void cmbProcess_Click(object sender, EventArgs e)
        {

        }
        void RefreshTime()
        {
            lbTime.Text = "--h";

            //사용자번호추적
            if (cmbUser.Text.Trim() == "")
            {
                //FCOMMON.Util.MsgE("담당자가 선택되지 않았습니다.");
                return;
            }
            if (cmbUser.Text.IndexOf("(") == -1 || cmbUser.Text.IndexOf(")") == -1)
            {
                // FCOMMON.Util.MsgE("담당자 번호를 확인할 수 없습니다.(문의 T.8567)");
                return;
            }
            string request = cmbUser.Text.Substring(cmbUser.Text.LastIndexOf('(') + 1);
            request = request.Substring(0, request.Length - 1);

            float work, ot;
            int total;
            FCOMMON.DBM.getWorkTime(request, this.dtSD.Text.Substring(0, 7), out work, out total, out ot);
            lbTime.Text = string.Format(" {0}h/{2}h, OT:{1}h", work, ot, total);
        }
        void dtSD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            var tb = sender as ToolStripTextBox;
            var input = tb.Text.Trim();
            if (input == "") tb.Text = DateTime.Now.ToString("yyyy-MM-dd");
            else
            {
                string dt = string.Empty;
                if (!util.MakeDateString(input, out dt))
                {
                    FCOMMON.Util.MsgE("입력값이 올바르지 않습니다.");
                    tb.SelectAll();
                    tb.Focus();
                    return;
                }
                else
                {
                    tb.Text = dt;
                }
            }
            if (tb == dtSD)
            {
                dtED.Focus();
                dtED.SelectAll();
            }
            else
            {
                btSearch.PerformClick();
                tb.SelectAll();
            }
        }

        void refreshData(bool tagonly = false)
        {
            // string state = "%";
            // if (cmbState.SelectedIndex > 0) state = cmbState.Text.Split(',')[0].Substring(1);

            //사용자번호추적
            if (cmbUser.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("담당자가 선택되지 않았습니다.");
                return;
            }
            if (cmbUser.SelectedIndex > 0 && (cmbUser.Text.IndexOf("(") == -1 || cmbUser.Text.IndexOf(")") == -1))
            {
                FCOMMON.Util.MsgE("담당자 번호를 확인할 수 없습니다.(문의 T.8567)");
                return;
            }



         




            string request = cmbUser.Text.Substring(cmbUser.Text.LastIndexOf('(') + 1);
            request = request.Substring(0, request.Length - 1);
            if (cmbUser.SelectedIndex == 0) request = "%"; 


            //사용자 목록다중선택으로 인해 처리
            var sql = "SELECT gcode, idx, pidx, pdate, uid, requestpart, package, status, type, description," +
                        "remark, hrs, import, wuid, wdate, dbo.getUserName(uid) AS username, projectName, ot," +
                        "dbo.getWorkWeek(pdate) AS ww, process, isnull(jobgrp,'') as jobgrp, tag," +
                        "dbo.getCodeSValue(gcode, '15', type) AS svalue," +
                        "otStart, otEnd, autoinput, kisullv, kisuldiv, kisulamt, ot2, otwuid, ottime";
            sql += " FROM JobReport";
            sql += " WHERE (gcode = @gcode) and (pdate BETWEEN @sd AND @ed)";
            if (request != "%")
            {
                //사용자가 지정되어있다
                sql += $" AND uid = '{request}'";
            }
            else
            {
                //전체사용자가 지정되어있다. 해당하는 사용자 목록에서만 취한다.
                var userlist = new List<string>();
                for (int i = 1; i < cmbUser.Items.Count; i++) //0번요소는 전체이다
                {
                    var userinfo = cmbUser.Items[i].ToString();
                    var userno = userinfo.Substring(userinfo.LastIndexOf('(') + 1);
                    userno = userno.Substring(0, userno.Length - 1);
                    userlist.Add(userno);
                }
                sql += " and uid in ('" + string.Join("','", userlist) + "')";
            }

            if (tagonly) sql += " and isnull(tag,'') <> ''";
            sql += " ORDER BY pdate DESC";

            var cmd = new System.Data.SqlClient.SqlCommand(sql, ta.Connection);
            cmd.Parameters.Add("sd", SqlDbType.VarChar).Value = dtSD.Text;
            cmd.Parameters.Add("ed", SqlDbType.VarChar).Value = dtED.Text;
            cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode;
            var da = new System.Data.SqlClient.SqlDataAdapter(cmd);

            dsMSSQL.JobReport.Clear();
            dsMSSQL.JobReport.AcceptChanges();
            da.Fill(this.dsMSSQL.JobReport);
            dsMSSQL.JobReport.AcceptChanges();

            //if (tagonly == false)
            //    this.ta.Fill(this.dsMSSQL.JobReport, dtSD.Text, dtED.Text, request, FCOMMON.info.Login.gcode);
            //else
            //    this.ta.FillByTagOnly(this.dsMSSQL.JobReport, dtSD.Text, dtED.Text, request, FCOMMON.info.Login.gcode);


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

            if ( request != FCOMMON.info.Login.no && curLevel < 5)
            {
                this.fpSpread1_Sheet1.Columns["ot"].Visible = false;
            }
            else 
            {
                this.fpSpread1_Sheet1.Columns["ot"].Visible = true;
            }




            RefreshTime();
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            FormattingData();

            if (getKisulInput == false)
            {
                fpSpread1.ActiveSheet.Columns["kisuldiv"].Visible = false;
                fpSpread1.ActiveSheet.Columns["kisullv"].Visible = false;
                fpSpread1.ActiveSheet.Columns["kisulamt"].Visible = false;
            }

        }
        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var prjindex = this.fpSpread1.ActiveSheet.Columns["pidx"].Index;
            var stsindex = this.fpSpread1.ActiveSheet.Columns["status"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var state = this.fpSpread1.ActiveSheet.GetValue(i, prjindex);
                string stateStr = string.Empty;
                if (state != null) stateStr = state.ToString();

                var status = this.fpSpread1.ActiveSheet.GetValue(i, stsindex);
                string statusStr = string.Empty;
                if (status != null) statusStr = status.ToString();

                //프로젝트여부에따라 회색
                switch (stateStr.ToLower())
                {
                    case "-1":
                        this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.WhiteSmoke;
                        break;
                    default:
                        this.fpSpread1.ActiveSheet.Rows[i].BackColor = SystemColors.Window;
                        break;
                }
                if (statusStr.EndsWith("완료"))
                {
                    this.fpSpread1.ActiveSheet.Cells[i, stsindex].BackColor = Color.Lime;
                }
                else
                {
                    this.fpSpread1.ActiveSheet.Cells[i, stsindex].BackColor = Color.Gold;
                }
            }
            this.fpSpread1.ResumeLayout();
        }
        int funcSave()
        {
            int cnt = 0;
            this.Validate();
            this.bs.EndEdit();
            try
            {
                cnt = this.tam.UpdateAll(this.dsMSSQL);
                FormattingData();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }
            return cnt;
        }

        private void projectsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            funcSave();

        }
        void Projects_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["pdate"] = DateTime.Now.ToString("yyyy-MM-dd");
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["status"] = "진행 완료";//other
            e.Row["uid"] = FCOMMON.info.Login.no; //이름을 직접 기록
            e.Row["hrs"] = 8.0;
            e.Row["ot"] = 0.0;
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void partListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;
            var f = new fPartList(dr.idx);
            f.MdiParent = this.MdiParent;
            f.Show();
        }


        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
                this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                col.Width = 100;
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void btSearch_Click(object sender, EventArgs e)
        {

        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            //사용자목록처리
            var namestr = string.Format("{0}({1})", FCOMMON.info.Login.nameK, FCOMMON.info.Login.no); ;
            if (FCOMMON.info.Login.no == "dev") namestr = "김치균(395552)";
            this.cmbUser.Text = namestr;
            refreshData();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var newdr = this.dsMSSQL.JobReport.NewJobReportRow();
            newdr.status = "진행 완료";
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday ||
                DateTime.Now.DayOfWeek == DayOfWeek.Saturday) newdr.hrs = 0;

            var f = new JobReport_.fJobReport_Add(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.dsMSSQL.JobReport.AddJobReportRow(newdr);
                int cnt = this.ta.Update(newdr);
                newdr.AcceptChanges();
                FormattingData();
                if (cnt != 1)
                    FCOMMON.Util.MsgE("자료가 추가되지 않았습니다.\n\n잠시 후 다시 시도하세요");
            }
            else newdr.Delete();
        }

        private void btFind_Click(object sender, EventArgs e)
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.Trim() == "")
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    var collist = new string[] { "requestpart", "package", "projectname", "process", "[type]", "description", "tag" };
                    string filter = ""; // "itemna like ? or package like ? or projectname like ? or process like ? or [type] like ? or description like ?";
                    foreach (var col in collist)
                    {
                        if (filter != "") filter += " or ";
                        filter += col + " like ?";
                    }
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            funcEdit();
        }

        void funcEdit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.JobReportRow;

            bool ReadMod = false;
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));

            if (dr.uid != FCOMMON.info.Login.no && curLevel < 5)
            {
                ReadMod = true;
                //FCOMMON.Util.MsgE("타인의 자료는 추가/변경/삭제 할 수 없습니다.");
                //return;
            }
            else if (dr.ot > 0 && dr.ot2 > 0)
            {
                //util.MsgE("연장/휴일 근무가 관리자에의해 확정된 상태이므로 값을 변경할 수 없습니다");
                //ReadMod = true;
            }

            //ot데이터가잇고 관리자 확정되엇다면 처리하지 못한다

            var f = new JobReport_.fJobReport_Add(dr, false, ReadMod);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (dr.RowState != DataRowState.Unchanged && ReadMod == false)
                {
                    int cnt = this.ta.Update(dr);
                    dr.AcceptChanges();
                    FormattingData();
                }
            }
            else if (ReadMod == false) dr.RejectChanges();
        }

        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "jobreport.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                var dlg = FCOMMON.Util.MsgQ("다음 파일이 생성 되었습니다.\n\n" + sd.FileName + "\n파일을 확인 할까요?");
                if (dlg == DialogResult.Yes)
                    util.RunExplorer(sd.FileName);
            }
        }

        private void btCopy_Click(object sender, EventArgs e)
        {
            funcCopy(); //190509
        }
        void funcCopy()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.JobReportRow;

            //현재 데이터를 입력하여 신규 추가를 한다.
            var newdr = this.dsMSSQL.JobReport.NewJobReportRow();
            FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.uid = FCOMMON.info.Login.no;
            //newdr.description = "";
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd"); //190509
            newdr.idx = -1;
            //newdr.hrs = 8.0;
            newdr.SethrsNull();
            newdr.ot = 0.0;
            newdr.status = string.Empty;
            newdr.Setot2Null();
            newdr.SetotwuidNull();
            newdr.SetotReasonNull();
            newdr.SetottimeNull();

            newdr.SetotEndNull();
            newdr.SetotStartNull();

            newdr.EndEdit();

            //var newdr = this.dsMSSQL.JobReport.NewJobReportRow();
            JobReport_.fJobReport_Add f = new JobReport_.fJobReport_Add(newdr, true);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.dsMSSQL.JobReport.AddJobReportRow(newdr);
                this.ta.Update(newdr);
                newdr.AcceptChanges();
            }
            else newdr.Delete();
        }

        private void btDel_Click(object sender, EventArgs e)
        {
            funcDelete();
        }
        void funcDelete()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.JobReportRow;
            if (dr.uid != FCOMMON.info.Login.no && FCOMMON.info.Login.level < 5)
            {
                FCOMMON.Util.MsgE("타인의 자료는 추가/변경/삭제 할 수 없습니다.");
                return;
            }


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


            if (ta.CheckOt2Input(dr.gcode, dr.idx) > 0 && FCOMMON.info.Login.level < 5)
            {
                FCOMMON.Util.MsgE("연장/휴일 근무 시간이 승인된 자료이므로 삭제할 수 없습니다");
                return;
            }
            var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            dr.Delete();
            try
            {
                this.ta.Update(dr);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("삭제실패\n\n" + ex.Message);
            }
        }
        private void lbStt_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fSelectDay(DateTime.Parse(dtSD.Text));
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            var sdDate = f.dtPick.SelectionStart;//  DateTime.Parse(DateTime.Now.ToString("yyyy-") + f.selectmon.ToString() + "-01");
            dtSD.Text = sdDate.ToString("yyyy-MM-dd");
            if (f.dtPick.SelectionStart.ToString("yyyy-MM-dd") == f.dtPick.SelectionEnd.ToString("yyyy-MM-dd"))
                dtED.Text = sdDate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            else
                dtED.Text = f.dtPick.SelectionEnd.ToString("yyyy-MM-dd");
            refreshData();
        }

        private void btReport_Click(object sender, EventArgs e)
        {

        }

        private void cmbUser_Click(object sender, EventArgs e)
        {

        }

        private void cmbUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshTime();
        }

        private void 복사ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcCopy();
        }

        private void 편집ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcEdit();
        }

        private void 삭제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcDelete();
        }

        private void btReportDay_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {

        }

        private void btSearch_ButtonClick(object sender, EventArgs e)
        {
            refreshData();
        }

        private void 태그자료만조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            refreshData(true);
        }

        private void toolStripLabel4_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fSelectDay(DateTime.Parse(dtED.Text));
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            dtED.Text = f.dtPick.SelectionStart.ToString("yyyy-MM-dd");
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            var oldlist = (List<string>)tbProcess.Tag;
            var f = new JobReport_.fSelectProcess(oldlist.ToArray());
            if (f.ShowDialog() == DialogResult.OK)
            {
                tbProcess.Tag = f.values;
                tbProcess.Text = string.Join(",", f.values);
                UpdateUserList();
            }

        }

        private void k5DailyFormToolStripMenuItem_Click(object sender, EventArgs e)
        {

            var f = new JobReport_.rK5Dailyform();
            f.Show();
        }

        private void wFDailToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f2 = new JobReport_.K5Dailyform();
            f2.Show();
        }

        private void btImport_Click(object sender, EventArgs e)
        {
            var f = new FPJ0000.JobReport_.fJobReportImport();
            f.ShowDialog();
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {

        }

        private void btOpenFolder_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.JobReportRow;
            if (dr != null && (dr.RowState == DataRowState.Modified || dr.RowState == DataRowState.Unchanged))
            {
                Util.openjobreportitem(dr.idx);
            }
            else FCOMMON.Util.MsgE("자료가 저장되기 전에는 폴더를 확인할 수 없습니다.\r\n자료를 저장한 후 다시 시도하세요");
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            this.splitContainer1.Panel2Collapsed = !this.splitContainer1.Panel2Collapsed;
            richTextBox1.Visible = true;
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            var sdo = DateTime.Parse(dtSD.Text);
            var sd = DateTime.Parse(sdo.AddMonths(-1).ToString("yyyy-MM-01"));
            var ed = sd.AddMonths(1).AddDays(-1);
            dtSD.Text = sd.ToString("yyyy-MM-dd");
            dtED.Text = ed.ToString("yyyy-MM-dd");

        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            var sdo = DateTime.Parse(dtSD.Text);
            var sd = DateTime.Parse(sdo.AddMonths(1).ToString("yyyy-MM-01"));
            var ed = sd.AddMonths(1).AddDays(-1);
            dtSD.Text = sd.ToString("yyyy-MM-dd");
            dtED.Text = ed.ToString("yyyy-MM-dd");
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rK5Dailyform();
            f.Show();
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            if(curLevel < 5)
            {
                AR.UTIL.MsgE("사용 권한이 없습니다");// util.MsgE("");
                return;
            }
            var f = new JobReport_.rJobReportUser();
            f.Show();
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            //string request = cmbUser.Text.Substring(cmbUser.Text.LastIndexOf('(') + 1);
            //request = request.Substring(0, request.Length - 1);
            //string name = cmbUser.Text.Substring(0, cmbUser.Text.IndexOf('('));
            var f = new JobReport_.fJobChartMenu();
            f.ShowDialog();
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReportDay(dtSD.Text);
            f.Show();
        }

        private void toolStripButton14_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReport();
            f.Show();
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReportPrj(dtSD.Text);
            f.Show();
        }

        private void toolStripButton3_Click_1(object sender, EventArgs e)
        {
            var f = new JobReport_.fProjectConnect(dtSD.Text, dtED.Text);
            f.ShowDialog();
        }

        private void 개인별프로젝트스케쥴현황ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReportPrjSche();
            f.Show();
        }

        private void toolStripButton5_Click_1(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReportType();
            f.Show();
        }

        private void qlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.JobReportRow;

            var f = new FCOMMON.fSelectDays(DateTime.Now, DateTime.Now);
            if (f.ShowDialog() != DialogResult.OK) return;

            var sd = f.dts.SelectionStart;
            var ed = f.dte.SelectionEnd;

            DateTime d = sd;
            var ucnt = 0;
            while (true)
            {
                //종료일보다 작으면 넘어간다
                if (d > ed) break;

                if (d.DayOfWeek == DayOfWeek.Sunday || d.DayOfWeek == DayOfWeek.Saturday)
                {
                    d = d.AddDays(1);
                    continue;
                }

                //현재 데이터를 입력하여 신규 추가를 한다.
                var newdr = this.dsMSSQL.JobReport.NewJobReportRow();
                FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
                newdr.wdate = DateTime.Now;
                newdr.wuid = FCOMMON.info.Login.no;
                newdr.uid = FCOMMON.info.Login.no;

                newdr.pdate = d.ToString("yyyy-MM-dd"); //190509
                newdr.idx = -1;
                newdr.hrs = 8.0;
                newdr.ot = 0.0;

                newdr.Setot2Null();
                newdr.SetotwuidNull();
                newdr.SetotReasonNull();
                newdr.SetottimeNull();
                newdr.SetotEndNull();
                newdr.SetotStartNull();

                newdr.EndEdit();
                this.dsMSSQL.JobReport.AddJobReportRow(newdr);

                ucnt += ta.Update(dsMSSQL.JobReport);
                d = d.AddDays(1);
            }

            util.MsgI($"토/일은 제외되었습니다. 기타 휴일은 적용되지 않았으니 데이터를 확인하세요\nupdate count : {ucnt}");


        }

        private void 상태일괄변경ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //상태일괄변경

            var selected = this.fpSpread1_Sheet1.GetSelections();   //선택된 개체확인
            List<int> rows = new List<int>();
            foreach (var item in selected)
            {
                for (int i = item.Row; i < item.Row + item.RowCount; i++)
                {
                    if (rows.Contains(i) == false)
                    {
                        if (fpSpread1_Sheet1.IsRowBound(i))
                        {
                            rows.Add(i);
                        }
                    }

                }
            }

            //이대상의 실제 데이터베이스 인덱스값을 생성해서 폼에 전송한다.
            var codlist = DBM.getCodeList("12");

            var f = new FCOMMON.fLOV(codlist.Select(t => t.Value).ToArray());
            if (f.ShowDialog() != DialogResult.OK) return;

            if (f.SelectedValue.isEmpty()) return;

            var colstat = fpSpread1_Sheet1.Columns["status"];
            var colidx = fpSpread1_Sheet1.Columns["idx"];
            var value = f.SelectedValue;

            foreach (var rowindex in rows)
            {
                var idx = fpSpread1_Sheet1.Cells[rowindex, colidx.Index].Value;
                var dr = this.dsMSSQL.JobReport.Where(t => t.idx == (int)idx).FirstOrDefault();
                dr["status"] = value;
                dr.EndEdit();

            }
            this.Validate();
            this.bs.EndEdit();
            if (btSave.Visible == false)
            {
                var cnt = funcSave();
                AR.UTIL.MsgI($"{cnt}건의 자료가 업데이트 되었습니다");
            }
            else
            {
                FCOMMON.Util.MsgI($"{rows.Count} 건의 자료가 변경되었습니다\n저장 버튼을 누르면 적용 됩니다\n취소하려면 새로고침을 누르세요");
            }

        }

        private void fpSpread1_CellClick(object sender, FarPoint.Win.Spread.CellClickEventArgs e)
        {

        }
    }
}
