using FarPoint.Win;
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 rJobReportUser : Form
    {
        Boolean binit = false;
        public rJobReportUser()
        {
            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")).AddDays(-1);
        }

        private void rJobReport_Load(object sender, EventArgs e)
        {
            this.tbProcess.Items.Clear();
            this.fpSpread1_Sheet2.AddSelection(2, 3, 4, 3);
           // fpSpread1_Sheet2.Columns[1, 0].AllowAutoSort = true;
            //this.fpSpread1_Sheet2.ColumnHeader.AutoTextIndex = 1;


            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;

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

            //엑셀파일불러오기
            //var file = FCOMMON.Util.CurrentPath + "ReportForUser.xlsx";
            //this.fpSpread1.OpenExcel(file);
            if (this.fpSpread1.Sheets.Count > 1) this.fpSpread1.ActiveSheetIndex = 0;

            //refrehData();
            binit = true;
            
            FarPoint.Win.Spread.GridLine black = new FarPoint.Win.Spread.GridLine(FarPoint.Win.Spread.GridLineType.Flat, Color.Black);
            fpSpread1_Sheet2.VerticalGridLine = black;
            fpSpread1_Sheet2.HorizontalGridLine = black;
        }
        private void SetFreezeRowCount_Click(object sender, EventArgs e)
        {
           
        }
        void UpdateUserList()
        {
            var db = new EEEntities();

            cmbUser.Items.Clear();
            cmbUser.Items.Add("--전체--");

            //일반사용자 목록 가져온다
            IQueryable<IGrouping<String, vJobReportForUser>> userlist;

            if (tbProcess.SelectedIndex <= 0)
            {
                //공정구분없이 전체사용자를 가져온다
                userlist = db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode).OrderBy(t => t.name).GroupBy(t => t.name);
            }
            else
            {
                userlist = 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 item 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 db = new EEEntities();


            //조회공정
            this.fpSpread1.Sheets[0].Cells[3, 2].Value = tbProcess.Text;

            //담당자
            this.fpSpread1.Sheets[0].Cells[3, 3].Value = cmbUser.Text;

            //시작일:F4
            this.fpSpread1.Sheets[0].Cells[3, 5].Value = dts.Value;

            //종료일:G4                       
            this.fpSpread1.Sheets[0].Cells[3, 6].Value = dte.Value;

            //근문일수,시간
            var vSD = dts.Value.ToShortDateString();
            var vED = dte.Value.ToShortDateString();

            //휴가일수확인
            var drDays = db.HolidayLIst.Where(t => t.free == false && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0);

            //근무일수적용
            if (drDays == null || drDays.Count() < 1) this.fpSpread1.Sheets[0].Cells[3, 7].Value = 0;
            else this.fpSpread1.Sheets[0].Cells[3, 7].Value = drDays.Count();

            //기준시간 1번시트에 추가 표시 (210215 - 정봉석)
            //this.fpSpread1.Sheets[1].Cells["F1"].Value = drDays.Count() * 8;

            ComplexBorderSide left = new ComplexBorderSide(Color.Gray, 1);
            ComplexBorderSide top = new ComplexBorderSide(Color.Gray, 1);
            ComplexBorderSide right = new ComplexBorderSide(Color.Gray, 1);
            ComplexBorderSide bottom = new ComplexBorderSide(Color.Gray, 1);

            //사용자목록을 가져온다
            List<vJobReportForUser> baseData;
            if (cmbUser.SelectedIndex > 0)
            {
                //사용자번호 
                var UserNo = cmbUser.Text.Substring(1, cmbUser.Text.IndexOf(']') - 1);
                baseData = db.vJobReportForUser
                    .Where(t => t.gcode == FCOMMON.info.Login.gcode && t.id == UserNo && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0)
                    .OrderBy(t => t.name)
                    .OrderBy(t => t.pdate)
                    .ToList();
            }
            else if (tbProcess.SelectedIndex > 0)
            {
                baseData = db.vJobReportForUser
                    .Where(t => t.gcode == FCOMMON.info.Login.gcode && t.userProcess == tbProcess.Text && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0)
                    .OrderBy(t => t.name)
                    .OrderBy(t => t.pdate)
                    .ToList();
            }
            else
            {
                baseData = db.vJobReportForUser
                    .Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0)
                    .OrderBy(t => t.name)
                    .OrderBy(t => t.pdate)
                    .ToList();
            }


            //사용자로 그룹해서 수량을 세명 , 사용자 숫자가 된다.
            this.fpSpread1.Sheets[0].Cells[3, 9].Value = baseData.GroupBy(t => t.id).Count(); //인원수

            var col = 0;
            var row = 0;


            //해당 그룹의 기간데이터를 가져온다
            //if (cmbUser.SelectedIndex > 0)
            //{
            //    //사용자번호 
            //    var UserNo = cmbUser.Text.Substring(1, cmbUser.Text.IndexOf(']') - 1);
            //    baseData = db.vJobReportForUser
            //        .Where(t => t.gcode == FCOMMON.info.Login.gcode && t.id == UserNo && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0)
            //        .OrderBy(t => t.name)
            //        .OrderBy(t => t.pdate)
            //        .ToList();
            //}
            //else if (tbProcess.SelectedIndex > 0)
            //{
            //    baseData = db.vJobReportForUser
            //        .Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0 && t.userProcess == tbProcess.Text)
            //        .OrderBy(t => t.name)
            //        .OrderBy(t => t.pdate)
            //        .ToList();
            //}
            //else
            //{
            //    baseData = db.vJobReportForUser
            //        .Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0)
            //        .OrderBy(t => t.name)
            //        .OrderBy(t => t.pdate)
            //        .ToList();
            //}

            col = 0;
            row = 0;
            fpSpread1.Sheets[1].RowCount = baseData.GroupBy(t => t.id).Count() ;
            foreach (var item in baseData.GroupBy(t => t.id)) //사용자별로 그룹을 해서
            {
                var dr = item.FirstOrDefault();
                this.fpSpread1.Sheets[1].Cells[row, 0].Value = dr.name;
                this.fpSpread1.Sheets[1].Cells[row, 1].Value = dr.id;
                this.fpSpread1.Sheets[1].Cells[row, 2].Value = item.Sum(t => t.hrs);
                this.fpSpread1.Sheets[1].Cells[row, 3].Value = item.Sum(t => t.ot);
                row += 1;
            }
            fpSpread1.Sheets[1].ColumnCount = 4;
            fpSpread1.Sheets[1].RowCount = row + 1;

            //Raw dat a표시
            row = 1;
            this.fpSpread1.Sheets[2].RowCount = baseData.Count + 1;
            foreach (var item in baseData)
            {
                col = 0;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.id;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.name;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.pdate;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.userProcess;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.process;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.svalue;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.hrs;
                this.fpSpread1.Sheets[2].Cells[row, col++].Value = item.ot;
                row += 1;
            }

            // var dtRaw = db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(vSD) >= 0 && t.pdate.CompareTo(vED) <= 0);

            //인원분석보고용타입설1
            col = 2;
            var orTypeName = baseData.Where(t => t.svalue != "휴가").OrderBy(t => t.svalue).GroupBy(t => t.svalue);
            this.fpSpread1.ActiveSheetIndex = 0;
            foreach (var item in orTypeName)
            {
                var dr = item.FirstOrDefault();
                this.fpSpread1.Sheets[0].Cells[6, col++].Value = dr.svalue;
                //col += 1;
            }

            for (int i = col; i <= 6; i++)
                this.fpSpread1.Sheets[0].Cells[6, i].Value = "*";

            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ko-KR", false);
            FarPoint.Win.Spread.CellType.NumberCellType numberCellType1 = new FarPoint.Win.Spread.CellType.NumberCellType();
            numberCellType1.NegativeRed = true;
            numberCellType1.NullDisplay = "--";


            //프로세스목록을 먼저 기록한다
            row = 7;
            this.fpSpread1.Sheets[0].RowCount = 101;
            //var orProcess = baseData.OrderBy(t => t.process).GroupBy(t => t.process);

            //프로세스목록은 전체로 사용한다.
            var prclist = db.Common.Where(t => t.gcode == FCOMMON.info.Login.gcode &&  t.grp == "16").OrderBy(t => t.code).ToList();
            this.progressBar2.Maximum = prclist.Count;
            this.progressBar2.Value = 0;
            foreach(var prcitem in prclist)
            {
                this.progressBar2.Value += 1;
                var item = baseData.Where(t => t.process == prcitem.memo); //해당 프로세스에 해당하는 아이템을 가져온다
                                                                           //}

                if(prcitem.memo.StartsWith("ASM Feeder Center"))
                    Console.WriteLine("sdf");

                //foreach (var item in orProcess)
                //{
                var processName = prcitem.memo; // item.FirstOrDefault().process;
                this.fpSpread1.Sheets[0].Cells[row, 1].Value = processName;

                //2번부터는 데이터를 넣어야 한다
                double sumOt = 0.0;
                double holytime = 0.0;
                int coldata = 2;
                for (int i = 2; i <= 6; i++)
                {
                    if(item.Any()==false)
                    {
                        //자료가없다면 0으로 채운다
                        fpSpread1.Sheets[0].Cells[row, coldata].Value = null;
                    }
                    else
                    {
                        var colData = fpSpread1.Sheets[0].Cells[6, i].Value;
                        var colName = string.Empty;// fpSpread1.Sheets[0].Cells[6, i].Value.ToString();
                        if (colData != null) colName = colData.ToString();

                        //이 이름에 해당하는 데이터의 시간을 가져온다
                        double ot = 0.0;
                        double hrs = 0.0;
                        if (colName != "*" && colName.isEmpty()==false)
                        {
                            //double holytime = 0.0;
                            var timeList = item.Where(t => t.svalue == colName);
                            if (timeList != null)
                            {
                                hrs = (double)timeList.Sum(t => t.hrs);
                                ot = (double)timeList.Sum(t => t.ot);
                                sumOt += ot;
                            }
                        }
                        if (ot + hrs == 0.0) fpSpread1.Sheets[0].Cells[row, coldata].Value = null;
                        else fpSpread1.Sheets[0].Cells[row, coldata].Value = ot + hrs; //없음으로한다
                    }
                  

                    coldata += 1;
                }



                fpSpread1.Sheets[0].Cells[row, 7].CellType = numberCellType1;
                fpSpread1.Sheets[0].Cells[row, 7].ParseFormatString = "N1";
                fpSpread1.Sheets[0].Cells[row, 8].CellType = numberCellType1;
                fpSpread1.Sheets[0].Cells[row, 8].ParseFormatString = "N1";



                fpSpread1.Sheets[0].Cells[row, 7].Formula = string.Format("SUM(C{0}:G{0})+K{0}+J{0}", row + 1);
                fpSpread1.Sheets[0].Cells[row, 8].Formula = string.Format("H{0}/$I$4", row + 1);
                //H8 /$I$4
                if (sumOt == 0.0) fpSpread1.Sheets[0].Cells[row, 9].Value = null; //OT합계
                else fpSpread1.Sheets[0].Cells[row, 9].Value = sumOt; //OT합계



                // process 의 휴가시간을 다시 계산한다.
                var 휴가데이터 = baseData.Where(t => t.process == processName && t.svalue == "휴가");
                if (휴가데이터 == null || 휴가데이터.Count() < 1)
                {
                    fpSpread1.Sheets[0].Cells[row, 10].Value = null;// 0.0; //휴가시간
                }
                else fpSpread1.Sheets[0].Cells[row, 10].Value = 휴가데이터.Sum(t => t.hrs); //휴가시간

                for (int i = 1; i <= 10; i++)
                {
                    fpSpread1.Sheets[0].Cells[row, i].BackColor = Color.White;
                    fpSpread1.Sheets[0].Cells[row, i].Border = new ComplexBorder(left, top, right, bottom);
                    fpSpread1.Sheets[0].Cells[row, i].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                    fpSpread1.Sheets[0].Cells[row, i].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
                }


                row += 1;
            }

            //합계데이터
            fpSpread1.Sheets[0].Cells[row, 1].Value = "합계";
            fpSpread1.Sheets[0].Cells[row, 1].BackColor = Color.LightGray;
            fpSpread1.Sheets[0].Cells[row, 1].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
            fpSpread1.Sheets[0].Cells[row, 1].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
            fpSpread1.Sheets[0].Cells[row, 1].Border = new ComplexBorder(left, top, right, bottom);
            for (int i = 2; i < 11; i++)
            {
                char basec = 'C';
                char newc = (char)(basec + (i - 2));
                fpSpread1.Sheets[0].Cells[row, i].Formula = "SUM(" + newc.ToString() + "8:" + newc.ToString() + row.ToString() + ")";
                fpSpread1.Sheets[0].Cells[row, i].BackColor = Color.LightGray;



                fpSpread1.Sheets[0].Cells[row, i].CellType = numberCellType1;
                fpSpread1.Sheets[0].Cells[row, i].ParseFormatString = "N1";
                fpSpread1.Sheets[0].Cells[row, i].CellType = numberCellType1;
                fpSpread1.Sheets[0].Cells[row, i].ParseFormatString = "N1";


                fpSpread1.Sheets[0].Cells[row, i].Border = new ComplexBorder(left, top, right, bottom);
                fpSpread1.Sheets[0].Cells[row, i].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                fpSpread1.Sheets[0].Cells[row, i].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

            }

            this.fpSpread1.Sheets[0].RowCount = row + 1;




            // 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 (binit == false) return;
            UpdateUserList();
            //if (tbProcess.SelectedIndex >= 0) refrehData();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btSave_Click(object sender, EventArgs e)
        {
            var sd = new SaveFileDialog();
            sd.Filter = "excel(*.xls)|*.xls";
            sd.FilterIndex = 0;
            sd.FileName = "적정인원관리.xls";
            if (sd.ShowDialog() == DialogResult.OK)
            {
                fpSpread1.SaveExcel(sd.FileName);
                FCOMMON.Util.MsgE("파일저장완료\n" + sd.FileName);
            }
        }

        private void linkLabel9_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var lnk = sender as LinkLabel;
            var txt = int.Parse(lnk.Text.Substring(0, 2));
            var sd = DateTime.Parse(dts.Value.ToString("yyyy") + "-" + txt.ToString("00") + "-01");
            var ed = sd.AddMonths(1).AddDays(-1);
            this.dts.Value = sd;
            this.dte.Value = ed;
        }
        private void SetUnfilterRow()
        {
            int[] unfilterRows = new int[3] { 0, 8, 9 };
            this.fpSpread1.Sheets[1].RowFilter.UnfilteredRows = unfilterRows;
        }

        private void fpSpread1_AutoSortingColumn(object sender, FarPoint.Win.Spread.AutoSortingColumnEventArgs e)
        {
           
        }

        private void fpSpread1_CellClick(object sender, FarPoint.Win.Spread.CellClickEventArgs e)
        {
            
           
        }
    }
}
