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 rJobReportDay : fBase
    {
        //  Boolean binit = false;
        public rJobReportDay(string baseday)
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            if (baseday.Length > 7)
                tbMon.Text = baseday.Substring(0, 7);

        }

        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;

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

            //this.tbMon.Text = DateTime.Now.ToString("yyyy-MM");
            refrehData();
            // binit = true;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var f = new FCOMMON.fSelectMonth();
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            this.tbMon.Text = string.Format("{0:0000}-{1:00}", DateTime.Now.Year, f.selectmon);
            refrehData();

        }
        void refrehData()
        {
            string prcname = tbProcess.SelectedIndex < 1 ? "%" : tbProcess.Text.Trim();
            this.ta.Fill(this.dsReport.JobReportDay, tbMon.Text, FCOMMON.info.Login.gcode, prcname);

            var taH = new dsReportTableAdapters.HolidayLIstTableAdapter();
            taH.Fill(this.dsReport.HolidayLIst, tbMon.Text + "%");
            //this.reportViewer1.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout);
            //this.reportViewer1.ZoomMode = Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
            //this.reportViewer1.RefreshReport();

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

            var Process = tbProcess.Text.Trim();
            if (Process == "%" || tbProcess.SelectedIndex == 0) Process = "";

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

            //날짜에 해당하는 열을 먼저 생성한다
            dataGridView1.Columns.Add("dvcu_damdang", "사원명");
            // dataGridView1.Columns.Add("dvcu_process", "공정");
            var daylist = dsReport.JobReportDay.OrderBy(t => t.pdate).GroupBy(t => t.pdate);
            foreach (var dayitem in daylist)
            {

                var dtValue = DateTime.Parse(dayitem.Key);
                var week = wekklist[(int)dtValue.DayOfWeek];
                this.dataGridView1.Columns.Add("dvcu_pdate", dayitem.Key.Substring(8, 2) + "(" + week.ToString() + ")");

                //휴일이면 태그에 1을 넣는다
                var drh = this.dsReport.HolidayLIst.Where(t => t.pdate == dayitem.Key).FirstOrDefault();
                if (drh != null && drh.free == true)
                    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 1].Tag = "1";
                else
                    this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 1].Tag = "0";


                //if (dtValue.DayOfWeek == DayOfWeek.Saturday || dtValue.DayOfWeek == DayOfWeek.Sunday)
                //{

                //}
                //else
                //{
                //    this.dataGridView1.Columns.Add("dvcu_pdate", dayitem.Key.Substring(8, 2) );
                //}

                this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            dataGridView1.Columns.Add("dvcu_sum", "합계");
            this.dataGridView1.Columns[this.dataGridView1.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            var curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.jobreport));

            foreach (var item in dsReport.JobReportDay.Where(t => t.processs.Contains(Process)).OrderBy(t => t.uname + t.uid).GroupBy(t => t.uname))
            {
                //사용자별로 데이터를 가져온다.
                var username = item.Key;
                var userid = item.FirstOrDefault().uid;
                if (curLevel < 5 && userid != FCOMMON.info.Login.no) continue;

                List<string> rowdata = new List<string>();
                rowdata.Add(username);
                // rowdata.Add(item.FirstOrDefault().processs);

                //이 사용자의 데이터를 날짜별로 정렬해서 가져온다.
                var sum = 0.0;
                var sumOT = 0.0;
                var sumFR = 0.0; //휴일근무시간 210310
                for (int i = 1; i < this.dataGridView1.Columns.Count - 1; i++)
                {
                    var col = this.dataGridView1.Columns[i];
                    var dayStr = col.HeaderText.Substring(0, 2);

                    var daydata = dsReport.JobReportDay.Where(t => t.uid == userid && t.pdate.EndsWith(dayStr)).FirstOrDefault();
                    if (daydata != null)
                    {
                        // 휴일여부확인
                        //var daystrF = this.tbMon.Text + "-" + dayStr;
                        //var dayinfo = dsReport.HolidayLIst.Where(t => t.pdate == daystrF).FirstOrDefault();

                        sum += daydata.hrs;

                        if (col.Tag.ToString() == "1")
                        {
                            //이날은 휴일이다
                            sumFR += daydata.ot;// + daydata.hrs;
                                                //sumOT += daydata.ot;
                            rowdata.Add("*" + daydata.hrs.ToString() + "+" + daydata.ot.ToString());
                        }
                        else
                        {
                            //평일이다
                            sumOT += daydata.ot;

                            if (daydata.jobtype == "휴가")
                            {
                                if (daydata.hrs + daydata.ot == 8.0) rowdata.Add("휴가");
                                else rowdata.Add((daydata.hrs.ToString() + "+" + daydata.ot.ToString()));
                            }
                            else
                            {
                                rowdata.Add((daydata.hrs.ToString() + "+" + daydata.ot.ToString()));
                            }

                        }
                    }
                    else rowdata.Add("--"); //업무일지에 자료가 없다.
                }
                rowdata.Add(sum.ToString() + "+" + sumOT.ToString() + "(*" + sumFR.ToString() + ")");
                this.dataGridView1.Rows.Add(rowdata.ToArray());
            }
            foreach (DataGridViewRow dvrow in this.dataGridView1.Rows)
            {
                for (int i = 1; i < this.dataGridView1.ColumnCount - 1; i++)
                {
                    var col = this.dataGridView1.Columns[i];
                    var cellvalue = "--";
                    if (dvrow.Cells[i].Value != null) cellvalue = dvrow.Cells[i].Value.ToString();
                    if (cellvalue == "--") dvrow.Cells[i].Style.ForeColor = Color.Gray;
                    else if (cellvalue == "휴가") dvrow.Cells[i].Style.ForeColor = Color.Tomato;
                    else
                    {
                        var datasplbu = cellvalue.Split('+');
                        double hrs;
                        double ot;
                        if (double.TryParse(datasplbu[1], out ot) == false) ot = 0;

                        if (col.Tag.ToString() == "1")
                        {
                            dvrow.Cells[i].Style.ForeColor = Color.Green;
                        }
                        else
                        {
                            if (double.TryParse(datasplbu[0], out hrs))
                            {
                                if (hrs > 8.0) dvrow.Cells[i].Style.ForeColor = Color.Blue;
                                else if (hrs < 8.0) dvrow.Cells[i].Style.ForeColor = Color.Red;
                                else
                                {
                                    if (ot == 0)
                                        dvrow.Cells[i].Style.ForeColor = Color.Black;
                                    else
                                        dvrow.Cells[i].Style.ForeColor = Color.Magenta;
                                }
                            }
                            else
                            {
                                FCOMMON.Util.MsgE("숫자변경실패 " + cellvalue);
                                dvrow.Cells[i].Style.ForeColor = Color.Red;
                            }
                        }

                    }
                }

            }
            this.dataGridView1.AutoResizeColumns();
        }

        private void tbProcess_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {

        }

        private void lbStt_Click(object sender, EventArgs e)
        {
            var f = new FCOMMON.fSelectMonth();
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            this.tbMon.Text = string.Format("{0:0000}-{1:00}", DateTime.Now.Year, f.selectmon);
            refrehData();
        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }

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

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

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

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            var sdo = DateTime.Parse(this.tbMon.Text + "-01");
            var sd = sdo.AddMonths(-1);
            tbMon.Text = sd.ToString("yyyy-MM");

        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            var sdo = DateTime.Parse(this.tbMon.Text + "-01");
            var sd = sdo.AddMonths(1);
            tbMon.Text = sd.ToString("yyyy-MM");
        }
    }
}
