using FarPoint.Win;
using FCOMMON;
using GrapeCity.Win.Spread.InputMan.CellType;
using NetOffice.Attributes;
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 : fBase
    {
        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)
        {
            EnsureVisibleAndUsableSize();
            this.fpSpread1_Sheet2.AddSelection(2, 3, 4, 3);
            // fpSpread1_Sheet2.Columns[1, 0].AllowAutoSort = true;
            //this.fpSpread1_Sheet2.ColumnHeader.AutoTextIndex = 1;

            this.tbProcess.Items.Clear();
            tbProcess.Items.Add("--전체--");
            //var taProcess = new dsReportTableAdapters.ProcessListTableAdapter();
            var dtProcessList = FCOMMON.DBM.GroupUserProcessList();// taProcess.GetData(FCOMMON.info.Login.gcode);
            foreach (var dr in dtProcessList)
                tbProcess.Items.Add(dr);

            //사용자의 공정명을 선택해준다
            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 ta = new dsPRJTableAdapters.vJobReportForUserListTableAdapter();

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

            //일반사용자 목록 가져온다
            dsPRJ.vJobReportForUserListDataTable userlist;

            if (tbProcess.SelectedIndex <= 0)
            {
                //공정구분없이 전체사용자를 가져온다
                userlist = ta.GetData(FCOMMON.info.Login.gcode, "%");
                //  db.vJobReportForUser.Where(t => t.gcode == FCOMMON.info.Login.gcode).OrderBy(t => t.name).GroupBy(t => t.name);
            }
            else
            {
                userlist = ta.GetData(FCOMMON.info.Login.gcode, tbProcess.Text);
                //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 dr 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 taHolydayDateList = new dsJobReportTableAdapters.HolidayDateListTableAdapter();
            var taJobReportForUser = new dsJobReportTableAdapters.vJobReportForUserTableAdapter();
            var taCommon = new dsJobReportTableAdapters.CommonTableAdapter();


            this.fpSpread1.Sheets[0].ColumnCount = 12;
            //조회공정
            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;


            this.fpSpread1.Sheets[0].Cells[5, 11].BackColor = this.fpSpread1.Sheets[0].Cells[5, 10].BackColor;
            this.fpSpread1.Sheets[0].Cells[5, 11].ForeColor = this.fpSpread1.Sheets[0].Cells[5, 10].ForeColor;
            this.fpSpread1.Sheets[0].Cells[5, 11].Value = "총투입\n시간(%)";
            fpSpread1.Sheets[0].Columns[11].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
            fpSpread1.Sheets[0].Columns[11].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
            fpSpread1.Sheets[0].AddSpanCell(5, 11, 2, 1);

            //근문일수,시간
            var vSD = dts.Value.ToString("yyyy-MM-dd");
            var vED = dte.Value.ToString("yyyy-MM-dd");

            //휴가일수확인
            var drDays = taHolydayDateList.GetData(vSD, vED);
            // 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);

            //사용자목록을 가져온다
            dsJobReport.vJobReportForUserDataTable baseData;
            if (cmbUser.SelectedIndex > 0)
            {
                //사용자번호 
                var UserNo = cmbUser.Text.Substring(1, cmbUser.Text.IndexOf(']') - 1);
                baseData = taJobReportForUser.GetDataID(FCOMMON.info.Login.gcode, UserNo, vSD, vED);
                //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 = taJobReportForUser.GetByProcess(FCOMMON.info.Login.gcode, tbProcess.Text, vSD, vED);
                //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 = taJobReportForUser.GetByDate(FCOMMON.info.Login.gcode, vSD, vED);
                //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.type;
                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 != "휴가" && string.IsNullOrEmpty(t.svalue) == false).OrderBy(t => t.svalue).GroupBy(t => t.svalue);
            this.fpSpread1.ActiveSheetIndex = 0;
            var maxcol = 6;
            bool useOther = false;
            foreach (var item in orTypeName)
            {
                var dr = item.FirstOrDefault();

                if (col == maxcol + 1)   //엑셀파일 특성상 5개가 최고이다
                {
                    this.fpSpread1.Sheets[0].Cells[6, col - 1].Value = "[ Other ]";
                    useOther = true;
                }
                else if (col > maxcol + 1)
                {
                    useOther = true;
                }
                else
                {
                    this.fpSpread1.Sheets[0].Cells[6, col].Value = dr.svalue;
                }
                col++;
            }

            //항목이 6개 미만일 경우 제목을 * 로 변경해준다
            for (int i = col; i <= maxcol; 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 = taCommon.GetData(FCOMMON.info.Login.gcode, "15");
            // 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.type.Replace(" ", "") == prcitem.memo.Replace(" ", "")); //해당 프로세스에 해당하는 아이템을 가져온다

                //프로세스 이름 확인
                if (prcitem.memo == null) prcitem.memo = string.Empty;
                var processName = prcitem.memo.Trim();
                this.fpSpread1.Sheets[0].Cells[row, 1].Value = processName;

                if (processName == "Documentation (문서작업)")
                {

                }

                //2번부터는 데이터를 넣어야 한다
                double sumOt = 0.0;
                var sumvalue_hrs = 0.0;
                var sumvalue_ot = 0.0;

                for (int i = 2; i <= (useOther ? maxcol - 1 : maxcol); i++) //외부엑셀을 쓰다보니 열갯수가 5개로 제한되어있다.
                {
                    if (item.Any() == false) //자료가없다면 0으로 채운다
                    {
                        fpSpread1.Sheets[0].Cells[row, i].Value = null;
                    }
                    else
                    {
                        var colData = fpSpread1.Sheets[0].Cells[6, i].Value;    //해당 열의 제목을 취함
                        var colName = colData?.ToString() ?? string.Empty;// string.Empty;// fpSpread1.Sheets[0].Cells[6, i].Value.ToString();

                        //이 이름에 해당하는 데이터의 시간을 가져온다
                        double ot = 0.0;
                        double hrs = 0.0;
                        if (colName != "*" && colName.isEmpty() == false)
                        {
                            //해당 이름에 해당하는 데이트 취합
                            var timeList = item.Where(t => t.svalue.Replace(" ", "") == colName.Replace(" ", ""));
                            if (timeList != null)
                            {
                                hrs = (double)timeList.Sum(t => t.hrs);
                                ot = (double)timeList.Sum(t => t.ot);
                                sumOt += ot;
                                sumvalue_hrs += hrs;
                                sumvalue_ot += ot;
                            }
                        }
                        if (ot + hrs == 0.0) fpSpread1.Sheets[0].Cells[row, i].Value = null;  //값이 없는 경우는 nul 처리
                        else fpSpread1.Sheets[0].Cells[row, i].Value = ot + hrs;
                    }
                }

                //other 칸이 활성화되었다면 총량에서 뺴야한다 (lee jong myoung)
                if (useOther)
                {
                    var tot_hr = item.Sum(t => t.hrs);
                    var tot_ot = item.Sum(t => t.ot);
                    var othervalue = (tot_hr + tot_ot) - (sumvalue_hrs + sumvalue_ot);    //total - displayvalue 
                    if (othervalue == 0.0) fpSpread1.Sheets[0].Cells[row, maxcol].Value = null;  //값이 없는 경우는 nul 처리
                    else fpSpread1.Sheets[0].Cells[row, maxcol].Value = othervalue;
                }

                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}", row + 1);
                fpSpread1.Sheets[0].Cells[row, 8].Formula = string.Format("H{0}/$I$4", row + 1);

                var tot_process_ot = item.Sum(t => t.ot);
                var tot_process_hrs = item.Sum(t => t.hrs);
                var tot_time = baseData.Sum(t => t.hrs) + baseData.Sum(t => t.ot);
                if (tot_process_ot == 0.0) fpSpread1.Sheets[0].Cells[row, 9].Value = null; //OT합계
                else fpSpread1.Sheets[0].Cells[row, 9].Value = tot_process_ot; //OT합계

                var perc = ((tot_process_ot + tot_process_hrs) / tot_time) * 100.0; //총투입시간(%)
                if (perc == 0.0) fpSpread1.Sheets[0].Cells[row, 11].Value = null;
                else fpSpread1.Sheets[0].Cells[row, 11].Value = Math.Round(perc, 2);
                this.fpSpread1.Sheets[0].Cells[row, 11].Border = this.fpSpread1.Sheets[0].Cells[row, 3].Border;

                var 휴가데이터 = baseData.Where(t => t.process.Replace(" ", "") == processName.Replace(" ", "") && t.svalue.Replace(" ", "") == "휴가");
                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;
            }

            var total_value = baseData.Sum(t => t.hrs) + baseData.Sum(t => t.ot);


            //합계데이터
            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;

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


        }
    }
}
