using FarPoint.Win.Spread;
using FPJ0000.OtConfirm;
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 fOTConfirm : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fOTConfirm()
        {
            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;

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        Boolean binit = false;

        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 = DateTime.Now.ToString("yyyy-MM-dd");// sdate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            this.dtSD.Text = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");

            //공정목록
            // var taProc = new dsReportTableAdapters.ProcessListTableAdapter();
            var dtProcList = FCOMMON.DBM.GroupUserProcessList();//taProc.GetData(FCOMMON.info.Login.gcode);
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.otconfirm));
            //cmbProcess.Items.Clear();
            //cmbProcess.Items.Add("--전체--");



            List<String> fprclist = new List<string>();
            foreach (var dr in dtProcList)
            {
                fprclist.Add(dr);
            }
            tbProcess.Tag = fprclist.ToArray();
            tbProcess.Text = string.Join(",", fprclist.ToArray());

            //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(); //현재사용자의 이름을 반환한다


            btConf.Visible = curLevel >= 5;
            //btConfAll.Visible = curLevel >= 5;


            this.dv1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            if (curLevel >= 5)
            {
                //dv1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
                if (cmbUser.Items.Count > 0)
                    cmbUser.SelectedIndex = 0;
            }
            else
            {
                cmbUser.Text = namestr;
                //dv1.EditMode = DataGridViewEditMode.EditProgrammatically;
            }


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

            if (curLevel < 5)
            {
                toolStripButton4.Enabled = false;
                cmbUser.Enabled = false;
                tbProcess.Enabled = false;
            }
                


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


                //일반사용자의경우에는 상태를 변경하지 못한다.


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

            refreshData();
            binit = true;


        }

        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 == null || prclist.Count < 1)
            {
                var processStr = "%";
                var dtUserList = taUserList.GetData(processStr, FCOMMON.info.Login.gcode);
                foreach (dsReport.ProcessUserListRow dr in dtUserList.OrderBy(t => t.name))
                {
                    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))
                    {
                        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 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()
        {
            // 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 = "%"; //전체검색 201028 - chi(임현대)


            //사용자 목록다중선택으로 인해 처리
            var sql = "SELECT *, dbo.getUserName(uid) AS username,  dbo.getWorkWeek(pdate) AS ww, dbo.getCodeSValue(gcode, '15',type) AS svalue, dbo.IsHoliday(pdate) as FreeDay,dbo.[GetWeekName](pdate) as WeekName";
            sql += " FROM JobReport";
            sql += " WHERE (pdate BETWEEN @sd AND @ed) AND(gcode = @gcode)";
            sql += " and isnull(ot,0) > 0";
            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) + "')";
            }


            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();
            da.Fill(this.dsMSSQL.JobReport);
            dsMSSQL.JobReport.AcceptChanges();

            RefreshTime();


        }

        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 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 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 cmbUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshTime();
        }

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

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

        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 = (string[])tbProcess.Tag;
            var f = new JobReport_.fSelectProcess(oldlist);
            if (f.ShowDialog() == DialogResult.OK)
            {
                tbProcess.Tag = f.values;
                tbProcess.Text = string.Join(",", f.values);
                UpdateUserList();
            }

        }

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

        private void arDatagridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //전체승인
            using (var f = new fOTConfirmValue())
            {
                if (f.ShowDialog() != DialogResult.OK) return;
            }


            var dlg = util.MsgQ("미 입력된 승인시간을 일괄 입력할까요?\n휴일에는 1.5x 가 적용 됩니다");
            if (dlg != DialogResult.Yes) return;

            var sb = new System.Text.StringBuilder();
            foreach (dsPRJ.JobReportRow dr in this.dsMSSQL.JobReport)
            {
                if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached) continue;
                if (dr.ot2 == 0)
                {

                    if (dr.FreeDay) dr.ot2 = dr.ot * 1.5;
                    else dr.ot2 = dr.ot;

                    sb.Append($"{dr.username}:{dr.uid} 요청:{dr.ot},승인:{dr.ot2},비고:일괄");
                }
                dr.EndEdit();
            }

            this.Validate();
            this.bs.EndEdit();
            try
            {
                var cnt = ta.Update(this.dsMSSQL.JobReport);
                dsMSSQL.JobReport.AcceptChanges();
                util.MsgI($"{cnt}건의 자료가 저장되었습니다");
                FCOMMON.DBM.InsertLog("OTCONFIRM", sb.ToString());
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            List<dsPRJ.JobReportRow> rows = new List<dsPRJ.JobReportRow>();
            List<int> rowindex = new List<int>();
            foreach (DataGridViewCell cell in dv1.SelectedCells)
            {
                if (cell.RowIndex < 0 || cell.ColumnIndex < 0) continue;
                var drItem = ((DataRowView)(dv1.Rows[cell.RowIndex].DataBoundItem)).Row as dsPRJ.JobReportRow;
                if (rows.Contains(drItem) == false) rows.Add(drItem);
                if (rowindex.Contains(cell.RowIndex) == false) rowindex.Add(cell.RowIndex);
            }

            //데이터를 외부 폼에 전송하여 값을 셋팅해온다
            using (var f = new OtConfirm.fOTConfirmOK(rows.ToArray()))
            {
                if (f.ShowDialog() == DialogResult.OK)
                {
                    foreach (var row in rows)
                        row.EndEdit();

                    try
                    {
                        var cnt = ta.Update(rows.ToArray());
                        foreach (var row in rows)
                            row.AcceptChanges();

                        util.MsgI($"{cnt}건의 자료가 저장되었습니다");
                        foreach (var dr in rows)
                        {
                            FCOMMON.DBM.InsertLog("OTCONFIRM", $"{dr.username}:{dr.uid},요청:{dr.ot},승인:{dr.ot2},관리자비고:{dr.otReason}");
                        }
                    }
                    catch (Exception ex)
                    {
                        FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
                    }
                }
            }
        }

        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 btConfAll_CheckStateChanged(object sender, EventArgs e)
        {

        }

        private void 목록내보내기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var sd = new SaveFileDialog())
            {
                sd.Filter = "콤마로 분리된 파일|*.csv";
                sd.FilterIndex = 0;
                if (sd.ShowDialog() != DialogResult.OK) return;
                var fn = dv1.ExportData(sd.FileName);

                var dlg = AR.UTIL.MsgQ("생성된 파일을 확인할까요?");
                if (dlg != DialogResult.Yes) return;

                AR.UTIL.RunExplorer(fn);

            }
            
        }
    }
}