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 fJobChartMenu : Form
    {
        Boolean binit = false;

        public fJobChartMenu()
        {
            InitializeComponent();
            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 fJobChartMenu_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;

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

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

            //refrehData();
            binit = true;
        }
        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, 4].Value = dts.Value;

            //종료일:G4                       
            this.fpSpread1.Sheets[0].Cells[3, 5].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, 6].Value = 0;
            else this.fpSpread1.Sheets[0].Cells[3, 6].Value = drDays.Count();


            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).OrderBy(t => t.name).ToList();
            }
            else if (tbProcess.SelectedIndex > 0)
            {
                baseData = db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.userProcess == tbProcess.Text).OrderBy(t => t.name).ToList();
            }
            else
            {
                baseData = db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode).OrderBy(t => t.name).ToList();
            }


            //사용자로 그룹해서 수량을 세명 , 사용자 숫자가 된다.
            this.fpSpread1.Sheets[0].Cells[3, 7].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 = 1;
            fpSpread1.Sheets[1].RowCount = baseData.GroupBy(t => t.id).Count() + 1;
            foreach (var item in baseData.GroupBy(t => t.id)) //사용자별로 그룹을 해서
            {
                var dr = item.FirstOrDefault();
                this.fpSpread1.Sheets[2].Cells[row, 0].Value = dr.name;
                this.fpSpread1.Sheets[2].Cells[row, 1].Value = dr.id;
                this.fpSpread1.Sheets[2].Cells[row, 2].Value = item.Sum(t => t.hrs);
                this.fpSpread1.Sheets[2].Cells[row, 3].Value = item.Sum(t => t.ot);
                row += 1;
            }
            fpSpread1.Sheets[1].ColumnCount = 5;
            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[3].Cells[row, col++].Value = item.id;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.name;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.pdate;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.userProcess;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.process;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.svalue;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.hrs;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.ot;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.requestpart;
                this.fpSpread1.Sheets[3].Cells[row, col++].Value = item.package;
                row += 1;
            }

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

            //공정목록(우측으로 전개함)
            col = 2;
            var orTypeName = baseData.Where(t => t.svalue != "휴가").OrderBy(t => t.process).GroupBy(t => t.process);
            this.fpSpread1.ActiveSheetIndex = 0;
            foreach (var item in orTypeName)
            {
                var dr = item.FirstOrDefault();
                this.fpSpread1.Sheets[0].Cells[6, col++].Value = dr.process;
                if (col == 11) break; //목록개수를 넘었으니 더이상 진행하지 못한다 이것들은 모두 ETC에 넣는다
                //col += 1;
            }

            //나머지 열을 * 로 채운다
            for (int i = col; i < 11; 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;            
            var orProcess = baseData.OrderBy(t => t.requestpart).GroupBy(t => t.requestpart);
            this.fpSpread1.Sheets[0].RowCount = 7+ orProcess.Count() + 1;

            foreach (var item in orProcess)
            {
                var RequestPart = item.FirstOrDefault().requestpart;
                this.fpSpread1.Sheets[0].Cells[row, 1].Value = RequestPart;

                //2번부터는 데이터를 넣어야 한다
                double sumOt = 0.0;
                double holytime = 0.0;
                int coldata = 2;
                for (int i = 2; i < 11; i++)
                {
                    var colName = fpSpread1.Sheets[0].Cells[6, i].Value.ToString();

                    //이 이름에 해당하는 데이터의 시간을 가져온다
                    double ot = 0.0;
                    double hrs = 0.0;
                    if (colName != "*")
                    {
                        //double holytime = 0.0;
                        var timeList = item.Where(t => t.process == 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;
                }

                //ETC영역계산
                {
                    //전체합산데이터와, 2~10까지의 데이터가 일치하지 않으면 그것이 ETC이다
                    var etchr = item.Sum(t => t.hrs);
                    var etcot = item.Sum(t => t.ot);

                    //현재데이터의  hrs의 합
                    var subtotal = 0.0;
                    for(int i = 2; i <11;i++)
                    {
                        var ivalue = fpSpread1.Sheets[0].Cells[row, i].Value;
                        if (ivalue != null) subtotal += (double)ivalue;
                    }
                    var etcval = (etchr + etcot) - subtotal;
                    fpSpread1.Sheets[0].Cells[row, 11].Value = etcval;
                }

                fpSpread1.Sheets[0].Cells[row, 12].CellType = numberCellType1;
                fpSpread1.Sheets[0].Cells[row, 12].ParseFormatString = "N1";
                fpSpread1.Sheets[0].Cells[row, 12].Formula = string.Format("SUM(C{0}:G{0})+L{0}", row + 1);
                
                //H8 /$I$4
                if (sumOt == 0.0) fpSpread1.Sheets[0].Cells[row, 13].Value = null; //OT합계
                else fpSpread1.Sheets[0].Cells[row, 13].Value = sumOt; //OT합계

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

                for (int i = 1; i <= 14; i++)
                {
                    if(i == 12) fpSpread1.Sheets[0].Cells[row, i].BackColor = Color.LightGray;
                    else 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 <= 14; 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;
        }

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

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

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