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 fProjectListU : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fProjectListU()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsMSSQL.Projects.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

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

            //분류 - 190905
            //var dt_cate = FCOMMON.DBM.getCodeTable("20");
            //cmbCate.Items.Clear();
            //cmbCate.Items.Add("--전체--");
            //foreach (DataRow dr in dt_cate.Rows)
            //    cmbCate.Items.Add(dr["Value"].ToString());
            //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("전체");
            //var procesList = FCOMMON.DBM.getProcessList();
            //foreach (DataRow dr in procesList.Rows)
            //    cmbProcess.Items.Add(dr["Value"].ToString());
            ////cmbProcess.Text = FCOMMON.info.Login.process;
            //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; i++)
            //{
            //    cmbYearS.Items.Add(i.ToString("0000"));
            //    cmbYearE.Items.Add(i.ToString("0000"));
            //}
            //this.cmbYearS.Text = DateTime.Now.AddYears(-2).Year.ToString("0000");
            //this.cmbYearE.Text = DateTime.Now.Year.ToString("0000");
            dts.Value = DateTime.Now.AddDays(-7);
            dte.Value = DateTime.Now.AddDays(-1);

            Refresh_UserList();
            // 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; //목록에서 저장버튼은 제거한다.

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


        }

        void refreshData()
        {

            string state = "";
            string State_Select =
                "SELECT  [idx],pno,[status],[process],[part],[pdate], " +
                "ReqSite,ReqPlant,ReqLine,ReqPackage,[name],'' as remark_ans,[reqstaff], [costo],[costn],[cnt], " +
                "[remark_req],[sdate],[ddate],[edate],[odate], [orderno], " +
                "[path], dbo.getScheduleProgress(idx) as ProgressPrj,[bHighlight],[bCost],[bFanOut], " +
                "effect_intangible,effect_tangible, " +
                "dbo.getProjectFinishRate(gcode, idx) AS finishrate, sfi_type, sfi_savetime, sfi_savecount, " +
                "championid, designid, assemblyid, epanelid, softwareid, userAssembly, " +
                "dbo.getUserName2(championid, usermanager) as name_champion, " +
                "dbo.getUserName2(designid, usermain) as name_design, " +
                "dbo.getUserName2(assemblyid, userAssembly) as name_assembly, " +
                "dbo.getUserName2(epanelid, userhw2) as name_epanel, " +
                "dbo.getUserName2(softwareid, usersub) as name_software,jasmin,[memo],wuid,wdate,gcode" +
                " 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 ";
            State_where += " championid = @username and sdate >= @sdate";

            if (state != "") State_where += " AND " + state;
            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),sdate desc";

            string request = cmbUserList.Text.Split('|')[1].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.Add("sdate", SqlDbType.VarChar);
            selCmd.Parameters["username"].Value = request;
            selCmd.Parameters["sdate"].Value = DateTime.Now.AddYears(-5).ToString("yyyy-MM-dd");

            System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter();
            sda.SelectCommand = selCmd;
            this.dsMSSQL.Projects.Clear();
            sda.Fill(this.dsMSSQL.Projects);

            //제목줄을 업데이트한ㄷ remark_ans 열에
            foreach (dsPRJ.ProjectsRow dr in this.dsMSSQL.Projects)
            {
                var plant = "";
                var site = "";
                var line = "";
                if (dr.IsReqSiteNull() == false) site = dr.ReqSite;
                if (dr.IsReqPlantNull() == false) plant = dr.ReqPlant;
                if (dr.IsReqLineNull() == false) line = dr.ReqLine;
                if (site.isEmpty()) site = "{SITE}";
                else site = $"[{site}]";
                if (plant.isEmpty()) plant = "{PLANT}";

                if (line.isEmpty()) line = "{LINE},";
                else if (line == "N/A" || line == "NA") line = string.Empty;
                else line = $"Line {line},";
                var fullname = $"{site} {plant},{line}{dr.name}";
                dr.name2 = fullname.Trim();
            }
            this.dsMSSQL.Projects.AcceptChanges();


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

        void Refresh_UserList()
        {
            var ta = new Project.DSProjectSummaryTableAdapters.ProjectUserListTableAdapter();
            var dt = ta.GetData(FCOMMON.info.Login.gcode);
            cmbUserList.Items.Clear();
            foreach (Project.DSProjectSummary.ProjectUserListRow dr in dt)
            {
                cmbUserList.Items.Add($"{dr.username}|{dr.championid}");
            }
            cmbUserList.Text = $"{FCOMMON.info.Login.nameK}|{FCOMMON.info.Login.no}";
        }

        /// <summary>
        /// 프로젝트별 시간투입시간을 갱신한다
        /// </summary>
        void Refresh_ProjectHrs()
        {
            var ta = new Project.DSProjectSummaryTableAdapters.ProjectHrsTableAdapter();
            var uid = cmbUserList.Text.Split('|')[1].Trim();
            var sd = dts.Value;// DateTime.Now.AddDays(-7);
            var ed = dte.Value;// DateTime.Now;
            ta.Fill(dsProjectSummary1.ProjectHrs, FCOMMON.info.Login.gcode, uid, sd.ToString("yyyy-MM-dd"), ed.ToString("yyyy-MM-dd"));

            grpsum.Text  =$"집계기간:{sd.ToString("yyyy-MM-dd")}~{ed.ToString("yyyy-MM-dd")}";
            //var ss = chart1.Series[0];
            //ss.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.String;
            //ss.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            //ss.Points.Clear();

            //총량확인
            var sumhrs = dsProjectSummary1.ProjectHrs.Sum(t => t.hrs);
            foreach (Project.DSProjectSummary.ProjectHrsRow dr in dsProjectSummary1.ProjectHrs)
            {
                dr.perc = (float)((dr.hrs / sumhrs) * 100f);
                //ss.Points.Add(new System.Windows.Forms.DataVisualization.Charting.DataPoint
                //{
                //    AxisLabel = (dr.prj == "___" ? "(기타)" : dr.prj),
                //    YValues = new double[] { dr.hrs }
                //});
                if (dr.prj.Length > 40)
                    dr.shortname = dr.prj.Substring(0, 40) + "...";
                else dr.shortname = dr.prj;
                //ss.Points.Add( dr.hrs);
            }
            dsProjectSummary1.ProjectHrs.AcceptChanges();

            //프로젝트참여율 확인
             foreach(dsPRJ.ProjectsRow dr in this.dsMSSQL.Projects)
            {
                var data = dsProjectSummary1.ProjectHrs.Where(t => t.prj == dr.name).FirstOrDefault();
                if (data != null) dr.chamyeo = data.perc;
                else dr.SetchamyeoNull();
            }
            this.dsMSSQL.Projects.AcceptChanges();

            //this.chart1.Invalidate();
           // arDatagridView1.AutoResizeColumns();
            this.bsProjectHRS.Sort = "perc desc";
        }


        void FormattingData()
        {

            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var statindex = this.fpSpread1.ActiveSheet.Columns["Status"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var state = this.fpSpread1.ActiveSheet.GetValue(i, statindex);
                string stateStr = string.Empty;
                if (state != null) stateStr = state.ToString();

                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
            {
                this.ta.Update(this.dsMSSQL.Projects);//.UpdateAll(this.dsMSSQL.Projects);
                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);
                refreshData();
                if (newidx != null)
                {
                    var newdr = this.dsMSSQL.Projects.Where(t => t.idx == newidx).FirstOrDefault();
                    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);

                FCOMMON.Util.MsgI("파일생성 완료\n\n" + 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();
        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            //히스토리 데이터를 업데이트하고 첫번재 자료를 표시한다.
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            
            var dr = drv.Row as dsPRJ.ProjectsRow;
            rt_aft.Rtf = dr.CMP_After;
            rt_bef.Rtf = dr.CMP_Before;
            rt_cmp.Rtf = dr.CMP_Description;
                        

            if (dr.IslasthistoryNull() == false)
            {
                if (dr.lasthistory.StartsWith("["))
                {
                    var dtstr = dr.lasthistory.Substring(1, 10);
                    if(DateTime.TryParse(dtstr,out DateTime ldt))
                    {
                        var ts = DateTime.Now - ldt;
                        if (ts.TotalDays >= 7) richTextBox2.BackColor = Color.WhiteSmoke;
                        else richTextBox2.BackColor = Color.White;
                    }
                    else richTextBox2.BackColor = Color.WhiteSmoke;
                }
                else richTextBox2.BackColor = Color.WhiteSmoke;
            }
            else richTextBox2.BackColor = Color.WhiteSmoke;


            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
            {

            }
        }

        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;
            //    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 toolStripButton7_Click(object sender, EventArgs e)
        {
            refreshData();
        }

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

        private void toolStrip2_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

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

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

        private void button1_Click_2(object sender, EventArgs e)
        {
            //FCOMMON.Util.MsgI("이전사람선택하기");
            if (cmbUserList.SelectedIndex > 0)
                cmbUserList.SelectedIndex -= 1;
            refreshData();
        }

        private void button2_Click_2(object sender, EventArgs e)
        {
            //FCOMMON.Util.MsgI("다음사람선택하기");
            if (cmbUserList.SelectedIndex < cmbUserList.Items.Count - 1)
                cmbUserList.SelectedIndex += 1;
            refreshData();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Refresh_UserList();
        }
    }
}