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 : Form
    {
        Boolean binit = false;
        public rJobReportDay()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            
            
        }

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

            this.tbProcess.Text = FCOMMON.info.Login.process;
            if (tbProcess.SelectedIndex < 0) tbProcess.SelectedIndex = 0;

            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()
        {
            this.ta.Fill(this.dsReport.JobReportDay, tbMon.Text, FCOMMON.info.Login.gcode);
            //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);
                if(dtValue.DayOfWeek == DayOfWeek.Saturday || dtValue.DayOfWeek == DayOfWeek.Sunday)
                {
                    var week = wekklist[(int)dtValue.DayOfWeek];
                    this.dataGridView1.Columns.Add("dvcu_pdate", dayitem.Key.Substring(8, 2) + "(" + week.ToString() + ")");
                }
                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;


            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;
                List<string> rowdata = new List<string>();
                rowdata.Add(username);
               // rowdata.Add(item.FirstOrDefault().processs);

                //이 사용자의 데이터를 날짜별로 정렬해서 가져온다.
                var sum = 0.0;
                var sumOT = 0.0;
                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)
                    {
                        sum += daydata.hrs;
                        sumOT += daydata.ot;
                        rowdata.Add((daydata.hrs.ToString() + "+" + daydata.ot.ToString()));
                    }
                    else rowdata.Add("--");
                }
                rowdata.Add(sum.ToString() + "+" + sumOT.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 cellvalue = "--";
                    if(dvrow.Cells[i].Value != null) cellvalue=  dvrow.Cells[i].Value.ToString();
                    if (cellvalue == "--") dvrow.Cells[i].Style.ForeColor = Color.Gray;
                    else
                    {
                        var datasplbu = cellvalue.Split('+');
                        double hrs;
                        double ot;
                        if (double.TryParse(datasplbu[1], out ot) == false) ot = 0;

                        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 button1_Click(object sender, EventArgs e)
        {
            refrehData();
        }

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