using FCOMMON;
using AR;
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;

namespace FPJ0000.JobReport_
{
    public partial class rJobReportOT : fBase
    {
        int curLevel=0;
        public rJobReportOT()
        {
            InitializeComponent();
             curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.otconfirm));
        }

        private void rJobReport_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.tbProcess.Items.Clear();
            tbProcess.Items.Add("전체");
            //var taProcess = new dsReportTableAdapters.ProcessListTableAdapter();
            var dtProcessList = FCOMMON.DBM.GroupUserProcessList();//taProcess.GetData(FCOMMON.info.Login.gcode);
            foreach (var dr in dtProcessList)
                tbProcess.Items.Add(dr);

            //this.tbProcess.Text = FCOMMON.info.Login.process;
            if (tbProcess.SelectedIndex < 0) tbProcess.SelectedIndex = 0;
            this.cmbApploval.SelectedIndex = 0; //default : 승인
            this.tbSd.Text = DateTime.Now.Year.ToString() + "-01";
            this.tbEd.Text = DateTime.Now.Year.ToString() + "-12";
            this.Show();
            Application.DoEvents();

            cmbUserList.SelectedIndex = 0;

            //refrehData();
        }

        void refrehData()
        {
            if(curLevel < 5)
            {
                UTIL.MsgE("사용 권한이 없습니다");
                return;
            }

            var isReqData = cmbApploval.SelectedIndex > 0;  //미승인선택
            string prcname = tbProcess.SelectedIndex < 1 ? "%" : tbProcess.Text.Trim();
            if (isReqData)
            {
                this.ta.FillByOtReq(this.dsReport.jobReport, FCOMMON.info.Login.gcode, prcname, tbSd.Text, tbEd.Text);
            }
            else
            {
                if (radType.Checked)
                    this.ta.FillByOt2(this.dsReport.jobReport, FCOMMON.info.Login.gcode, prcname, tbSd.Text, tbEd.Text);
                else if (radTypePMS.Checked)
                    this.ta.FillByOtPMS(this.dsReport.jobReport, FCOMMON.info.Login.gcode, prcname, tbSd.Text, tbEd.Text);
                else
                    this.ta.FillByOTAll(this.dsReport.jobReport, FCOMMON.info.Login.gcode, prcname, tbSd.Text, tbEd.Text);
            }



            //그리드뷰 생성
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.Rows.Clear();
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersHeight = 35;
            this.dataGridView1.Columns.Add("공정", "공정");
            this.dataGridView1.Columns.Add("이름", "이름");
            this.dataGridView1.Columns.Add("사번", "사번");


            //이름/년도데이터추가
            var ymlist = dsReport.jobReport.OrderBy(t => t.yymm).GroupBy(t => t.yymm);
            foreach (var ym in ymlist)
            {
                var drYm = ym.FirstOrDefault();
                var basehr = int.Parse(drYm.yymm.Substring(drYm.yymm.IndexOf('(')).Replace("(", "").Replace(")", ""));
                var colname = drYm.yymm;//.Substring(0, 7);
                var yymm = drYm.yymm.Substring(0, 7);


                if (isReqData)
                {
                    this.dataGridView1.Columns.Add(colname, yymm + "\n휴일");
                    this.dataGridView1.Columns.Add(colname, $"요청");
                }
                else if (radTypeAll.Checked)
                {
                    this.dataGridView1.Columns.Add(colname, yymm + "\n휴일");
                    this.dataGridView1.Columns.Add(colname, $"연장");
                    this.dataGridView1.Columns.Add(colname, $"휴일\n(PMS)");
                    this.dataGridView1.Columns.Add(colname, $"PMS");
                }
                else if (radType.Checked)
                {
                    this.dataGridView1.Columns.Add(colname, yymm + "\n휴일");
                    this.dataGridView1.Columns.Add(colname, $"연장");
                }
                else
                {
                    this.dataGridView1.Columns.Add(colname, yymm + "\n휴일\n(PMS)");
                    this.dataGridView1.Columns.Add(colname, $"PMS");
                }

                this.dataGridView1.Columns.Add(colname, $"{basehr}h\n%");

                this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 3].Tag = basehr;
                this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 3].DefaultCellStyle.Format = "N1";

                this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 2].Tag = basehr;
                this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 2].DefaultCellStyle.Format = "N1";

                this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 1].DefaultCellStyle.Format = "N1";

                if (radTypeAll.Checked)
                {
                    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 5].Tag = basehr;
                    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 5].DefaultCellStyle.Format = "N1";

                    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 4].Tag = basehr;
                    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 4].DefaultCellStyle.Format = "N1";
                }



            }

            //사용자별 전체합계칸
            if (isReqData)
            {
                this.dataGridView1.Columns.Add("subtotal", "합계\n휴일");
                this.dataGridView1.Columns.Add($"subtotal", $"합계\n요청");
            }
            else if (radTypeAll.Checked)
            {
                this.dataGridView1.Columns.Add("subtotal", "합계\n휴일");
                this.dataGridView1.Columns.Add($"subtotal", $"합계\n연장");
                this.dataGridView1.Columns.Add("subtotal", "합계\n휴일\n(PMS)");
                this.dataGridView1.Columns.Add($"subtotal", $"합계\nPMS");
            }
            else if (radType.Checked)
            {
                this.dataGridView1.Columns.Add("subtotal", "합계\n휴일");
                this.dataGridView1.Columns.Add($"subtotal", $"합계\n연장");
            }
            else
            {
                this.dataGridView1.Columns.Add("subtotal", "합계\n휴일\n(PMS)");
                this.dataGridView1.Columns.Add($"subtotal", $"합계\nPMS");
            }

            bool allUsers = this.cmbUserList.SelectedIndex == 1;

            List<FCOMMON.Models.GroupUserModel> users = new List<FCOMMON.Models.GroupUserModel>();

            //전체사람을 가져온다.
            if (allUsers)
            {
                users = FCOMMON.DBM.GetGroupUser(FCOMMON.info.Login.gcode);
            }
            else
            {
                //이름으로 정렬해서 데이터를 가져온다
                var namelist = this.dsReport.jobReport.OrderBy(t => t.UserProcess + t.uname).GroupBy(t => t.uname);
                foreach (var item in namelist)
                {
                    var dr = item.FirstOrDefault();
                    if (dr == null) continue;
                    users.Add(new FCOMMON.Models.GroupUserModel
                    {
                        email = string.Empty,
                        Gcode = string.Empty,
                        level = 1,
                        name = dr.uname,
                        Process = dr.UserProcess,
                        uid = dr.uid,
                        useJobReport = dr.useJobReport == 1,
                        useAccount = dr.useUserState == 1,
                    });
                }
            }


            foreach (var drName in users)
            {
                //var drName = uname.FirstOrDefault();
                if (chkExceptPak.Checked && drName.useJobReport == false) continue;

                List<string> rowdata = new List<string>();
                rowdata.Add(drName.Process);
                rowdata.Add(drName.name);
                rowdata.Add(drName.uid);

                double User_sumhlOne = 0;
                double User_sumotOne = 0;

                double User_sumhlAll = 0;
                double User_sumotAll = 0;

                List<Boolean> high = new List<bool>();
                List<Boolean> low = new List<bool>();

                var columngap = radTypeAll.Checked ? 4 : 2;
                for (int i = 3; i < this.dataGridView1.ColumnCount; i += columngap)
                {
                    var col = dataGridView1.Columns[i];
                    var colName = col.Name;
                    var coltitle = col.HeaderText;
                    if (col.Tag == null) continue;
                    var basehr = int.Parse(col.Tag.ToString());

                    var userDatas = dsReport.jobReport.Where(t => t.uid == drName.uid && t.yymm == colName);
                    if (userDatas == null || userDatas.Count() == 0)
                    {
                        //이달에는 데이터가없다
                        rowdata.Add(null);  //휴일
                        rowdata.Add(null);  //연장

                        //전체보기시에는 더많은 skip을 해야한다.
                        if (radTypeAll.Checked)
                        {
                            rowdata.Add(null);  //휴일(pms)
                            rowdata.Add(null);  //연장(pms)
                        }

                        rowdata.Add(null);  //ot율

                        high.Add(false);
                        low.Add(false);
                    }
                    else
                    {
                        ////모든데이터를 확인해서 휴일이랑 데이터를 분리해야한다.
                        //var sumhr = 0f;
                        //var sumot = 0f;
                        //var sumholy = 0f;
                        //foreach(dsReport.jobReportRow item in userDatas)
                        //{
                        //    dsReport.HolidayLIst.Where(t => t.pdate == item.yymm);
                        //}

                        var sumhr = userDatas.Sum(t => t.hrs);

                        double sumotOne = 0.0;  //연장근무(평일)
                        double sumhlOne = 0.0;  //연장근무(휴일)

                        double sumotAll = 0.0;  //연장근무합계(평일)
                        double sumhlAll = 0.0;  //연장근무합계(휴일)

                        if (isReqData)  //미승인데이터
                        {
                            sumotOne = userDatas.Sum(t => t.ot);
                            sumhlOne = userDatas.Sum(t => t.holyot);
                        }
                        else if (radType.Checked)   //대체승인
                        {
                            sumotOne = userDatas.Sum(t => t.ot2);
                            sumhlOne = userDatas.Sum(t => t.holyot2);
                        }
                        else if (radTypePMS.Checked)    //PMS승인
                        {
                            sumotOne = userDatas.Sum(t => t.otPMS);
                            sumhlOne = userDatas.Sum(t => t.holyotPMS);
                        }
                        else
                        {
                            //전체보기에는 두개를 모두 사용한다.
                            sumotOne = userDatas.Sum(t => t.ot2);
                            sumhlOne = userDatas.Sum(t => t.holyot2);

                            sumotAll = userDatas.Sum(t => t.otPMS);
                            sumhlAll = userDatas.Sum(t => t.holyotPMS);
                        }

                        //사용자별 누적 합계
                        User_sumhlOne += sumhlOne;
                        User_sumotOne += sumotOne;

                        if (radTypeAll.Checked)
                        {
                            User_sumhlAll += sumhlAll;
                            User_sumotAll += sumotAll;
                        }

                        var user_total_ot = sumhlOne + sumotOne;

                        //우측 합계표시
                        if (sumhlOne == 0.0) rowdata.Add(null);
                        else rowdata.Add($"{Math.Round(sumhlOne, 1)}");

                        if (sumotOne == 0.0) rowdata.Add(null);
                        else rowdata.Add($"{Math.Round(sumotOne, 1)}");

                        //전체라면 PMS용 합계를 추가
                        if (isReqData == false && radTypeAll.Checked)
                        {
                            user_total_ot += sumhlAll + sumotAll;

                            if (sumhlAll == 0.0) rowdata.Add(null);
                            else rowdata.Add($"{Math.Round(sumhlAll, 1)}");

                            if (sumotAll == 0.0) rowdata.Add(null);
                            else rowdata.Add($"{Math.Round(sumotAll, 1)}");
                        }



                        if (basehr != 0.0)
                        {
                            var otrate = (user_total_ot / basehr) * 100.0;
                            rowdata.Add($"{otrate:N1}%");
                        }
                        else rowdata.Add(null);


                        if (sumhr > basehr) high.Add(true);
                        else high.Add(false);

                        if (sumhr < basehr) low.Add(true);
                        else low.Add(false);
                    }
                }

                //사용자별 합계정보 표시

                if (User_sumhlOne == 0.0) rowdata.Add(null);
                else rowdata.Add($"{Math.Round(User_sumhlOne, 1)}"); //합계(휴일)

                if (User_sumotOne == 0.0) rowdata.Add(null);
                else rowdata.Add($"{Math.Round(User_sumotOne, 1)}"); //합계(연장, PMS)

                if (isReqData == false && radTypeAll.Checked)
                {

                    if (User_sumhlAll == 0.0) rowdata.Add(null);
                    else rowdata.Add($"{Math.Round(User_sumhlAll, 1)}"); //합계(휴일-PMS)

                    if (User_sumotAll == 0.0) rowdata.Add(null);
                    else rowdata.Add($"{Math.Round(User_sumotAll, 1)}"); //합게(연장-PMS)
                }




                dataGridView1.Rows.Add(rowdata.ToArray());

                //이번에 추가한 줄의 셀 컬러를 지정한다
                var currentrow = dataGridView1.Rows.Count - 1;
                for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
                {
                    var col = this.dataGridView1.Columns[i];
                    if (col.Tag == null)
                    {
                        //여기에는 합계칸이 온다
                        if (col.HeaderText.EndsWith("%"))
                        {
                            dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.Black;
                            dataGridView1.Rows[currentrow].Cells[i].Style.BackColor = Color.Gold;
                        }
                        else if (col.HeaderText.Contains("PMS"))
                        {
                            dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.DimGray;
                            dataGridView1.Rows[currentrow].Cells[i].Style.BackColor = Color.WhiteSmoke;
                        }
                        else
                        {
                            dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.Black;
                            dataGridView1.Rows[currentrow].Cells[i].Style.BackColor = Color.WhiteSmoke;
                        }

                        continue;
                    }
                    else
                    {
                        if (col.HeaderText.Contains("휴일"))
                            dataGridView1.Rows[currentrow].Cells[i].Style.BackColor = Color.White;// 155,82,93);
                        else if (col.HeaderText.Contains("요청") || col.HeaderText.Contains("연장") || col.HeaderText.Contains("PMS"))
                            dataGridView1.Rows[currentrow].Cells[i].Style.BackColor = Color.Linen;// 155,82,93);
                        else
                            dataGridView1.Rows[currentrow].Cells[i].Style.BackColor = Color.White;
                    }

                    var idx = i - 2;
                    if (idx < high.Count)
                    {
                        if (high[idx]) dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.Red;
                        else if (low[i - 2]) dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.Blue;
                        else dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.Black;
                    }
                    else dataGridView1.Rows[currentrow].Cells[i].Style.ForeColor = Color.Black;
                }
            }

            //총계추가

            var rowcount = dataGridView1.Rows.Count;
            List<object> rowdata2 = new List<object>();
            rowdata2.Add("합계");
            rowdata2.Add(rowcount);
            rowdata2.Add(null); //사번

            double sumhrs = 0.0;
            for (int i = 3; i < this.dataGridView1.ColumnCount; i++)
            {
                var col = this.dataGridView1.Columns[i];
                var colName = col.Name;
                var header = col.HeaderText;

                //%열은 처리하지않는다.
                if (col.HeaderText.EndsWith("%") == true)
                {
                    var hrstr = col.HeaderText.Substring(0, col.HeaderText.IndexOf('h')).Trim();
                    if (float.TryParse(hrstr, out float hrs))
                    {
                        rowdata2.Add($"{sumhrs/(hrs * rowcount)*100.0:N1}%");
                    }
                    else
                    {
                        rowdata2.Add(null);
                    }

                    sumhrs = 0f;
                    continue;
                }
                else
                {
                    var sum = 0.0;
                    for (int r = 0; r < this.dataGridView1.RowCount; r++)
                    {
                        var cell = dataGridView1.Rows[r].Cells[i];
                        if (cell.Value != null) sum += double.Parse(cell.Value.ToString());
                    }
                    if (sum != 0.0) rowdata2.Add(sum);
                    else rowdata2.Add(null);
                    sumhrs += sum;
                }

            }

            dataGridView1.Rows.Add(rowdata2.ToArray());
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].DefaultCellStyle.BackColor = Color.LightGray;

            this.dataGridView1.AutoResizeColumns();

        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            refrehData();
        }

        private void tbProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tbProcess.SelectedIndex >= 0 && curLevel >= 5) refrehData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.ExportData(string.Empty);
        }

        private void cmbApploval_SelectedIndexChanged(object sender, EventArgs e)
        {
            radType.Enabled = cmbApploval.SelectedIndex == 0;
            radTypeAll.Enabled = cmbApploval.SelectedIndex == 0;
            radTypePMS.Enabled = cmbApploval.SelectedIndex == 0;
        }
    }
}
