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.SaveCost
{
    public partial class fSaveCostReport : Form
    {
        public fSaveCostReport()
        {
            InitializeComponent();
        }

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

            dts.Value = new DateTime(DateTime.Now.Year, 1, 1);
            dte.Value = new DateTime(DateTime.Now.Year, 12, 31);

            //파일불러오기
            LoadExcel();
        }

        void LoadExcel()
        {
            //파일불러오기
            var fn = "CostReduction_" + DateTime.Now.Year.ToString("0000") + ".xlsx";
            var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + fn);
            this.fpSpread1.OpenExcel(fi.FullName);
        }


        int GetColIndex(string colname)
        {
            var sIndex = (int)'A';
            var eIndex = (int)'Z';
            var colsize = eIndex - sIndex + 1;
            var collist = colname.ToCharArray();
            var idx = 0;

            for (int i = collist.Length; i > 0; i--)
            {
                var c = collist[i - 1];
                idx += (int)(c - sIndex) + (colsize * (i - 1));
            }
            return idx;
        }
        string GetColName(int idx)
        {
            var sIndex = (int)'A';
            var eIndex = (int)'Z';
            var colsize = eIndex - sIndex + 1;
            string colName = string.Empty;
            while (true)
            {
                var mok = (int)(Math.Floor((idx * 1.0) / colsize));
                if (mok > 0) colName += (char)(mok + sIndex);
                var namoji = (idx % colsize);
                if (namoji < colsize)
                {
                    colName += (char)(namoji + sIndex);
                    break;
                }
                else idx = namoji;
            }
            return colName;
        }
        private void btRefresh_Click(object sender, EventArgs e)
        {
            //새로고침
            //a2 에 날짜를 표시함.
            var db = new EEEntities();
            var sd = this.dts.Value.ToShortDateString();
            var ed = this.dte.Value.ToShortDateString();

            this.fpSpread1.ActiveSheetIndex = 1;
            var 기간자료 = db.EETGW_SaveCost.Where(t => t.pdate.CompareTo(sd) >= 0 && t.pdate.CompareTo(ed) <= 0).OrderBy(t => t.pdate).GroupBy(t => t.name);


            var row = 6;
            foreach (var item in 기간자료)
            {
                var dr = item.FirstOrDefault();
                this.fpSpread1.ActiveSheet.Cells["C" + row.ToString()].Value = dr.eepart;
                this.fpSpread1.ActiveSheet.Cells["D" + row.ToString()].Value = dr.workgroup;
                this.fpSpread1.ActiveSheet.Cells["E" + row.ToString()].Value = dr.process;
                this.fpSpread1.ActiveSheet.Cells["F" + row.ToString()].Value = dr.site;
                this.fpSpread1.ActiveSheet.Cells["G" + row.ToString()].Value = dr.category;
                this.fpSpread1.ActiveSheet.Cells["H" + row.ToString()].Value = dr.subcate;
                this.fpSpread1.ActiveSheet.Cells["I" + row.ToString()].Value = dr.name;

                this.fpSpread1.ActiveSheet.Cells["J" + row.ToString()].Value = "--";
                this.fpSpread1.ActiveSheet.Cells["K" + row.ToString()].Value = "--";

                this.fpSpread1.ActiveSheet.Cells["L" + row.ToString()].Value = dr.part;
                var str_fanout = dr.fanout == null ? "New" : ((bool)dr.fanout ? "Fan-Out" : "New");
                this.fpSpread1.ActiveSheet.Cells["M" + row.ToString()].Value = str_fanout;

                this.fpSpread1.ActiveSheet.Cells["N" + row.ToString()].Value = item.Sum(t => t.costo);
                this.fpSpread1.ActiveSheet.Cells["O" + row.ToString()].Value = item.Sum(t => t.costn);

                this.fpSpread1.ActiveSheet.Cells["AM" + row.ToString()].Value = dr.userManager;

                //1월수량
                var colZ = GetColIndex("Z");
                for (int ii = 0; ii < 12; ii++)
                {
                    var psd = new DateTime(2021,ii+1,1);
                    var ped = psd.AddMonths(1).AddDays(-1);
                    var datas = item.Where(t => t.pdate.CompareTo(psd.ToShortDateString()) >= 0 && t.pdate.CompareTo(ped.ToShortDateString()) <= 0);
                    var tCnt = datas.Count();
                    this.fpSpread1.ActiveSheet.Cells[row, colZ + ii].Value = tCnt;// datas.Count();
                }

                row += 1;
            }





            //var 분류목록 = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.분류) == false).OrderBy(t => t.분류).GroupBy(t => t.분류).ToList();


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


            //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;

            //    //이 담당자의 횟수를 읽어온다
            //    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 건수 = 분류데이터.Count();
            //        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)); 


            ////모든열을 중앙정렬한다

            this.fpSpread1.ActiveSheetIndex = 0;
            this.fpSpread1.Invalidate();
        }

        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();
        }
    }
}
