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;

namespace FPJ0000.JobReport_
{
    public partial class rJobReportPrj : fBase
    {
        Boolean binit = false;
        public rJobReportPrj(string baseday)
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            this.dts.Value = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01"));
            this.dte.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1);

        }

        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;

            //사용자 목록을 선택한다
            UpdateUserList();

            var curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));
            if(curLevel < 5)
            {
                tbProcess.Enabled = false;
                cmbUser.Enabled = false;
            }

            //this.tbMon.Text = DateTime.Now.ToString("yyyy-MM");
            refrehData();
            binit = true;
        }
        void UpdateUserList()
        {
            var ta = new dsPRJTableAdapters.vJobReportForUserListTableAdapter();

            cmbUser.Items.Clear();

            //일반사용자 목록 가져온다
            dsPRJ.vJobReportForUserListDataTable userlist;

            if (tbProcess.SelectedIndex <= 0)
            {
                //공정구분없이 전체사용자를 가져온다
                userlist = ta.GetData(FCOMMON.info.Login.gcode, "%");
                //  db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode).OrderBy(t => t.name).GroupBy(t => t.name);
            }
            else
            {
                userlist = ta.GetData(FCOMMON.info.Login.gcode, tbProcess.Text);
                //db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.userProcess == tbProcess.Text).OrderBy(t => t.name).GroupBy(t => t.name);
            }

            //if (tbProcess.SelectedIndex != 0) userlist = userlist.Where(t => t.processs == tbProcess.Text); //해당 공정의 인원만 처리한다

            foreach (var dr in userlist)
            {
                //var dr = item.First();
                cmbUser.Items.Add(String.Format("[{0}] {1}", dr.id, dr.name));
            }

            if (tbProcess.SelectedIndex > 0)
                cmbUser.Text = string.Format("[{0}] {1}", FCOMMON.info.Login.no, FCOMMON.info.Login.nameK);

            if (cmbUser.SelectedIndex < 0) cmbUser.SelectedIndex = 0;  //기본전체로 선택해준다.
        }

        void refrehData()
        {

            //근문일수,시간
            var vSD = dts.Value.ToString("yyyy-MM-dd");
            var vED = dte.Value.ToString("yyyy-MM-dd");

            string prcname = tbProcess.SelectedIndex < 1 ? "%" : tbProcess.Text.Trim();
            var taH = new dsReportTableAdapters.JobProjectTimesTableAdapter();

            var username = cmbUser.Text.Trim();

            var uid = username.Substring(1, username.IndexOf("]") - 1);// "395552";

            taH.Fill(this.dsReport.JobProjectTimes, FCOMMON.info.Login.gcode, vSD, vED, uid);
            //this.reportViewer1.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout);
            //this.reportViewer1.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
            //this.reportViewer1.RefreshReport();

            //그리드뷰 생성
            this.dv1.Rows.Clear();
            this.dv1.Columns.Clear();


            var wekklist = new string[] { "일", "월", "화", "수", "목", "금", "토" };

            //날짜에 해당하는 열을 먼저 생성한다

            dv1.Columns.Add("dvcu_pidx", "*");
            dv1.Columns.Add("dvcu_state", "상태");
            dv1.Columns.Add("dvcu_title", "프로젝트");
            //dv1.Columns.Add("dvcu_hrs", "시간");

            //ww컬럼생성
            var wwlist = dsReport.JobProjectTimes.GroupBy(t => t.ww).Select(t => int.Parse(t.Key)).OrderBy(t => t).ToList();
            var wwfont = new Font("Consolas", 8f);
            dv1.ColumnHeadersDefaultCellStyle.Font = wwfont;

            foreach (var item in wwlist)
            {
                dv1.Columns.Add("dvcu_ww" + item, $"{item}(%)");
                dv1.Columns[dv1.Columns.Count - 1].DefaultCellStyle.NullValue = "";
                dv1.Columns[dv1.Columns.Count - 1].DefaultCellStyle.Format = "N2";
                dv1.Columns[dv1.Columns.Count - 1].DefaultCellStyle.Font = wwfont;
            }



            dv1.Columns.Add("dvcu_hrs", "합계(h)");
            dv1.Columns[dv1.Columns.Count - 1].DefaultCellStyle.BackColor = Color.LightGray;

            dv1.Columns.Add("dvcu_hrs", "비율(%)");
            dv1.Columns[dv1.Columns.Count - 1].DefaultCellStyle.Format = "N2";

            var TotHrs = dsReport.JobProjectTimes.Sum(t => t.hrs);

            //데이터를 추가한다.
            //bool addholy = false;
            foreach (var dr in dsReport.JobProjectTimes.OrderByDescending(t => t.PrjStatus + t.PrjName).GroupBy(t => t.PrjName))
            {
                var pidx = dr.Key;
                var fdr = dr.First();

                List<object> row = new List<object>();
                row.Add(fdr.pidx);
                if (string.IsNullOrEmpty(dr.Key))
                {
                    row.Add("--");
                    row.Add("비 프로젝트 업무");
                }
                else if (dr.Key == "미팅")
                {
                    row.Add("--");
                    row.Add("미팅");
                    //addholy = true;
                }
                else if (dr.Key == "휴가")
                {
                    row.Add("--");
                    row.Add("휴가");
                    //addholy = true;
                }
                else
                {
                    row.Add(fdr.PrjStatus);
                    if (fdr.PrjName.isEmpty())
                    {
                        row.Add($"{fdr.title}");
                    }
                    else
                    {
                        row.Add($"{fdr.PrjName}");
                    }

                }
                //row.Add("--");

                foreach (var item in wwlist)
                {
                    var wwsum = dsReport.JobProjectTimes.Where(t => t.ww == item.ToString()).Sum(t => t.hrs);
                    var wwhrs = 0.0;
                    var hrsdata = dr.Where(t => t.ww == item.ToString());
                    if (hrsdata.Any()) wwhrs = hrsdata.Sum(t => t.hrs);

                    var perc = 0.0;
                    if (wwsum > 0) perc = (wwhrs / wwsum) * 100.0;

                    if (perc == 0.0) row.Add(null);
                    else row.Add(perc);
                }

                row.Add(dr.Sum(t => t.hrs));
                var tperc = 0.0;
                if (TotHrs > 0) tperc = (dr.Sum(t => t.hrs) / TotHrs) * 100.0;

                row.Add(tperc);

                if (string.IsNullOrEmpty(dr.Key) || dr.Key == "휴가" || dr.Key == "미팅")
                    dv1.Rows.Insert(0, row.ToArray());
                else
                    dv1.Rows.Add(row.ToArray());


            }



            dv1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dv1.Columns[0].DefaultCellStyle.BackColor = Color.LightGray;
            dv1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;


            for (int i = 0; i < this.dv1.ColumnCount; i++)
            {
                var col = this.dv1.Columns[i];
                if (col.Name.StartsWith("dvcu_ww") == false) continue;

                foreach (DataGridViewRow dvrow in this.dv1.Rows)
                {
                    var c = dvrow.Cells[col.Index];
                    var v = c.Value;
                    double hrs = 0.0;
                    if (v != null) hrs = double.Parse(v.ToString());
                    if (hrs > 0)
                    {
                        c.Style.BackColor = Color.Gold;
                    }
                    else
                    {
                        c.Style.BackColor = Color.White;
                    }

                }

            }

            //첫줄은 색상을 변경해준다.
            //if (dv1.RowCount > 0)
            //{
            //    var dvrow = dv1.Rows[0];
            //    for (int i = 0; i < this.dv1.ColumnCount; i++)
            //    {
            //        var c = dvrow.Cells[i];
            //        c.Style.BackColor = Color.LightGray;
            //    }

            //}
            for(int r = 0; r < dv1.RowCount;r++)
            {
                var dvrow = dv1.Rows[r];
                var idxvlaue = dvrow.Cells[0].Value.ToString();
                if (idxvlaue == "-1")
                {
                    for (int i = 0; i < this.dv1.ColumnCount; i++)
                    {
                        var c = dvrow.Cells[i];
                        c.Style.BackColor = Color.LightGray;
                    }
                }
                else break;
                
            }


            //if (addholy && dv1.RowCount > 1)
            //{
            //    var dvrow = dv1.Rows[1];
            //    for (int i = 0; i < this.dv1.ColumnCount; i++)
            //    {
            //        var c = dvrow.Cells[i];
            //        c.Style.BackColor = Color.LightGray;
            //    }

            //}


            this.dv1.AutoResizeColumns();
        }



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

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

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

        private void button1_Click(object sender, EventArgs e)
        {
            var newsize = dv1.Columns[2].Width < 10 ? 100 : 5;
            this.dv1.SuspendLayout();
            for (int i = 3; i < this.dv1.ColumnCount - 2; i++)
            {
                this.dv1.Columns[i].Width = newsize;
            }
            this.dv1.ResumeLayout();
        }

        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        private void linkLabel13_Click(object sender, EventArgs e)
        {
            var lnk = sender as LinkLabel;
            if (lnk.Text.Equals("상반기"))
            {
                dts.Value = DateTime.Parse(DateTime.Now.Year.ToString("0000") + "-01-01");
                dte.Value = DateTime.Parse(DateTime.Now.Year.ToString("0000") + "-06-30");
            }
            else if (lnk.Text.Equals("하반기"))
            {
                dts.Value = DateTime.Parse(DateTime.Now.Year.ToString("0000") + "-07-01");
                dte.Value = DateTime.Parse(DateTime.Now.Year.ToString("0000") + "-12-31");
            }
            else
            {
                if (int.TryParse(lnk.Text.Substring(0, 2), out int mon) == false) return;
                dts.Value = DateTime.Parse(DateTime.Now.Year.ToString("0000") + "-" + mon.ToString("00") + "-01");
                dte.Value = dts.Value.AddMonths(1).AddDays(-1);
            }
        }

        private void linkLabel14_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }
    }
}
