using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FPJ0000.EBoard
{
    public partial class fEBoardReport : Form
    {
        public fEBoardReport()
        {
            InitializeComponent();
        }

        private void fEBoardReport_Load(object sender, EventArgs e)
        {
            //기본엑셀파일을 가져온다
            this.Show();
            Application.DoEvents();

            //파일불러오기
            //LoadExcel();
            this.fpSpread1.ActiveSheet.RowCount = 0;
            //this.rv1.RefreshReport();
        }

        string Loadexcel = string.Empty;

        void LoadExcel()
        {
            //파일불러오기
            if (radioButton1.Checked)
            {
                var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + "EBoardReport.xlsx");
                if (this.Loadexcel != fi.FullName)
                {
                    this.fpSpread1.OpenExcel(fi.FullName);
                    this.Loadexcel = fi.FullName;
                }

            }
            else
            {
                var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + "EBoardReportCapa.xlsx");
                if (this.Loadexcel != fi.FullName)
                {
                    this.fpSpread1.OpenExcel(fi.FullName);
                    this.Loadexcel = fi.FullName;
                }
            }
        }

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


            LoadExcel();

            if (radioButton1.Checked) Refresh1();
            else Refresh2();


            this.fpSpread1.Invalidate();
        }

        void Refresh1()
        {

            //var sql = "select * from eetgw_jobreport_eboard where gcode=@gcode and pdate between @sd and @ed";
            //var cmd = new System.Data.SqlClient.SqlCommand(sql, this.ta.Connection);
            //cmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode;
            //cmd.Parameters.Add("sd", SqlDbType.VarChar).Value = dts.Value.ToShortDateString();
            //cmd.Parameters.Add("ed", SqlDbType.VarChar).Value = dte.Value.ToShortDateString();
            //var da = new System.Data.SqlClient.SqlDataAdapter(cmd);
            //ds1.EETGW_JobReport_EBoard.Clear();
            //da.Fill(this.ds1.EETGW_JobReport_EBoard);
            //ds1.EETGW_JobReport_EBoard.AcceptChanges();
            //this.rv1.RefreshReport();

            //새로고침
            //a2 에 날짜를 표시함.
            var db = new EEEntities();
            var sd = this.dts.Value.ToShortDateString();
            var ed = this.dte.Value.ToShortDateString();

            var 분류목록 = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.분류) == false).OrderBy(t => t.분류).GroupBy(t => t.분류).ToList();
            IQueryable<EETGW_JobReport_EBoard> 기간자료;
            if (radPdate.Checked)
                기간자료 = db.EETGW_JobReport_EBoard.Where(t => t.pdate.CompareTo(sd) >= 0 && t.pdate.CompareTo(ed) <= 0);
            else
                기간자료 = db.EETGW_JobReport_EBoard.Where(t => t.수리완료일.CompareTo(sd) >= 0 && t.수리완료일.CompareTo(ed) <= 0);

             db = new EEEntities();
            var 담당목록raw = db.vGroupUser.AsNoTracking().Where(t => t.gcode == FCOMMON.info.Login.gcode && t.processs == "전자실" && string.IsNullOrEmpty(t.state) == true).ToList();
            var 담당목록 = 담당목록raw.GroupBy(t => t.name).ToList();


            var row = 1;
            var col = 1;
            var col0 = 1;
            foreach (var item in 분류목록)
            {
                var dr = item.FirstOrDefault();
                var cell = this.fpSpread1.Sheets[0].Cells[row, col + 0];
                cell.Value = dr.분류;
                cell.ColumnSpan = 2;
                cell.BackColor = Color.SkyBlue;
                cell.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                cell.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

                cell = this.fpSpread1.Sheets[0].Cells[row + 1, col + 0];
                cell.Value = "건";
                cell.BackColor = Color.Khaki;
                cell.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                cell.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

                cell = this.fpSpread1.Sheets[0].Cells[row + 1, col + 1];
                cell.Value = "시간";
                cell.BackColor = Color.Khaki;
                cell.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                cell.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

                col += 2;
                col0 += 1;
            }

            //마지막 열에는 비용절감항목을 추가한다.
            fpSpread1.Sheets[0].Cells[1, col].Value = "비용절감";
            fpSpread1.Sheets[0].Cells[1, col].BackColor = Color.WhiteSmoke;
            fpSpread1.Sheets[0].Cells[1, col].RowSpan = 2;
            fpSpread1.Sheets[0].Cells[1, col].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
            fpSpread1.Sheets[0].Cells[1, col].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;

            var MaxCol = col0;
            col = 0;
            row = 3;
            foreach (var item in 담당목록)
            {
                
                //var dr = item.KeY;
                this.fpSpread1.Sheets[0].Cells[row, col].Value = item.Key;

                

                var fistdr = item.FirstOrDefault();
                //var userdr = db.Users.Where(t => t.id == fistdr.id).FirstOrDefault();
                if (fistdr.outdate.isEmpty() ==false && fistdr.outdate.CompareTo(sd) <= 0)
                {
                    //퇴사자 처리
                    continue;
                }
                //if (item.Key == "이상호") continue;

                //이 담당자의 횟수를 읽어온다
                for (int i = 1; i < MaxCol; i++)
                {
                    var 분류명 = fpSpread1.Sheets[0].Cells[1, 1 + (i - 1) * 2].Value.ToString();
                    var 분류데이터 = 기간자료.Where(t => t.uid.Contains(item.Key) && t.분류 == 분류명);
                    var 건수 = 분류데이터.Sum(t => t.QTY);
                    var 시간 = 분류데이터.Sum(t => t.RepairTime);
                    this.fpSpread1.Sheets[0].Cells[row, (i - 1) * 2 + 1].Value = 건수;
                    this.fpSpread1.Sheets[0].Cells[row, (i - 1) * 2 + 2].Value = 시간;
                    this.fpSpread1.Sheets[0].Cells[row, (i - 1) * 2 + 2].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                    this.fpSpread1.Sheets[0].Cells[row, (i - 1) * 2 + 2].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

                    this.fpSpread1.Sheets[0].Cells[row, (i - 1) * 2 + 1].Column.Width = 50;
                    this.fpSpread1.Sheets[0].Cells[row, (i - 1) * 2 + 2].Column.Width = 70;
                }

                //이 담당자의 수리완료건의 비용절감비용을 가져온다
                var 절감비용 = 기간자료.Where(t => t.uid.Contains(item.Key) && t.분류 == "수리완료" && string.IsNullOrEmpty(t.수리완료일) == false && string.IsNullOrEmpty(t.외주업체) == true).Sum(t => t.CostReduction);
                this.fpSpread1.Sheets[0].Cells[row, (MaxCol) * 2 - 1].Value = 절감비용;
                this.fpSpread1.Sheets[0].Cells[row, (MaxCol) * 2 - 1].BackColor = Color.WhiteSmoke;
                this.fpSpread1.Sheets[0].Cells[row, (MaxCol) * 2 - 1].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
                this.fpSpread1.Sheets[0].Cells[row, (MaxCol) * 2 - 1].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                row += 1;
            }

            this.fpSpread1.Sheets[0].Cells[row, 0].Value = "합계";


            for (int i = 1; i < MaxCol; i++)
            {
                var colIdx = (i - 1) * 2;
                var c1 = (char)(65 + colIdx + 1);
                var c2 = (char)(65 + colIdx + 2);
                this.fpSpread1.Sheets[0].Cells[row, colIdx + 1].Formula = $"SUM({c1}4:{c1}" + row.ToString() + ")";
                this.fpSpread1.Sheets[0].Cells[row, colIdx + 2].Formula = $"SUM({c2}4:{c2}" + row.ToString() + ")";
            }
            var c3 = (char)(65 + MaxCol * 2 - 1);
            this.fpSpread1.Sheets[0].Cells[row, (MaxCol) * 2 - 1].Formula = $"SUM({c3}4:{c3}" + row.ToString() + ")";
            this.fpSpread1.Sheets[0].Cells["A1"].Value = "Performance";
            this.fpSpread1.Sheets[0].Cells["A1"].ColumnSpan = MaxCol * 2;
            this.fpSpread1.Sheets[0].Cells["A2"].Value = "성명";
            this.fpSpread1.Sheets[0].Cells["A2"].RowSpan = 2;

            this.fpSpread1.Sheets[0].Cells[$"A2:A{row}"].BackColor = Color.WhiteSmoke;

            //합계필드 색상변경
            this.fpSpread1.Sheets[0].Cells[$"A{row + 1}:{c3}{row + 1}"].BackColor = Color.WhiteSmoke;
            //this.fpSpread1.Sheets[0].Cells[$"A{row + 1}:{c3}{row + 1}"].Border =
            //    new FarPoint.Win.ComplexBorder(
            //        new FarPoint.Win.ComplexBorderSide(FarPoint.Win.ComplexBorderSideStyle.MediumLine)); 

            //차트데이터
            var chart1 = this.fpSpread1.ActiveSheet.Charts[0];
            chart1.Model.LabelAreas[0].Text = "Technical Support Q'ty & Cost Save(Kwon)";   //상단차트제목

            var ser1 = chart1.Model.PlotAreas[0].Series[0] as FarPoint.Win.Chart.ClusteredBarSeries;
            var ser1_df = ser1.Series[0].Values.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            var ser1_cn = ser1.Series[0].CategoryNames.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            ser1_df.Formula = $"Performance!$R$4:$R${row}";
            ser1_cn.Formula = $"Performance!$A$4:$A${row}";

            var ser2 = chart1.Model.PlotAreas[0].Series[1] as FarPoint.Win.Chart.LineSeries;
            var ser2_df = ser2.Values.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            var ser2_cn = ser2.CategoryNames.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            ser2_df.Formula = $"Performance!$D$4:$D${row}";
            ser2_cn.Formula = $"Performance!$A$4:$A${row}";

            var chart2 = this.fpSpread1.ActiveSheet.Charts[1]; //qty
            var ser21 = chart2.Model.PlotAreas[0].Series[0] as FarPoint.Win.Chart.PieSeries;
            var ser21_df = ser21.Values.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            var ser21_cn = ser21.CategoryNames.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            ser21_df.Formula = $"Performance!$D$4:$D${row}";
            ser21_cn.Formula = $"Performance!$A$4:$A${row}";

            var chart3 = this.fpSpread1.ActiveSheet.Charts[2]; //cost
            var ser31 = chart3.Model.PlotAreas[0].Series[0] as FarPoint.Win.Chart.PieSeries;
            var ser31_df = ser31.Values.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            var ser31_cn = ser31.CategoryNames.DataSource as FarPoint.Win.Spread.Chart.SeriesDataField;
            ser31_df.Formula = $"Performance!$R$4:$R${row}";
            ser31_cn.Formula = $"Performance!$A$4:$A${row}";
        }
        void Refresh2()
        {
            //Process / Equipment / BordName 으로 그룹핑
            //a2 에 날짜를 표시함.

            this.progressBar2.Value = 0;

            var db = new EEEntities();
            var sd = this.dts.Value.ToShortDateString();
            var ed = this.dte.Value.ToShortDateString();

            var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + "EBoardReportCapa.xlsx");
            this.fpSpread1.OpenExcel(fi.FullName);
            this.Loadexcel = fi.FullName;



            IQueryable<EETGW_JobReport_EBoard> 기간자료;
            if (radPdate.Checked)
                기간자료 = db.EETGW_JobReport_EBoard.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate.CompareTo(sd) >= 0 && t.pdate.CompareTo(ed) <= 0);
            else
                기간자료 = db.EETGW_JobReport_EBoard.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.수리완료일.CompareTo(sd) >= 0 && t.수리완료일.CompareTo(ed) <= 0);

            var Grp_process = 기간자료.GroupBy(t => t.Process);

            this.fpSpread1.Sheets[0].ColumnCount = 5;
            var row = 3;

            this.progressBar2.Maximum = Grp_process.Count();
            foreach (var item in Grp_process)
            {
                this.progressBar2.Value += 1;

                //포맷초기화
                //var rangec = this.fpSpread1.Sheets[0].Cells[$"A{row}:D{row}"];
                //rangec.BackColor = Color.White;
                //rangec.RowSpan = 1;
                //rangec.ColumnSpan = 1;
                //rangec.HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
                //rangec.VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

                var dr = item.FirstOrDefault();
                var cell = this.fpSpread1.Sheets[0].Cells[$"A{row}"];
                cell.Value = dr.Process;
                //cell.BackColor = Color.Lime;

                var row_grp = row;

                //이것아래의 모델그룹을 찾는다.
                var grp_model = item.GroupBy(t => t.Model);
                var cntg1 = 0;
                foreach (var itemModel in grp_model)
                {
                    var drModel = itemModel.FirstOrDefault();
                    var cellModel = this.fpSpread1.Sheets[0].Cells[$"B{row}"];
                    cellModel.Value = drModel.Model;
                    cellModel.BackColor = Color.White;

                    var row_mod = row;

                    if (cntg1 > 0)
                    {
                        this.fpSpread1.Sheets[0].Cells[$"A{row}"].Value = string.Empty;
                    }

                    //이것아래의 보드를 찾는다.
                    var grp_brd = itemModel.GroupBy(t => t.BoardName);
                    var cntg2 = 0;
                    foreach (var itemBrd in grp_brd)
                    {
                        var drBrd = itemBrd.FirstOrDefault();
                        var cellBrd = this.fpSpread1.Sheets[0].Cells[$"C{row}"];
                        cellBrd.Value = drBrd.BoardName;
                        cellBrd.BackColor = Color.White;

                        if (cntg2 > 0)
                        {
                            this.fpSpread1.Sheets[0].Cells[$"A{row}"].Value = string.Empty;
                            this.fpSpread1.Sheets[0].Cells[$"B{row}"].Value = string.Empty;
                        }

                        //합계수량
                        var sumQty = itemBrd.Sum(t => t.QTY);
                        var sumAmt = itemBrd.Sum(t => t.CostReduction);

                        var cellQty = this.fpSpread1.Sheets[0].Cells[$"D{row}"];
                        var cellAmt = this.fpSpread1.Sheets[0].Cells[$"E{row}"];
                        cellQty.Value = sumQty;
                        cellAmt.Value = sumAmt;

                        cntg2 += 1;
                        cntg1 += 1;
                        if (grp_brd.Count() > 1)
                            row += 1;
                    }

                    //소계를 추가한다.
                    if (cntg2 > 1)
                    {
                        this.fpSpread1.Sheets[0].Cells[$"A{row}"].Value = string.Empty;
                        this.fpSpread1.Sheets[0].Cells[$"B{row}"].Value = string.Empty;
                        this.fpSpread1.Sheets[0].Cells[$"C{row}"].Value = $"({drModel.Model}) Sub Total";
                        this.fpSpread1.Sheets[0].Cells[$"C{row}"].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Left;


                        this.fpSpread1.Sheets[0].Cells[$"D{row}"].Value = itemModel.Sum(t => t.QTY);
                        this.fpSpread1.Sheets[0].Cells[$"E{row}"].Value = itemModel.Sum(t => t.CostReduction);
                        this.fpSpread1.Sheets[0].Cells[$"C{row}:E{row}"].BackColor = Color.FromArgb(200, 200, 200);
                        this.fpSpread1.Sheets[0].Cells[$"B{row_mod}"].RowSpan = row - row_mod + 1;
                    }


                    //cntg1 += cntg2;
                    if ((grp_model.Count() + grp_brd.Count()) > 2)
                        row += 1;
                }

                if (cntg1 > 1)
                {
                    this.fpSpread1.Sheets[0].Cells[$"A{row}"].Value = string.Empty;
                    this.fpSpread1.Sheets[0].Cells[$"B{row}"].Value = $"({dr.Process}) Sub Total";
                    this.fpSpread1.Sheets[0].Cells[$"B{row}"].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Left;
                    this.fpSpread1.Sheets[0].Cells[$"B{row}"].ColumnSpan = 2;
                    //this.fpSpread1.Sheets[0].Cells[$"C{row}"].Value = string.Empty;// item.Count();
                    this.fpSpread1.Sheets[0].Cells[$"D{row}"].Value = item.Sum(t => t.QTY);
                    this.fpSpread1.Sheets[0].Cells[$"E{row}"].Value = item.Sum(t => t.CostReduction);
                    this.fpSpread1.Sheets[0].Cells[$"B{row}:E{row}"].BackColor = Color.FromArgb(150, 150, 150);
                    this.fpSpread1.Sheets[0].Cells[$"A{row_grp}"].RowSpan = row - row_grp + 1;
                }

                row += 1;
            }
            this.fpSpread1.Sheets[0].Cells[$"A{row}"].Value = "Total";
            this.fpSpread1.Sheets[0].Cells[$"B{row}"].Value = string.Empty;// $"({dr.Process})-{cntg1}";            
            this.fpSpread1.Sheets[0].Cells[$"C{row}"].Value = string.Empty;// item.Count();
            this.fpSpread1.Sheets[0].Cells[$"D{row}"].Value = 기간자료.Sum(t => t.QTY);
            this.fpSpread1.Sheets[0].Cells[$"E{row}"].Value = 기간자료.Sum(t => t.CostReduction);

            this.fpSpread1.Sheets[0].Cells[$"A{row}:E{row}"].BackColor = Color.SkyBlue;

            this.fpSpread1.Sheets[0].RowCount = row;
            this.progressBar2.Value = this.progressBar2.Maximum;
        }



        private void btSave_Click(object sender, EventArgs e)
        {
            //파일저장
            var sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            if (sd.ShowDialog() == DialogResult.OK)
            {
                this.fpSpread1.SaveExcel(sd.FileName);
            }
        }

        private void panel1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            LoadExcel();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var bt = sender as Button;
            if (bt.Text == "년")
            {
                dts.Value = new DateTime(DateTime.Now.Year, 1, 1);
                dte.Value = new DateTime(DateTime.Now.Year, 12, 31);
            }
            if (bt.Text == "월")
            {
                dts.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                dte.Value = dts.Value.AddMonths(1).AddDays(-1);
            }
            if (bt.Text == "주")
            {
                dts.Value = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek);
                dte.Value = DateTime.Now.AddDays(6 - (int)DateTime.Now.DayOfWeek);
            }
            if (bt.Text == "일")
            {
                dts.Value = DateTime.Now;
                dte.Value = DateTime.Now;
            }
            RefreshData();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
