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 fProjectList : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fProjectList()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsMSSQL.Projects.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => { 
                if(e1.KeyCode == Keys.F5)
                {
                    btSearch.PerformClick();
                }
            };
        }

        

        void __Closed(object sender, FormClosedEventArgs e)
        {
            timer1.Stop();
        }

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.tbRequest.Text = FCOMMON.info.Login.nameK;
            cmbDateType.SelectedIndex = 0;  //기본시작일 기준으로 한다

            cmbCate.Items.Clear();
            cmbCate.Items.Add("--전체--");
            //프로젝트내의 분류(category)를 확인하여 모로을 생성한다.
            var cn = FCOMMON.DBM.getCn();
            var sql = $"select category from projects where gcode='{FCOMMON.info.Login.gcode}'" +
                " and isnull(category,'') <> ''" +
                " group by category" +
                " order by category";
            var cmd = new System.Data.SqlClient.SqlCommand(sql, cn); cn.Open();
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                var category = rdr[0].ToString();
                cmbCate.Items.Add(category);
            }
            rdr.Close();
            cmd.Dispose();
            cn.Dispose();
            cmbCate.SelectedIndex = 0;

            this.cmbSort.Items.Clear();
            this.cmbSort.Items.AddRange(new string[] {
                "---",
                "Origin Cost",
                "Input Cost",
                "Effect Cost",
                "Asset No",
                "Project",
                "Champion",
                "Requestor",
                "Process",
                "Asset / 사용자 / 등록날짜",
                "Project No",
                "검토기한",
                "만료일자",
                "업데이트",
                "완료일자",
            });

            chk검토_CheckedChanged(this.chk검토, null);
            chk검토_CheckedChanged(this.chk진행, null);
            chk검토_CheckedChanged(this.chk대기, null);
            chk검토_CheckedChanged(this.chk보류, null);
            chk검토_CheckedChanged(this.chk완료, null);
            chk검토_CheckedChanged(this.chk취소, null);
            chk검토_CheckedChanged(this.chk완료보고, null);

            this.cmbProcess.Items.Clear();
            this.cmbProcess.Items.Add("전체");

            //프로젝트내의 분류(category)를 확인하여 모로을 생성한다.
            cn = FCOMMON.DBM.getCn();
            sql = $"select userprocess from projects where gcode='{FCOMMON.info.Login.gcode}'" +
                " and isnull(userprocess,'') <> ''" +
                " group by userprocess" +
                " order by userprocess";
            cmd = new System.Data.SqlClient.SqlCommand(sql, cn); cn.Open();
            rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                var userprocess = rdr[0].ToString();
                cmbProcess.Items.Add(userprocess);
            }
            rdr.Close();
            cmd.Dispose();
            cn.Dispose();






            if (cmbProcess.SelectedIndex < 0) cmbProcess.SelectedIndex = 0;

            this.cmbSort.SelectedIndex = 0;
            this.cmbYearS.Items.Clear();
            this.cmbYearE.Items.Clear();
            for (int i = 2010; i <= DateTime.Now.Year+1; i++)
            {
                cmbYearS.Items.Add(i.ToString("0000"));
                cmbYearE.Items.Add(i.ToString("0000"));
            }
            this.cmbYearS.Text = DateTime.Now.Year.ToString("0000");
            this.cmbYearE.Text = DateTime.Now.Year.ToString("0000");
            refreshData();

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.project));
            if (curLevel >= 5)
            {
                btSave.Visible = true;
            }
            else
            {
                btSave.Visible = false; //목록에서 저장버튼은 제거한다.
                btViewDel.Visible = false;
                fpSpread1.EditMode = false;
                fpSpread1.Sheets[0].SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Row;
                fpSpread1.EditModePermanent = false;
                fpSpread1.EditModeReplace = false;

                foreach (FarPoint.Win.Spread.Column col in fpSpread1.ActiveSheet.Columns)
                    col.Locked = true;
            }
            timer1.Start();

        }

        void refreshData()
        {

            string state = "";
            if (chk검토.Checked && chk진행.Checked && chk보류.Checked && chk완료.Checked && chk취소.Checked && chk대기.Checked)
            {
                state = "";
            }
            else if (chk검토.Checked == false && chk진행.Checked == false && chk보류.Checked == false && chk완료.Checked == false && chk취소.Checked == false && chk대기.Checked == false)
            {
                chk진행.Checked = true;
                state = "[status] = '진행'"; //아무것도 선택안하면 진행을 선택해준다.
            }
            else
            {
                state = "[status] in (";
                if (chk검토.Checked) state += "'검토'";

                if (chk보류.Checked)
                {
                    if (state.EndsWith("(") == false) state += ",";
                    state += "'보류'";
                }
                if (chk대기.Checked)
                {
                    if (state.EndsWith("(") == false) state += ",";
                    state += "'대기'";
                }
                if (chk진행.Checked)
                {
                    if (state.EndsWith("(") == false) state += ",";
                    state += "'진행'";
                }
                if (chk취소.Checked)
                {
                    if (state.EndsWith("(") == false) state += ",";
                    state += "'취소'";
                }
                if (chk완료.Checked)
                {
                    if (state.EndsWith("(") == false) state += ",";
                    state += "'완료'";
                }
                if (chk완료보고.Checked)
                {
                    if (state.EndsWith("(") == false) state += ",";
                    state += "'완료(보고)'";
                }
                state += ")";
            }

            //            SELECT  idx, status, pdate, name, usermain, usersub, request, reqstaff, sdate, edate, odate, memo, wuid, wdate, rev, pidx, userManager, level, part, process, costo, costn, cnt, remark_req, 
            //               remark_ans, ddate, progress, import
            //FROM     Projects
            //WHERE  (status LIKE @state) AND (ISNULL(userManager, '') LIKE @username OR
            //               ISNULL(usermain, '') LIKE @username OR
            //               ISNULL(usersub, '') LIKE @username)
            //ORDER BY (CASE WHEN [status] = '검토' THEN '0' WHEN ([status] = '진행') THEN '1' WHEN ([status] = '보류') THEN '2' WHEN ([status] = '완료') THEN '3' WHEN ([status] = '취소') 
            //               THEN '9' ELSE '5' END)

            //  var orgQuery = this.ta.Adapter.SelectCommand.CommandText;

            string State_Select = " SELECT  [idx],[pidx],[gcode],[isdel],[status],[asset],[level],[rev]," +
                " [process],[part],[pdate],[name],[userManager],[usermain],[usersub],[userhw2],[reqstaff]," +
                " [costo],[costn],[cnt],[remark_req],[remark_ans],[sdate],[ddate],[edate],[odate],[progress],bmajoritem," +
                " [memo],[wuid],[wdate],[orderno],[crdue],[import],[path],[userprocess],[bCost],[bFanOut],[bHighlight],[div]," +
                " dbo.getScheduleProgress(idx) as ProgressPrj,'' AS lasthistory,'' AS wws, '' AS wwo, '' AS wwe, '' AS wwd,model,serial," +
                " [championid], dbo.getProjectFinishRate(gcode, idx) AS finishrate,sfic,sfi_shiftcount, sfi_type, sfi_savetime, sfi_savecount," +
                " championid,designid,epanelid,softwareid,effect_tangible,effect_intangible," +
                "dbo.getUserName2(championid,usermanager) as name_champion," +
                "dbo.getUserName2(designid,usermain) as name_design," +
                "dbo.getUserName2(epanelid,userhw2) as name_epanel," +
                "dbo.getUserName2(softwareid,usersub) as name_software,category," +
                "ReqLine,ReqSite,ReqPackage,ReqPlant,pno,kdate,jasmin,sfi,'' AS lasthistoryD," +
                "(select max(pdate) from ProjectsHistory where pidx = Projects.idx) as lasthistory_date,dbo.getLastProjectScheduleNo(gcode,idx) as lastSchNo,cramount,panelimage,Priority,sfi_count" +
                " FROM Projects";
            //string State_Select = " SELECT  [idx],[pidx],[gcode],[isdel],[status],[asset],[level],[rev],[process],[part],[pdate],[name],[userManager],[usermain],[usersub],[userhw2],[reqstaff],[costo],[costn],[cnt],[remark_req],[remark_ans],[sdate],[ddate],[edate],[odate],[progress],[memo],[wuid],[wdate],[orderno],[crdue],[import],[path],[userprocess],[bCost],[bFanOut],[div],dbo.getScheduleProgress(idx) as ProgressPrj, dbo.getLastHistory(idx) AS lasthistory, dbo.getWorkWeek(sdate) AS wws, dbo.getWorkWeek(odate) AS wwo, dbo.getWorkWeek(edate) AS wwe, dbo.getWorkWeek(ddate) AS wwd FROM Projects";
            string State_where = " WHERE gcode=@gcode and isnull(div,'') <> 'EB' and ";

            if (btViewDel.Checked == false) State_where += " isnull(isdel,0)=0 and ";    //삭제보기 햇을 경우

           // if(chk비용절감.Checked== false) State_where += " isnull(bcost,0)=0 and ";    //삭제보기 햇을 경우

            //만료,완료,출고
            if (cmbDateType.SelectedIndex > 0)
            {
                var dateField = "";
                if (cmbDateType.SelectedIndex == 1) dateField = "sdate";
                else if (cmbDateType.SelectedIndex == 2) dateField = "ddate";
                else if (cmbDateType.SelectedIndex == 3) dateField = "edate";
                else if (cmbDateType.SelectedIndex == 4) dateField = "odate";
                State_where += " " + dateField + " between '" + cmbYearS.Text + "-01-01' and '" + cmbYearS.Text + "-12-31' AND ";
            }


            //   "ISNULL(usermain, '') LIKE @username OR " +
            //   "ISNULL(reqstaff, '') LIKE @username OR " +
            //   "ISNULL(usersub, '') LIKE @username) ";
            State_where += " (ISNULL(userManager, '') LIKE @username OR " +
             "ISNULL(usermain, '') LIKE @username OR " +
             "ISNULL(reqstaff, '') LIKE @username OR " +             
                "dbo.getUserName(championid) LIKE @username OR " +
                "dbo.getUserName(designid) LIKE @username OR " +                
                "dbo.getUserName(epanelid) LIKE @username OR " +
                "dbo.getUserName(softwareid) LIKE @username OR " +
             "ISNULL(usersub, '') LIKE @username) ";

            if (state != "") State_where += " AND " + state;
            if (cmbCate.SelectedIndex > 0) State_where += $" AND isnull(category,'') like '{cmbCate.Text}%'";
            if (cmbProcess.SelectedIndex > 0) State_where += " and isnull(userprocess,'') = '" + cmbProcess.Text.Trim() + "'";
            string State_order = " ORDER BY (CASE " +
                " WHEN ([status] = '진행') THEN '0' " +
                " WHEN ([status] = '검토') THEN '1' " +
                " WHEN ([status] = '대기') THEN '2' " +
                " WHEN ([status] = '완료') THEN '3' " +
                " WHEN ([status] = '완료(보고)') THEN '4' " +
                " WHEN ([status] = '보류') THEN '5' " +
                " WHEN ([status] = '취소') THEN '9' " +
                " ELSE '5' END),userManager,sdate";

            string request = "%";
            if (tbRequest.Text.Trim() != "") request = "%" + this.tbRequest.Text.Trim() + "%";

            System.Data.SqlClient.SqlCommand selCmd = new System.Data.SqlClient.SqlCommand();
            selCmd.Connection = ta.Connection;
            selCmd.CommandText = State_Select + State_where + State_order;
            selCmd.Parameters.Add("gcode", SqlDbType.VarChar).Value = FCOMMON.info.Login.gcode;
            selCmd.Parameters.Add("username", SqlDbType.VarChar);
            selCmd.Parameters["username"].Value = request;

            System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter();
            sda.SelectCommand = selCmd;

            this.dsMSSQL.Projects.Clear();
            sda.Fill(this.dsMSSQL.Projects);

            //this.ta.Adapter.SelectCommand = selCmd;
            //this.ta.Fill(this.dsMSSQL.Projects, state,request);
            //  this.ta.Adapter.SelectCommand.CommandText = orgQuery;
            this.dsMSSQL.Projects.AcceptChanges();

            sbSumE.Text = this.dsMSSQL.Projects.Sum(t => t.coste).ToString("N2");
            sbSumO.Text = this.dsMSSQL.Projects.Sum(t => t.costo).ToString("N2");
            sbSumI.Text = this.dsMSSQL.Projects.Sum(t => t.costn).ToString("N2");

            lbcnt1.Text = "--";
            lbcnt2.Text = "--";
            lbcnt3.Text = "--";
            lbcnt4.Text = "--";
            lbcnt5.Text = "--";
            lbcnt6.Text = "--";

            var grps = this.dsMSSQL.Projects.GroupBy(t => t.status);
            foreach (var grp in grps)
            {
                var cnt = grp.Count();
                if (grp.Key == "검토") lbcnt1.Text = cnt.ToString();
                else if (grp.Key == "진행") lbcnt2.Text = cnt.ToString();
                else if (grp.Key == "보류") lbcnt3.Text = cnt.ToString();
                else if (grp.Key == "취소") lbcnt4.Text = cnt.ToString();
                else if (grp.Key == "완료") lbcnt5.Text = cnt.ToString();
                else if (grp.Key == "완료(보고)") lbcnt6.Text = cnt.ToString();
            }

            FormattingData();
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        void FormattingData()
        {

            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var statindex = this.fpSpread1.ActiveSheet.Columns["Status"].Index;
            var hoighlightindex = this.fpSpread1.ActiveSheet.Columns["Highlight"].Index;
            var costindex = this.fpSpread1.ActiveSheet.Columns["costsave"].Index;
            var majorindex = this.fpSpread1.ActiveSheet.Columns["majoritem"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var hightlight = this.fpSpread1.ActiveSheet.GetValue(i, hoighlightindex);
                var state = this.fpSpread1.ActiveSheet.GetValue(i, statindex);
                var cost = this.fpSpread1.ActiveSheet.GetValue(i, costindex);
                var major = this.fpSpread1.ActiveSheet.GetValue(i, majorindex);

                string stateStr = string.Empty;
                string highstr = string.Empty;
                string coststr = string.Empty;
                string majorstr = string.Empty;

                if (hightlight != null) highstr = hightlight.ToString();
                if (state != null) stateStr = state.ToString();
                if (cost != null) coststr = cost.ToString();
                if (major != null) majorstr = major.ToString();


                if (highstr == "True")
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.Lime;
                else if (coststr == "True")
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.Gold;
                else if (majorstr == "True")
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.HotPink;
                else
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.White;

                switch (stateStr.ToLower())
                {
                    case "검토":
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Blue;
                        break;
                    case "취소":
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Red;
                        break;
                    case "진행":
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Green;
                        break;
                    case "보류":
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Tomato;
                        break;
                    case "완료(보고)":
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Gray;
                        break;
                    case "완료":
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Magenta;
                        break;
                    default:
                        this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Black;
                        break;
                }

            }
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            this.fpSpread1.ResumeLayout();
        }

        void funcSave(Boolean pmt)
        {
            this.Validate();
            this.bs.EndEdit();

            if (pmt)
            {
                var dlg = FCOMMON.Util.MsgQ("변경 사항을 저장하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            try
            {
                var cnt = this.ta.Update(this.dsMSSQL.Projects);//.UpdateAll(this.dsMSSQL.Projects);
                if(cnt == 0)
                {
                    util.MsgI("변경된 내용이 없습니다");
                }
                else dsMSSQL.Projects.AcceptChanges();
                FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

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

        }
        void Projects_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
        }

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

        void menu_partlist()
        {
            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.StartPosition = FormStartPosition.CenterScreen;
            f.Show();
        }
        private void partListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_partlist();
        }


        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.ResetVisible();
                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)
        {

        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            //사용자목록처리
            if (tbRequest.Text != "")
            {
                tbRequest.Text = string.Empty;
            }
            else tbRequest.Text = FCOMMON.info.Login.nameK;

            refreshData();
        }

        private void scheduleToolStripMenuItem_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 fProjectSchedule(dr.idx);
            f.MdiParent = this.MdiParent;
            f.Show();
        }

        private void makeRepeatToolStripMenuItem_Click(object sender, EventArgs e)
        {
            funcCopy();
        }
        void funcCopy()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;
            var dlg = FCOMMON.Util.MsgQ("선택된 프로젝트를 복사하시겠습니까?\n\n생성된 자료는 [검토] 상태로 전환 됩니다.");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
            {
                var ta = new dsPRJTableAdapters.QueriesTableAdapter();
                int? newidx = -1;
                var retval = ta.CopyProjectData(dr.idx, FCOMMON.info.Login.no, ref newidx);
                this.chk검토.Checked = true; //검토가안보이면 오류
                chk검토_CheckedChanged(this.chk검토, null);
                refreshData();
                if (newidx != null)
                {
                    var newdr = this.dsMSSQL.Projects.Where(t => t.idx == newidx).FirstOrDefault();
                    if(newdr == null)
                    {
                        util.MsgE($"복사된 자료가 조회되지 않았습니다.\n수동으로 조회 후 정보를 변경 하세요\nIDX:{newidx}");
                        return;
                    }
                    newdr.userprocess = FCOMMON.info.Login.process;
                    var f = new fProjectData(newdr);
                    if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.project));
                        if (curLevel < 5)
                        {
                            funcSave(false); //자동저장
                        }
                    }
                }
            }
        }

        void menu_iomap()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;
            var f = new fProjectIOMap(dr.idx);
            f.Show();
        }

        private void iOMapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menu_iomap();
        }

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

        private void btFind_Click(object sender, EventArgs e)
        {

            string search = tbFind.Text.Trim();
            if (search == "")
            {

                bs.Filter = "";
                tbFind.BackColor = SystemColors.Control;
                FormattingData();
            }
            else
            {
                try
                {
                    var cols = new string[] {
                        "name","process","reqstaff","usermain",
                        "orderno","usersub","userManager",
                        "remark_req"};
                    bs.Filter = FCOMMON.Util.MakeFilterString(cols, search);
                    tbFind.BackColor = Color.Lime;
                    tbFind.SelectAll();
                    tbFind.Focus();
                    FormattingData();
                }
                catch (Exception ex)
                {
                    bs.Filter = "";
                    FCOMMON.Util.MsgE(ex.Message);
                    tbFind.BackColor = Color.Red;
                    FormattingData();
                }
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            funcDelete();
        }
        void funcDelete()
        {
            var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
            {
                bs.RemoveCurrent();

                //일반사용자는 바로 저장되도록 함
                int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.project));
                if (curLevel < 5)
                {
                    funcSave(false); //자동저장
                }
            }
        }
        private void 엑셀파일로저장ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = ("excel|*.xls");
            var dlg = sd.ShowDialog();
            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                this.fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);

                var dlga = FCOMMON.Util.MsgQ("파일생성 완료\n파일을 확인 할까요?\n" + sd.FileName);
                if (dlga == DialogResult.Yes)
                {
                    FCOMMON.Util.RunExplorer(sd.FileName);
                }
            }
        }

        private void 메일발송주소관리ToolStripMenuItem_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 fMailList(dr.idx);
            f.ShowDialog();
        }

        bool Alert_DDate = false;
        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            //히스토리 데이터를 업데이트하고 첫번재 자료를 표시한다.
            var drv = this.bs.Current as DataRowView;
            if (drv == null)
            {
                this.label1.Text = "프로젝트가 선택되지 않았습니다";
                return;
            }
            var dr = drv.Row as dsPRJ.ProjectsRow;
            this.label1.Text = string.Format("[{0}] {1}", dr.name, dr.memo);

            button2.BackColor = dr.jasmin > 0 ? Color.Lime : SystemColors.Control;

            if (dr.status == "진행" && dr.edate.isEmpty())
            {
                if (DateTime.TryParse(dr.ddate, out DateTime dd))
                {
                    if (dd <= DateTime.Now) Alert_DDate = true;
                    else Alert_DDate = false;
                }
                else Alert_DDate = false;
            }
            else Alert_DDate = false;




            var progress = FCOMMON.DBM.GetProjectBuyInfo(dr.idx);
            //var sql = "select  ((sum((case when isnull(qtybuy,0) = isnull(qtyin,0) then 1 else 0 end))*1.0) / count(*))*100 " +
            //    $" from ProjectsPart where project = {dr.idx}" +
            //    $" and isnull(qtybuy,0) <> 0";
            //var stR_result = FCOMMON.DBM.ExecuteScalar(sql);
            if (progress < 0.1f)
            {
                tableLayoutPanel3.Visible = false;
            }
            else
            {
                tableLayoutPanel3.Visible = true;
                this.label17.Text = string.Format("구매 완료({0:N0}%)", progress);
                this.prb1.ProgressMin = 0;
                this.prb1.ProgressMax = 100;
                this.prb1.ProgressValue = progress;
            }

            try
            {
                taHist.Fill(this.dsMSSQL.ProjectsHistory, dr.idx);
            }
            catch
            {

            }
            try
            {
                taHistD.Fill(this.dsMSSQL.EETGW_ProjecthistoryD, dr.idx);
            }
            catch { }
        }

        private void button1_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 fProejctHistory(dr.idx);
            f.StartPosition = FormStartPosition.CenterScreen;
            var dlg = f.ShowDialog();
            bs_CurrentChanged(sender, e);
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var newdr = this.dsMSSQL.Projects.NewProjectsRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.sdate = DateTime.Now.ToString("yyyy-MM-dd");
            //newdr.userManager = FCOMMON.info.Login.nameK;
            newdr.championid = FCOMMON.info.Login.no;
            newdr.progress = 0;
            newdr.userprocess = FCOMMON.info.Login.process;
            newdr.costn = 0;
            newdr.costo = 0;
            newdr.cnt = 1;
            newdr.pno = 0; //신규는 0번으로 한다
            newdr.name = "Project Title";
            var f = new fProjectData(newdr);
            f.StartPosition = FormStartPosition.CenterScreen;
            var dlg = f.ShowDialog();
            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                this.dsMSSQL.Projects.AddProjectsRow(newdr);
                try
                {

                    ta.Update(newdr);
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE("Save Error\n" + ex.Message);
                }

            }
            else newdr.Delete();
        }

        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.ProjectsRow;
            var f = new fProjectData(dr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.project));
                if (curLevel < 5)
                {
                    funcSave(false); //자동저장
                }
                FormattingData();
            }
        }

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

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

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //                ---
            //Origin Cost
            //Input Cost
            //Effect Cost
            //Asset No
            //Project
            //Champion
            //Requestor
            //Process
            switch (cmbSort.SelectedIndex)
            {
                case 1:
                    if (this.bs.Sort == "costo") this.bs.Sort = "costo desc";
                    else this.bs.Sort = "costo";
                    break;
                case 2:
                    if (this.bs.Sort == "costn") this.bs.Sort = "costn desc";
                    else this.bs.Sort = "costn";
                    break;
                case 3:
                    if (this.bs.Sort == "coste") this.bs.Sort = "coste desc";
                    else this.bs.Sort = "coste";
                    break;
                case 4:
                    if (this.bs.Sort == "asset") this.bs.Sort = "asset desc";
                    else this.bs.Sort = "asset";
                    break;
                case 5:
                    if (this.bs.Sort == "[name]") this.bs.Sort = "[name] desc";
                    else this.bs.Sort = "[name]";
                    break;
                case 6:
                    if (this.bs.Sort == "userManager") this.bs.Sort = "userManager desc";
                    else this.bs.Sort = "userManager";
                    break;
                case 7:
                    if (this.bs.Sort == "reqstaff") this.bs.Sort = "reqstaff desc";
                    else this.bs.Sort = "reqstaff";
                    break;
                case 8:
                    if (this.bs.Sort == "process") this.bs.Sort = "process desc";
                    else this.bs.Sort = "process";
                    break;
                case 9:
                    //"Asset / 사용자 / 등록날짜"
                    var sort = "asset,usermain,pdate";
                    if (this.bs.Sort == sort) this.bs.Sort = sort;
                    else this.bs.Sort = sort;
                    break;
                case 10:
                    this.bs.Sort = "pno";
                    break;
                case 11://검토기한 230209
                    this.bs.Sort = "kdate";
                    break;
                case 12: //만료일자
                    this.bs.Sort = "ddate desc";
                    break;
                case 13: //업데이트
                    this.bs.Sort = "lasthistory_date";
                    break;
                case 14: //완료일자
                    this.bs.Sort = "edate desc";
                    break;
                default:
                    this.bs.Sort = "";
                    break;
            }
        }

        private void btCopy_Click(object sender, EventArgs e)
        {
            funcCopy();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            menu_partlist();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            menu_iomap();
        }

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

        private void 공유폴더ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showfolder();
        }
        void showfolder()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;

            var tbPath = dr.path;

            if (tbPath == "") tbPath = "/" + dr.idx.ToString();

            if (tbPath.StartsWith("\\") == false)
            {
                if (tbPath.StartsWith("/")) tbPath = tbPath.Replace("/", "\\");
                else tbPath = "\\" + tbPath;
            }
            //\\10.131.32.29\Data
            var datapath = FCOMMON.DBM.getCodeSvalue("55", "01");
            var serverpath = System.IO.Path.Combine(datapath, "Data", "Project");
            if (System.IO.Directory.Exists(serverpath) == false)
            {
                FCOMMON.Util.MsgE("프로젝트 기본경로가 존재하지 않아 진행할 수 없습니다\n\n" +
                    serverpath);
                return;
            }

            var path = serverpath + tbPath;
            if (System.IO.Directory.Exists(path) == false)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(path);

                    string[] subdir = new string[] { "Source", "Document", "Draw", "Estimate" };
                    foreach (var dir in subdir)
                        System.IO.Directory.CreateDirectory(path + "\\" + dir);

                }
                catch (Exception eX)
                {
                    FCOMMON.Util.MsgE("프로젝트 저장소 생성실패\n" + eX.Message);
                    return;
                }
            }

            FCOMMON.Util.RunExplorer(path);
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            showfolder();
        }

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

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

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void cmbDateType_Click(object sender, EventArgs e)
        {

        }

        private void cmbYearE_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            var f = new fProjectSummary();
            f.Show();
        }

        private void chk검토_CheckedChanged(object sender, EventArgs e)
        {
            var but = sender as ToolStripButton;
            but.ForeColor = but.Checked ? Color.Blue : Color.Black;
            but.Font = but.Checked ? new Font("맑은 고딕", 10, FontStyle.Bold) : new Font("맑은 고딕", 10);
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            var f = new JobReport_.rJobReportPrjSche();
            f.Show();
        }

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

            if (dr.jasmin < 1)
            {
                FCOMMON.Util.MsgE($"프로젝트 정보에 자스민 TASK ID가 입력되지 않았습니다");
                return;
            }
            var url = $"https://scwa.amkor.co.kr/jasmine/view/{dr.jasmin}";
            FCOMMON.Util.RunExplorer(url);
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void bsHist_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bsHist.Current as DataRowView;
            if (drv == null)
            {
                label4.BackColor = SystemColors.Control;
                return;
            }
            var dr = drv.Row as dsPRJ.ProjectsHistoryRow;

            if (dr.IspdateNull()) label4.BackColor = SystemColors.Control;
            else if (DateTime.TryParse(dr.pdate, out DateTime dt_pdate))
            {
                var ts = DateTime.Now - dt_pdate;
                if (ts.TotalDays > 7) label4.BackColor = Color.Tomato;
                else label4.BackColor = Color.Lime;
            }
            else label4.BackColor = SystemColors.Control;



        }

        private void bsHistD_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bsHistD.Current as DataRowView;
            if (drv == null)
            {
                sbDateMemo.BackColor = SystemColors.Control;
                return;
            }
            var dr = drv.Row as dsPRJ.EETGW_ProjecthistoryDRow;

            if (dr.IspdateNull()) sbDateMemo.BackColor = SystemColors.Control;
            else if (DateTime.TryParse(dr.pdate, out DateTime dt_pdate))
            {
                var ts = DateTime.Now - dt_pdate;
                if (ts.TotalDays > 7) sbDateMemo.BackColor = Color.Tomato;
                else sbDateMemo.BackColor = Color.Lime;
            }
            else sbDateMemo.BackColor = SystemColors.Control;
        }

        private void label31_Click(object sender, EventArgs e)
        {

            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;

            //프로젝트 메모 추가
            var newdr = this.dsMSSQL.EETGW_ProjecthistoryD.NewEETGW_ProjecthistoryDRow();
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.remark = string.Empty;
            newdr.pidx = dr.idx;
            var f = new fHistAddDay(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
                dsMSSQL.EETGW_ProjecthistoryD.AddEETGW_ProjecthistoryDRow(newdr);
                var cnt = taHistD.Update(newdr);
                if (cnt < 1) FCOMMON.Util.MsgE("추가가 실패 되었습니다");
                else bs_CurrentChanged(null, null);
            }
        }
        private void label11_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsRow;


            //주간진행내용 추가
            var newdr = this.dsMSSQL.ProjectsHistory.NewProjectsHistoryRow();
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.remark = string.Empty;
            newdr.pidx = dr.idx;

            var f = new fHistAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
                dsMSSQL.ProjectsHistory.AddProjectsHistoryRow(newdr);
                var cnt = taHist.Update(newdr);
                if (cnt < 1) FCOMMON.Util.MsgE("추가가 실패 되었습니다");
                else bs_CurrentChanged(null, null);
            }
        }




        private void rtMemo_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //프로젝트메모편집

            var drv = this.bsHistD.Current as DataRowView;
            if (drv == null) return;

            var newdr = drv.Row as dsPRJ.EETGW_ProjecthistoryDRow;
            var f = new fHistAddDay(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
                var cnt = taHistD.Update(newdr);
                if (cnt < 1) FCOMMON.Util.MsgE("편집이 실패 되었습니다");
            }
        }

        private void richTextBox2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //주간진행내용편집

            var drv = this.bsHist.Current as DataRowView;
            if (drv == null) return;

            var newdr = drv.Row as dsPRJ.ProjectsHistoryRow;
            var f = new fHistAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
                taHist.Update(newdr);
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Alert_DDate)
            {
                if (label8.BackColor == Color.Gold)
                    label8.BackColor = SystemColors.Control;
                else
                    label8.BackColor = Color.Gold;
            }
            else label8.BackColor = SystemColors.Control;
        }

        private void cmbDateType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbYearS.Enabled = cmbDateType.SelectedIndex != 0;
        }
    }
}