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.Threading.Tasks;
using System.Windows.Forms;

namespace FBS0000.Holiday
{
    public partial class fErrorChk : fBase
    {
        public fErrorChk()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;

            //dtSD.KeyDown += dtSD_KeyDown;
            //dtED.KeyDown += dtSD_KeyDown;
            tbDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }
        private void fErrorChk_Load(object sender, EventArgs e)
        {
            //기본 이번달 설정한다
            EnsureVisibleAndUsableSize();
            button2.PerformClick();
        }


        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            //검사버튼
            this.lvNG.CheckBoxes = true;
            var sd = DateTime.Parse(dtSD.Text);
            var ed = DateTime.Parse(dtED.Text);
            var idx = 0;

            var gcode = FCOMMON.info.Login.gcode;
            var id = FCOMMON.info.Login.no;

            var cn = FCOMMON.DBM.getCn();
            cn.Open();
            var cmd = new System.Data.SqlClient.SqlCommand("", cn);
            cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = gcode;
            cmd.Parameters.Add("uid", SqlDbType.VarChar).Value = id;

            lvOK.Items.Clear();
            lvOK.FullRowSelect = true;
            lvOK.CheckBoxes = false;

            lvNG.Items.Clear();
            lvNG.FullRowSelect = true;
            lvNG.CheckBoxes = true;

            while (true)
            {
                var CD = sd.AddDays(idx++);
                if (CD > ed) break;
                var pdate = CD.ToString("yyyy-MM-dd");
                tbDate.Text = pdate;
                Application.DoEvents();

                //이날짜의 업무일지 발생데이터를 확인
                cmd.CommandText = "select sum(isnull(ot2,0)) from jobreport where gcode = @gcode and pdate='{0}' and isnull(ot,0) >0 and isnull(ot2,0) > 0";
                cmd.CommandText = string.Format(cmd.CommandText, pdate);


                var obj_jobreport = cmd.ExecuteScalar().ToString();
                double val_jobreport = 0.0;
                if (string.IsNullOrEmpty(obj_jobreport) == false) val_jobreport = double.Parse(obj_jobreport);
                textBox2.Tag = val_jobreport;// db_jobreport.Sum(t => t.kisulamt);
                textBox2.Text = textBox2.Tag.ToString();




                //휴가신청확인
                cmd.CommandText = "select  cate,sum(HolyDays),sum(HolyTimes) from EETGW_HolydayRequest where gcode = @gcode and sdate = '{0}' and isnull(conf,0) = 1 group by cate";
                cmd.CommandText = string.Format(cmd.CommandText, pdate);
                var dar = cmd.ExecuteReader();
                double val_day = 0;
                double val_time = 0;
                Dictionary<string, double> catelistd = new Dictionary<string, double>();
                Dictionary<string, double> catelistt = new Dictionary<string, double>();
                while (dar.Read())
                {
                    var str_cate = dar[0].ToString();
                    var str_day = dar[1].ToString();
                    var str_time = dar[2].ToString();

                    var v_day = 0.0;
                    var v_time = 0.0;

                    v_day += double.Parse(str_day);
                    v_time += double.Parse(str_time);

                    val_day += v_day;
                    val_time += v_time;


                    if (v_day != 0.0 && catelistd.ContainsKey(str_cate))
                        catelistd[str_cate] = catelistd[str_cate] + v_day;
                    else if(v_day != 0.0)
                        catelistd.Add(str_cate, v_day);


                    if (v_time != 0.0 && catelistt.ContainsKey(str_cate))
                        catelistt[str_cate] = catelistt[str_cate] + v_time;
                    else if(v_time != 0.0)
                        catelistt.Add(str_cate, v_time);
                }
                textBox3.Tag = val_day;// db_jobreport.Sum(t => t.kisulamt);
                textBox3.Text = textBox3.Tag.ToString();
                textBox4.Tag = val_time;// db_jobreport.Sum(t => t.kisulamt);
                textBox4.Text = textBox4.Tag.ToString();
                dar.Close();


                //근태입력자료확인

                cmd.CommandText = "select cate,sum(term)  ,sum(crtime),sum(termdr),sum(drtime),sum(drtimepms)" +
                    " from Holyday " +
                    " where gcode = @gcode and sdate = '{0}'  and isnull(extidx,-1) <> -1" +
                    " group by cate";

                cmd.CommandText = string.Format(cmd.CommandText, pdate);
                dar = cmd.ExecuteReader();
                val_day = 0;
                val_time = 0;
                double val_day_dr = 0;
                double val_time_dr = 0;
                double val_time_drPMS = 0;
                Dictionary<string, double> d_drd = new Dictionary<string, double>();
                Dictionary<string, double> d_drt = new Dictionary<string, double>();
                Dictionary<string, double> d_drtPMS = new Dictionary<string, double>();
                Dictionary<string, double> d_crd = new Dictionary<string, double>();
                Dictionary<string, double> d_crt = new Dictionary<string, double>();
                double v_crd, v_crt, v_drd, v_drt, v_drtPMS;
                System.Text.StringBuilder sbcate = new StringBuilder();
                while (dar.Read())
                {
                    v_crd = v_crt = v_drd = v_drt = v_drtPMS = 0.0;
                    var str_cate = dar[0].ToString();
                    var str_day_cr = dar[1].ToString();
                    var str_time_cr = dar[2].ToString();
                    var str_day_dr = dar[3].ToString();
                    var str_time_dr = dar[4].ToString();
                    var str_time_drPMS = dar[5].ToString();

                    if (string.IsNullOrEmpty(str_day_cr) == false) v_crd = double.Parse(str_day_cr);
                    if (string.IsNullOrEmpty(str_time_cr) == false) v_crt = double.Parse(str_time_cr);

                    if (string.IsNullOrEmpty(str_day_dr) == false) v_drd = double.Parse(str_day_dr);
                    if (string.IsNullOrEmpty(str_time_dr) == false) v_drt = double.Parse(str_time_dr);

                    if (string.IsNullOrEmpty(str_time_drPMS) == false) v_drtPMS = double.Parse(str_time_drPMS);

                    if(v_crd != 0.0)
                    {
                        if (d_crd.ContainsKey(str_cate))
                            d_crd[str_cate] = d_crd[str_cate] + v_crd;
                        else
                            d_crd.Add(str_cate, v_crd);
                    }
                    
                    if(v_crt != 0.0)
                    {
                        if (d_crt.ContainsKey(str_cate))
                            d_crt[str_cate] = d_crt[str_cate] + v_crt;
                        else
                            d_crt.Add(str_cate, v_crt);
                    }

                    if(v_drd != 0.0)
                    {
                        if (d_drd.ContainsKey(str_cate))
                            d_drd[str_cate] = d_drd[str_cate] + v_drd;
                        else
                            d_drd.Add(str_cate, v_drd);
                    }

                    
                    if(v_drt != 0.0)
                    {
                        if (d_drt.ContainsKey(str_cate))
                            d_drt[str_cate] = d_drt[str_cate] + v_drt;
                        else
                            d_drt.Add(str_cate, v_drt);
                    }

                    if(v_drtPMS != 0.0)
                    {
                        if (d_drtPMS.ContainsKey(str_cate))
                            d_drtPMS[str_cate] = d_drtPMS[str_cate] + v_drtPMS;
                        else
                            d_drtPMS.Add(str_cate, v_drtPMS);
                    }
                    

                    

                    val_day += v_crd;// double.Parse(str_day_cr);
                    val_time += v_crt;// double.Parse(str_time_cr);

                    val_day_dr += v_drd;// double.Parse(str_day_dr);
                    val_time_dr += v_drt;// double.Parse(str_time_dr);
                    val_time_drPMS += v_drtPMS;
                }
                dar.Close();

                //카테고리별데이터확인 (대변[CR]자료를 대상으로함)
                bool cateerr = false;
                foreach (var item in catelistd)
                {
                    if (d_crd.ContainsKey(item.Key) == false)
                    {
                        sbcate.Append($"{item.Key}(X)");
                        cateerr = true;
                        break;
                    }
                    else
                    {
                        if (d_crd[item.Key] != item.Value)
                        {
                            sbcate.Append($"{item.Key}({d_crd[item.Key]}|{item.Value})");
                            cateerr = true;
                            break;
                        }
                    }
                }
                if (cateerr == false)
                {
                    foreach (var item in catelistt)
                    {
                        if (d_crt.ContainsKey(item.Key) == false)
                        {
                            sbcate.Append($"{item.Key}(X)");
                            cateerr = true;
                            break;
                        }
                        else
                        {
                            if (d_crt[item.Key] != item.Value)
                            {
                                sbcate.Append($"{item.Key}({d_crt[item.Key]}|{item.Value})");
                                cateerr = true;
                                break;
                            }
                        }
                    }
                }
                if (cateerr == false)
                {
                    foreach (var item in d_crd)
                    {
                        if (item.Key.Equals("대체")) continue;
                        if (catelistd.ContainsKey(item.Key) == false)
                        {
                            sbcate.Append($"{item.Key}(X)");
                            cateerr = true;
                            break;
                        }
                        else
                        {
                            if (catelistd[item.Key] != item.Value)
                            {
                                sbcate.Append($"{item.Key}({catelistd[item.Key]}|{item.Value})");
                                cateerr = true;
                                break;
                            }
                        }
                    }
                }
                if (cateerr == false)
                {
                    foreach (var item in d_crt)
                    {
                        if (item.Key.Equals("대체")) continue;
                        if (catelistt.ContainsKey(item.Key) == false)
                        {
                            sbcate.Append($"{item.Key}(X)");
                            cateerr = true;
                            break;
                        }
                        else
                        {
                            if (catelistt[item.Key] != item.Value)
                            {
                                sbcate.Append($"{item.Key}({catelistt[item.Key]}|{item.Value})");
                                cateerr = true;
                                break;
                            }
                        }
                    }
                }
                textBox6.Tag = val_day;// db_jobreport.Sum(t => t.kisulamt);
                textBox6.Text = textBox6.Tag.ToString();
                textBox5.Tag = val_time;// db_jobreport.Sum(t => t.kisulamt);
                textBox5.Text = textBox5.Tag.ToString();

                textBox8.Tag = val_day_dr;// db_jobreport.Sum(t => t.kisulamt);
                textBox8.Text = textBox8.Tag.ToString();
                textBox7.Tag = val_time_dr;// db_jobreport.Sum(t => t.kisulamt);
                textBox7.Text = textBox7.Tag.ToString();


                bool dataError = false;
                if (textBox2.Text.Equals(textBox7.Text) == false) dataError = true;
                if (textBox3.Text.Equals(textBox6.Text) == false) dataError = true;
                if (textBox4.Text.Equals(textBox5.Text) == false) dataError = true;
                if (cateerr) dataError = true;


                ListViewItem lv = dataError ? this.lvNG.Items.Add(pdate) : this.lvOK.Items.Add(pdate);
                lv.SubItems.Add("입력/생성");
                lv.SubItems.Add($"--/{textBox8.Text}");
                lv.SubItems.Add($"{textBox2.Text}/{textBox7.Text}");
                lv.SubItems.Add($"{textBox3.Text}/{textBox6.Text}");
                lv.SubItems.Add($"{textBox4.Text}/{textBox5.Text}");
                lv.SubItems.Add(sbcate.ToString());

                if (dataError)
                {
                    //해당 월이 마감되었다면 청색으로 한다.
                    if (FCOMMON.DBM.GetMagamStatus(pdate.Substring(0, 7)))
                    {
                        lv.ForeColor = Color.Blue;
                        lv.Checked = false;
                    }
                    else
                    {
                        lv.ForeColor = Color.Tomato;
                        lv.Checked = true;
                    }
                }
                else lv.ForeColor = Color.Black;

                //if (val_jobreport > 0) break;
            }
            cn.Dispose();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //오류수정버튼

            if (lvNG.CheckedItems.Count < 1)
            {
                FCOMMON.Util.MsgE("정정할 자료가 선택되지 않았습니다");
                return;
            }

            if (FCOMMON.Util.MsgQ("재 생성 할까요?") != DialogResult.Yes) return;


            //검사버튼
            var sd = DateTime.Parse(dtSD.Text);
            var ed = DateTime.Parse(dtED.Text);
            //       var idx = 0;

            var gcode = FCOMMON.info.Login.gcode;
            var id = FCOMMON.info.Login.no;

            var cn = FCOMMON.DBM.getCn();
            cn.Open();
            var cmd = new System.Data.SqlClient.SqlCommand("", cn);
            cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = gcode;
            cmd.Parameters.Add("uid", SqlDbType.VarChar).Value = id;
            cmd.Parameters.Add("pdate", SqlDbType.VarChar).Value = "1982-11-23";


            lvNG.FullRowSelect = true;
            foreach (ListViewItem lv in lvNG.CheckedItems)
            {
                var CD = DateTime.Parse(lv.SubItems[0].Text);

                //if (CD > ed) break;
                var pdate = CD.ToString("yyyy-MM-dd");
                cmd.Parameters["pdate"].Value = pdate;
                tbDate.Text = pdate;
                Application.DoEvents();


                if (FCOMMON.Util.MsgQ(pdate + "를 재생성 할까요?") != DialogResult.Yes) break;

                //근태-업무일지자료삭제
                cmd.CommandText = "delete from Holyday where gcode = @gcode and extcate = 'HO' and sdate=@pdate and isnull(extidx,-1) <> -1";
                cmd.CommandText = string.Format(cmd.CommandText, pdate);
                var cnt1 = cmd.ExecuteNonQuery();
                Console.WriteLine($"{cnt1}건의 근태자료가 삭제 되었습니다");

                //근태-업무일지자료생성
                cmd.CommandText = "insert into Holyday(gcode, cate, sdate, edate, term, crtime, termdr, DrTime, contents, [uid], wdate, wuid, extcate, extidx) ";
                cmd.CommandText += "select gcode,'대체',pdate,pdate,0,0,0,isnull(ot2,0),projectname,uid,GETDATE(),@uid + '-ERR','HO',idx from jobreport where gcode = @gcode and pdate = @pdate and isnull(ot2,0) > 0 and isnull(ot,0) > 0";
                cmd.CommandText = string.Format(cmd.CommandText, pdate);
                var cnt2 = cmd.ExecuteNonQuery();
                Console.WriteLine($"{cnt2}건의 근태자료가 생성 되었습니다");



                //근태-휴가신청자료삭제
                cmd.CommandText = "delete from Holyday where gcode = @gcode and extcate = '휴가' and sdate=@pdate and isnull(extidx,-1) <> -1";
                cmd.CommandText = string.Format(cmd.CommandText, pdate);
                cnt1 = cmd.ExecuteNonQuery();
                Console.WriteLine($"{cnt1}건의 근태자료가 삭제 되었습니다");

                //근태-휴가신청자료생성(승인완료된자료대상)
                cmd.CommandText = "insert into Holyday(gcode, cate, sdate, edate, term, crtime, termdr, DrTime, contents, [uid], wdate, wuid, extcate, extidx) ";
                cmd.CommandText += "select gcode,cate,sdate,edate,isnull(holydays,0),isnull(holytimes,0),0,0,HolyReason,uid,GETDATE(),@uid + '-ERR','휴가',idx " +
                    " from EETGW_HolydayRequest " +
                    " where gcode = @gcode and sdate = @pdate and isnull(conf,0)  = 1";

                cmd.CommandText = string.Format(cmd.CommandText, pdate);
                cnt2 = cmd.ExecuteNonQuery();
                Console.WriteLine($"{cnt2}건의 근태자료가 생성 되었습니다");

            }
            cn.Dispose();

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            dtSD.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01");
            dtED.Value = dtSD.Value.AddMonths(1).AddDays(-1);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var 시작달 = DateTime.Parse(dtSD.Value.ToString("yyyy-MM") + "-01");
            dtSD.Value = 시작달.AddMonths(-1);
            dtED.Value = dtSD.Value.AddMonths(1).AddDays(-1);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            var 다음달 = DateTime.Parse(dtSD.Value.ToString("yyyy-MM") + "-01");
            dtSD.Value = 다음달.AddMonths(1);
            dtED.Value = dtSD.Value.AddMonths(1).AddDays(-1);
        }
    }
}
