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;
using util = FCOMMON.Util;

namespace FPJ0000
{
    public partial class fJobReportAI : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fJobReportAI()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsMSSQL.JobReport.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        Boolean binit = false;

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();

            //공정목록
            //var taProc = new dsReportTableAdapters.ProcessListTableAdapter();
            var dtProcList = FCOMMON.DBM.GroupUserProcessList();//taProc.GetData(FCOMMON.info.Login.gcode);
            cmbProcess.Items.Clear();
            cmbProcess.Items.Add("--전체--");
            foreach (var dr in dtProcList)
            {
                cmbProcess.Items.Add(dr);
            }
            cmbProcess.Text = FCOMMON.info.Login.process;
            if (cmbProcess.SelectedIndex < 0) cmbProcess.SelectedIndex = 0; //공정이 없는 사람은 전체보기로 함

            btSave.Visible = true;

            btDebug.Visible = FCOMMON.info.Login.no == "dev";

            refreshData();
            binit = true;

        }

        private void cmbProcess_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (binit == false) return;
        }
        private void cmbProcess_Click(object sender, EventArgs e)
        {

        }



        void refreshData(bool tagonly = false)
        {
            this.ta.Fill(this.dsMSSQL.EETGW_JobReport_AutoInput, FCOMMON.info.Login.gcode);

            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            FormattingData();
        }
        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var delindex = this.fpSpread1.ActiveSheet.Columns["pidx"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var state = this.fpSpread1.ActiveSheet.GetValue(i, delindex);
                string stateStr = string.Empty;
                if (state != null) stateStr = state.ToString();

                switch (stateStr.ToLower())
                {
                    case "-1":
                        this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.WhiteSmoke;
                        break;
                    default:
                        this.fpSpread1.ActiveSheet.Rows[i].BackColor = SystemColors.Window;
                        break;
                }
            }
            this.fpSpread1.ResumeLayout();
        }
        void funcSave()
        {
            this.Validate();
            this.bs.EndEdit();
            try
            {
                this.ta.Update(this.dsMSSQL);
                FormattingData();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }
        }

        private void projectsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            funcSave();

        }
        void Projects_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["pdate"] = DateTime.Now.ToString("yyyy-MM-dd");
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["status"] = "진행 완료";//other
            e.Row["uid"] = FCOMMON.info.Login.no; //이름을 직접 기록
            e.Row["hrs"] = 8.0;
            e.Row["ot"] = 0.0;
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void partListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;
            var f = new fPartList(dr.idx);
            f.MdiParent = this.MdiParent;
            f.Show();
        }


        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
                this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                col.Width = 100;
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var newdr = this.dsMSSQL.EETGW_JobReport_AutoInput.NewEETGW_JobReport_AutoInputRow();
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.uid = FCOMMON.info.Login.no;
            newdr.gcode = FCOMMON.info.Login.gcode;
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;

            var f = new JobReport_.fJobReport_AddAI(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.dsMSSQL.EETGW_JobReport_AutoInput.AddEETGW_JobReport_AutoInputRow(newdr);
                int cnt = this.ta.Update(newdr);
                newdr.AcceptChanges();
                FormattingData();
                if (cnt != 1)
                    FCOMMON.Util.MsgE("자료가 추가되지 않았습니다.\n\n잠시 후 다시 시도하세요");
            }
            else newdr.Delete();
        }

        private void btFind_Click(object sender, EventArgs e)
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.Trim() == "")
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    var collist = new string[] { "requestpart", "package", "projectname", "process", "[type]", "description", "tag" };
                    string filter = ""; // "itemna like ? or package like ? or projectname like ? or process like ? or [type] like ? or description like ?";
                    foreach (var col in collist)
                    {
                        if (filter != "") filter += " or ";
                        filter += col + " like ?";
                    }
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            funcEdit();
        }

        void funcEdit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.EETGW_JobReport_AutoInputRow;
            if (dr.uid != FCOMMON.info.Login.no && FCOMMON.info.Login.level < 5)
            {
                FCOMMON.Util.MsgE("타인의 자료는 추가/변경/삭제 할 수 없습니다.\n관리자는 변경할 수 있습니다");
                return;
            }

            var f = new JobReport_.fJobReport_AddAI(dr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (dr.RowState != DataRowState.Unchanged)
                {
                    int cnt = this.ta.Update(dr);
                    dr.AcceptChanges();
                    FormattingData();
                }
            }
            else dr.RejectChanges();
        }

        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "jobreport.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                FCOMMON.Util.MsgI("다음 파일이 생성 되었습니다.\n\n" + sd.FileName);
            }
        }

        private void btCopy_Click(object sender, EventArgs e)
        {
            funcCopy(); //190509
        }
        void funcCopy()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.EETGW_JobReport_AutoInputRow;

            //현재 데이터를 입력하여 신규 추가를 한다.
            var newdr = this.dsMSSQL.EETGW_JobReport_AutoInput.NewEETGW_JobReport_AutoInputRow();
            FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.uid = FCOMMON.info.Login.no;
            //newdr.description = "";
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd"); //190509
            newdr.idx = -1;
            newdr.hrs = 8.0;
            newdr.ot = 0.0;
            newdr.EndEdit();

            //var newdr = this.dsMSSQL.JobReport.NewJobReportRow();
            var f = new JobReport_.fJobReport_AddAI(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.dsMSSQL.EETGW_JobReport_AutoInput.AddEETGW_JobReport_AutoInputRow(newdr);
                this.ta.Update(newdr);
                newdr.AcceptChanges();
            }
            else newdr.Delete();
        }

        private void btDel_Click(object sender, EventArgs e)
        {
            funcDelete();
        }
        void funcDelete()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.EETGW_JobReport_AutoInputRow;

            var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            dr.Delete();
            try
            {
                this.ta.Update(dr);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("삭제실패\n\n" + ex.Message);
            }
        }


        private void 복사ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcCopy();
        }

        private void 편집ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcEdit();
        }

        private void 삭제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcDelete();
        }


        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btDebug_Click(object sender, EventArgs e)
        {

            var dlg = util.MsgQ("진짜 실행?");
            if (dlg != DialogResult.Yes) return;

            var cnt = 0;
            var db = new dsJobReportTableAdapters.HolidayLIstTableAdapter();// EEEntities();
            var taJobReportQuery = new dsJobReportTableAdapters.QueriesTableAdapter();
            var taJobReport = new dsPRJTableAdapters.JobReportTableAdapter();

            //근무일자 확인
            var dt = new FPJ0000.dsPRJ.JobReportDataTable();
            foreach (dsPRJ.EETGW_JobReport_AutoInputRow dr in this.dsMSSQL.EETGW_JobReport_AutoInput)
            {
                if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached) continue;
                if (dr.autoinput != "L") continue;

                //시작일자부텅 오늘까지 데이터를 확인한다.
                var sd = DateTime.Parse(dr.pdate);
                while (true)
                {
                    if (sd > DateTime.Now) break;
                    //이날짜가 일반 날짜라면 데이터를 기록한다.
                    var dayinfo = db.GetOne(sd.ToString("yyyy-MM-dd")).FirstOrDefault();// holilist.Where(t => t.pdate == sd.ToString("yyyy-MM-dd")).FirstOrDefault();
                    if (dayinfo.free == true)
                    {
                        sd = sd.AddDays(1);
                        continue; //휴일은 처리하지 않는다
                    }

                    //그냥 생성된자료가 없어야한다
                    var vPdate = sd.ToString("yyyy-MM-dd");
                    if (taJobReportQuery.ExistUserData(FCOMMON.info.Login.gcode, vPdate, dr.uid) > 0)// db.JobReport.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.pdate == vPdate && t.uid == dr.uid).Any())
                    {
                        sd = sd.AddDays(1);
                        continue;
                    }

                    //이데이터를 그대로 생성해준다.
                    var newdr = dt.NewJobReportRow();// new JobReport();
                    newdr.gcode = FCOMMON.info.Login.gcode;
                    newdr.wuid = FCOMMON.info.Login.no;
                    newdr.wdate = DateTime.Now;
                    newdr.pdate = sd.ToString("yyyy-MM-dd");
                    newdr.import = false;
                    newdr.hrs = dr.hrs;
                    newdr.ot = dr.ot;
                    newdr.process = dr.process;
                    newdr.projectName = dr.projectName;
                    newdr.pidx = dr.pidx;
                    newdr.package = dr.package;
                    newdr.autoinput = true;
                    newdr.description = dr.description;
                    newdr.description2 = dr.description2;
                    newdr.remark = dr.remark;
                    newdr.requestpart = dr.requestpart;
                    newdr.status = dr.status;
                    newdr.tag = dr.tag;
                    newdr.uid = dr.uid;
                    dt.AddJobReportRow(newdr);// db.JobReport.Add(newdr);
                    cnt += 1;//
                    sd = sd.AddDays(1);
                }


            }



            if (cnt > 0)
            {
                cnt = taJobReport.Update(dt);
                dt.AcceptChanges();
                FCOMMON.Util.MsgI($"{cnt} 건의 업무일지가 자동 생성 되었습니다");
            }

            taJobReport.Dispose();
            taJobReportQuery.Dispose();

        }
    }
}