using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;
using util = FCOMMON.Util;

namespace FPJ0000
{
    public partial class fHolyRequest : FCOMMON.fBase
    {
        int curLevel = 0;
        string fn_fpcolsize = "";
        public fHolyRequest()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dSKuntae.EETGW_HolydayRequest.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;

            dtSD.KeyDown += dtSD_KeyDown;
            dtED.KeyDown += dtSD_KeyDown;

            //관리자승인용 콤보박스 구성
            var dtCmbCF = new DataTable();
            dtCmbCF.Columns.Add("DP", typeof(String));
            dtCmbCF.Columns.Add("VAL", typeof(Int32));
            dtCmbCF.Rows.Add(new object[] { "선택안함", 0 });
            dtCmbCF.Rows.Add(new object[] { "승인", 1 });
            dtCmbCF.Rows.Add(new object[] { "거절", 2 });
            cmbCf.DataSource = dtCmbCF;
            cmbCf.DisplayMember = "DP";
            cmbCf.ValueMember = "VAL";
            dv1.EditMode = DataGridViewEditMode.EditProgrammatically;
            curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.holyreq));

        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        //Boolean binit = false;

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();

            this.dtED.Text = DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd");// sdate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            this.dtSD.Text = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");

            this.dv1.EditMode = DataGridViewEditMode.EditProgrammatically;
            UpdateUserList();

            btSave.Visible = false;// curLevel >= 5;
            btEdit.Text = curLevel >= 5 ? "승인(&E)" : "편집(&E)";
            // binit = true; 

            if (curLevel < 5)
            {
                cmbUser.Enabled = false;
            }
            else
            {
                if (cmbUser.Items.Count > 0)
                    cmbUser.SelectedIndex = 0;
            }


            refreshData();
        }

        void UpdateUserList(bool datelist = false)
        {   //this.cmbUser.DisplayMember = "dispName";
            //this.cmbUser.ValueMember = "id";
            // this.bs.DataSource = dr;
            this.cmbUser.Items.Clear();
            this.cmbUser.Items.Add("-- ALL --");
            //해당그룹내의 사용자 목록을 가져와야한다
            if (datelist == false)
            {
                var dtUser = FCOMMON.DBM.getActiveUserTable();
                foreach (DataRow dr in dtUser.Rows)
                {
                    this.cmbUser.Items.Add(dr["dispname"].ToString());
                }
            }
            else
            {
                var ta = new dsQueryTableAdapters.HolydayUserListTableAdapter();
                var dtUser = ta.GetData(FCOMMON.info.Login.gcode, dtSD.Text, dtED.Text);
                foreach (dsQuery.HolydayUserListRow dr in dtUser.Rows)
                {
                    this.cmbUser.Items.Add($"{dr.UserName}({dr.uid})");
                }
            }
            this.cmbUser.Text = $"{FCOMMON.info.Login.nameK}({FCOMMON.info.Login.no})";
            //if (this.cmbUser.SelectedIndex < 0) this.cmbUser.SelectedIndex = 0;
        }


        string GetUIDValue()
        {
            string uid = "%";
            if (cmbUser.SelectedIndex > 0)
            {
                var si = cmbUser.Text.IndexOf("(");
                var ei = cmbUser.Text.LastIndexOf(")");
                uid = cmbUser.Text.Substring(si + 1, ei - si - 1);
            }
            return uid;
        }

        private bool getKisulInput
        {
            get
            {
                return FCOMMON.Util.getBit(
                FCOMMON.info.Login.gpermission,
                (int)FCOMMON.eGroupPermission.jobreport_kisul);
            }
        }


        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()
        {

            //dsMSSQL.JobReport.Clear();
            var sd = dtSD.Text.Trim();
            var ed = dtED.Text.Trim();
            var seluid = GetUIDValue();

            var uid = "";
            if (cmbUser.SelectedIndex == 0) uid = "%";
            else uid = GetUIDValue();

            ta.Fill(this.dSKuntae.EETGW_HolydayRequest, FCOMMON.info.Login.gcode, sd, ed, uid);

            var sum_day = dSKuntae.EETGW_HolydayRequest.AsEnumerable().Where(t => t.conf == 1).Sum(t => t.HolyDays);
            var sum_time = dSKuntae.EETGW_HolydayRequest.AsEnumerable().Where(t => t.conf == 1).Sum(t => t.HolyTimes);

            var sum_day2 = dSKuntae.EETGW_HolydayRequest.AsEnumerable().Where(t => t.conf == 0).Sum(t => t.HolyDays);
            var sum_time2 = dSKuntae.EETGW_HolydayRequest.AsEnumerable().Where(t => t.conf == 0).Sum(t => t.HolyTimes);

            sbday.Text = $"합계(일) = 승인:{sum_day}/미승인:{sum_day2}";
            sbday.ForeColor = sum_day2 == 0 ? Color.Black : Color.Red;
            sbtime.Text = $"합계(시간) = 승인:{sum_time}/미승인:{sum_time2}";
            sbtime.ForeColor = sum_time2 == 0 ? Color.Black : Color.Red;
        }

        void funcSave()
        {
            this.Validate();
            this.bs.EndEdit();
            try
            {
                var cnt = ta.Update(this.dSKuntae.EETGW_HolydayRequest);
                util.MsgI($"{cnt}건의 자료가 저장되었습니다");
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }
        }

        void Projects_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["uid"] = FCOMMON.info.Login.no;
            e.Row["tel"] = FCOMMON.info.Login.tel;
            e.Row["processs"] = FCOMMON.info.Login.process;
            e.Row["name"] = FCOMMON.info.Login.nameK;
            e.Row["dept"] = FCOMMON.info.Login.dept;
            e.Row["conf"] = 0;
            e.Row["remark"] = string.Empty;
            e.Row["holydays"] = 0;
            e.Row["holytimes"] = 0f;

        }


        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[] { "name", "Response", "HolyReason", "remark" };
                    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)
        {
            funcSave();
        }

        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 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 arDatagridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            var newdr = this.dSKuntae.EETGW_HolydayRequest.NewEETGW_HolydayRequestRow();
            newdr.sdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.edate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.HolyDays = 0;
            newdr.HolyTimes = 0f;
            newdr.cate = "년차";
            //newdr.stime = "00:00";
            //newdr.etime = "00:00";
            var f = new OtConfirm.fHolyRequestAdd(newdr);
            if (f.ShowDialog() == DialogResult.OK)
            {
                newdr.EndEdit();
                this.dSKuntae.EETGW_HolydayRequest.AddEETGW_HolydayRequestRow(newdr);
                try
                {
                    var cnt = ta.Update(this.dSKuntae.EETGW_HolydayRequest);
                    dSKuntae.EETGW_HolydayRequest.AcceptChanges();
                    FCOMMON.Util.MsgI($"{cnt}건의 자료가 저장 되었습니다");
                    refreshData();
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE(ex.Message);
                }
            }
            else
            {
                newdr.Delete();
            }
        }

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

            //내자료가 아니면 편집할수없다
            if (curLevel < 5)
            {
                if (dr.uid != FCOMMON.info.Login.no)
                {
                    FCOMMON.Util.MsgE("담당자만 자료를 편집할 수 있습니다");
                    return;
                }
            }

            var f = new OtConfirm.fHolyRequestAdd(dr);
            if (f.ShowDialog() == DialogResult.OK)
            {
                dr.EndEdit();
                try
                {
                    var cnt = ta.Update(dr);
                    dr.AcceptChanges();
                    if (cnt == 0)
                        FCOMMON.Util.MsgE($"저장 실패");
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE(ex.Message);
                }
            }
            else
            {
                dr.RejectChanges();
            }
        }

        private void btDel_Click(object sender, EventArgs e)
        {
            //승인되자료는 삭제할수 없음
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSKuntae.EETGW_HolydayRequestRow;
            curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.holyreq));

            if (curLevel < 5)
            {
                if (dr.conf != 0)
                {
                    FCOMMON.Util.MsgE("승인된 자료는 삭제할 수 없습니다");
                    return;
                }
                if (dr.uid != FCOMMON.info.Login.no)
                {
                    FCOMMON.Util.MsgE("담당자만 자료를 삭제할 수 있습니다");
                    return;
                }
            }

            if (FCOMMON.DBM.GetMagamStatus(dr.sdate.Substring(0, 7)))
            {
                FCOMMON.Util.MsgE("마감된 자료이므로 삭제할 수 없습니다");
                return;
            }

            if (FCOMMON.DBM.GetMagamStatus(dr.edate.Substring(0, 7)))
            {
                FCOMMON.Util.MsgE("마감된 자료이므로 삭제할 수 없습니다");
                return;
            }

            var dlg = FCOMMON.Util.MsgQ("삭제할까요?");
            if (dlg != DialogResult.Yes) return;

            var delinfo = $"{dr.uid}|{dr.name}|{dr.cate}|{dr.sdate}|{dr.edate}|{dr.HolyReason}|{dr.HolyLocation}";
            bs.RemoveCurrent();
            var cnt = ta.Update(this.dSKuntae.EETGW_HolydayRequest);
            if (cnt == 0)
                FCOMMON.Util.MsgQ("삭제가 완료되지 않았습니다");
            else FCOMMON.Pub.AddLog($"[휴가신청데이터삭제] {delinfo}");
        }

        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 toolStripButton1_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DSKuntae.EETGW_HolydayRequestRow;
            if (dr.cate.Equals("외출") == false)
            {
                FCOMMON.Util.MsgE("외출 자료만 완료할 수 있습니다");
                return;
            }
            if (dr.conf != 1)
            {
                FCOMMON.Util.MsgE("관리자 승인된 자료만 완료할 수 있습니다");
                return;
            }
            var f = new OtConfirm.fOutCoomplete(dr);
            if (f.ShowDialog() == DialogResult.OK)
            {
                dr.stime = f.dtSD.Value.ToString("HH:mm");
                dr.etime = f.dtED.Value.ToString("HH:mm");
                dr.EndEdit();
                try
                {
                    var cnt = ta.Update(this.dSKuntae.EETGW_HolydayRequest);
                    dSKuntae.EETGW_HolydayRequest.AcceptChanges();
                    FCOMMON.Util.MsgI($"{cnt}건의 자료가 저장 되었습니다");
                    refreshData();
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE(ex.Message);
                }
            }
        }

        private void 외출완료ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripButton1.PerformClick();
        }
    }
}
