using FarPoint.CalcEngine;
using FCOMMON;
using FPJ0000.Project;
using NetOffice.OutlookApi;
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 fProjectListUser : FCOMMON.fBase
    {
        string fn_fpcolsize1 = "";
        string fn_fpcolsize2 = "";
        public fProjectListUser()
        {
            InitializeComponent();
            fn_fpcolsize1 = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + "_1.ini");
            fn_fpcolsize2 = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + "_2.ini");
            this.dsMSSQL.Projects.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;
        }

        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 = 1;  //기본시작일 기준으로 한다


            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; //목록에서 저장버튼은 제거한다.
                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 = "[status] <> '취소'";


            //            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]," +
                " [memo],[wuid],[wdate],[orderno],[crdue],[import],[path],[userprocess],[bCost],[bFanOut],[bHighlight],[div]," +
                " model,serial," +
                " [championid], dbo.getProjectFinishRate(gcode, idx) AS finishrate,sfi_shiftcount, sfi_type, sfi_savetime, sfi_savecount," +
                " championid,designid,assemblyid,epanelid,softwareid,userAssembly,effect_tangible,effect_intangible," +
                "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,category," +
                "ReqLine,ReqSite,ReqPackage,ReqPlant,pno,kdate,jasmin,sfi,'' AS lasthistoryD" +
                " 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 (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 " +
             "ISNULL(userAssembly, '') LIKE @username OR " +
                "dbo.getUserName(championid) LIKE @username OR " +
                "dbo.getUserName(designid) LIKE @username OR " +
                "dbo.getUserName(assemblyid) 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;


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



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


            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize1);
            //  FPUtil.ColSizeLoad(ref this.fpSpread2, fn_fpcolsize2);

            //요약하여 데이터 추가
            this.dSProjectSummary.ProjectCountForUser.Clear();

            //process, uid,user
            List<string> uids = new List<string>();
            var id_cmp = this.dsMSSQL.Projects.Where(t => string.IsNullOrEmpty(t.championid) == false).GroupBy(t => t.championid).Select(t => t.Key + "|" + t.First().name_champion + "|").ToList();
            var id_des = this.dsMSSQL.Projects.Where(t => string.IsNullOrEmpty(t.designid) == false).GroupBy(t => t.designid).Select(t => t.Key + "|" + t.First().name_design + "|").ToList();
            var id_sow = this.dsMSSQL.Projects.Where(t => string.IsNullOrEmpty(t.softwareid) == false).GroupBy(t => t.softwareid).Select(t => t.Key + "|" + t.First().name_software + "|").ToList();
            var id_asm = this.dsMSSQL.Projects.Where(t => string.IsNullOrEmpty(t.assemblyid) == false).GroupBy(t => t.assemblyid).Select(t => t.Key + "|" + t.First().name_assembly + "|").ToList();
            var id_epm = this.dsMSSQL.Projects.Where(t => string.IsNullOrEmpty(t.epanelid) == false).GroupBy(t => t.epanelid).Select(t => t.Key + "|" + t.First().name_epanel + "|").ToList();
            foreach (var item in id_cmp)
                if (item.isEmpty() == false && uids.Contains(item) == false) uids.Add(item);
            foreach (var item in id_des)
                if (item.isEmpty() == false && uids.Contains(item) == false) uids.Add(item);
            foreach (var item in id_sow)
                if (item.isEmpty() == false && uids.Contains(item) == false) uids.Add(item);
            foreach (var item in id_asm)
                if (item.isEmpty() == false && uids.Contains(item) == false) uids.Add(item);
            foreach (var item in id_epm)
                if (item.isEmpty() == false && uids.Contains(item) == false) uids.Add(item);

            //현그룹의 활성화된 사용자목록가져오기
            var dtActUser = DBM.getActiveUserTable();

            foreach (var uidinfo in uids.OrderBy(t => t))
            {
                var idinfo = uidinfo.Split('|');
                var uid = idinfo[0];

                if (dtActUser.Select($"id='{uid}'").Any() == false) continue;

                var newdr = this.dSProjectSummary.ProjectCountForUser.NewProjectCountForUserRow();

                newdr.UserID = uid;
                newdr.UserName = idinfo[1];
                newdr.Process = DBM.ExecuteScalar(string.Format("select top 1  isnull(process,'') from EETGW_GroupUser where gcode = '{0}' and uid='{1}'", FCOMMON.info.Login.gcode, newdr.UserID));

                //해당 유저의 데이터를 추출한다.
                var list = dsMSSQL.Projects.Where(t => t.championid == uid || t.softwareid == uid || t.designid == uid || t.epanelid == uid || t.assemblyid == uid).ToList();
                newdr.CntTotal = list.Count();
                newdr.CntProgress = list.Where(t => t.status == "진행").Count();
                newdr.CntComplete = list.Where(t => t.status.StartsWith("완료")).Count();
                newdr.CntCheck = list.Where(t => t.status == "검토").Count();
                newdr.CntHold = list.Where(t => t.status == "대기" || t.status == "보류").Count();

                //진행중인자료의 플랜을 확인한다.
                var listing = list.Where(t => t.status == "진행").ToList();

               if(uid == "395552")
                {

                }

                var yearstr = cmbYearS.Text;
                newdr.CntNone = listing.Where(t => string.IsNullOrEmpty(t.ddate)).Count();
                newdr.Plan01 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-01")).Count();
                newdr.Plan02 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-02")).Count();
                newdr.Plan03 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-03")).Count();
                newdr.Plan04 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-04")).Count();
                newdr.Plan05 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-05")).Count();
                newdr.Plan06 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-06")).Count();
                newdr.Plan07 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-07")).Count();
                newdr.Plan08 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-08")).Count();
                newdr.Plan09 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-09")).Count();
                newdr.Plan10 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-10")).Count();
                newdr.Plan11 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-11")).Count();
                newdr.Plan12 = listing.Where(t => t.ddate.StartsWith($"{yearstr}-12")).Count();

                var nextyear = (int.Parse(yearstr) + 1).ToString();
                newdr.PlanNext = listing.Where(t => t.ddate.StartsWith($"{nextyear}")).Count();
                newdr.CntOther = listing.Count - newdr.CntNone - newdr.PlanNext - newdr.Plan01 -
                     newdr.Plan02 - newdr.Plan03 - newdr.Plan04 - newdr.Plan05 - newdr.Plan06 -
                     newdr.Plan07 - newdr.Plan08 - newdr.Plan09 - newdr.Plan10 - newdr.Plan11 -
                     newdr.Plan12;


                this.dSProjectSummary.ProjectCountForUser.AddProjectCountForUserRow(newdr);
            }

            //합계를 추가하자
            var newdrs = this.dSProjectSummary.ProjectCountForUser.NewProjectCountForUserRow();
            newdrs.Process = "합계";
            newdrs.UserName = "";
            newdrs.UserID = "";
            newdrs.CntTotal = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntTotal);
            newdrs.CntProgress = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntProgress);
            newdrs.CntComplete = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntComplete);
            newdrs.CntCheck = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntCheck);
            newdrs.CntHold = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntHold);
            newdrs.CntNone = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntNone);
            newdrs.PlanNext = dSProjectSummary.ProjectCountForUser.Sum(t => t.PlanNext);
            newdrs.CntOther = dSProjectSummary.ProjectCountForUser.Sum(t => t.CntOther);
                 
            newdrs.Plan01 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan01);
            newdrs.Plan02 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan02);
            newdrs.Plan03 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan03);
            newdrs.Plan04 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan04);
            newdrs.Plan05 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan05);
            newdrs.Plan06 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan06);
            newdrs.Plan07 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan07);
            newdrs.Plan08 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan08);
            newdrs.Plan09 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan09);
            newdrs.Plan10 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan10);
            newdrs.Plan11 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan11);
            newdrs.Plan12 = dSProjectSummary.ProjectCountForUser.Sum(t => t.Plan12);
            this.dSProjectSummary.ProjectCountForUser.AddProjectCountForUserRow(newdrs);
        }

        void FormattingData()
        {

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

            //    if (majorstr == "True")
            //        this.fpSpread2.ActiveSheet.Rows[i].BackColor = Color.Lime;
            //    else
            //        this.fpSpread2.ActiveSheet.Rows[i].BackColor = Color.White;

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

            //}
            //FPUtil.ColSizeLoad(ref this.fpSpread2, fn_fpcolsize2);
            //this.fpSpread2.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_fpcolsize1);
                //    FPUtil.ColSizeLoad(ref this.fpSpread2, fn_fpcolsize2);
            }
            catch (System.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_fpcolsize1);
            //  FPUtil.ColsizeSave(this.fpSpread2, fn_fpcolsize2);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize1);
            // FPUtil.ColSizeLoad(ref this.fpSpread2, fn_fpcolsize2);
        }

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


        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)
            {
                try
                {
                    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);
                    }
                }
                catch (System.Exception ex)
                {
                    FCOMMON.Util.MsgE(ex.Message);
                }
            }
        }

        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;

        }

        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 (System.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 btCopy_Click(object sender, EventArgs e)
        {
            funcCopy();
        }

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

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

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



        }

        private void bsHistD_CurrentChanged(object sender, EventArgs e)
        {

        }

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

            }

        }

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

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void bsUser_CurrentChanged(object sender, EventArgs e)
        {
            var filter = "uid = '에라이'";
            var cur = this.bsUser.Current as DataRowView;
            if (cur == null)
            {
                bs.Filter = filter;
                return;
            }
            var dr = cur.Row as DSProjectSummary.ProjectCountForUserRow;
            if (dr == null)
            {
                bs.Filter = filter;
                return;
            }
            //var uid = dr.UserID;
            filter = "championid='{0}' or designid='{0}' or assemblyid='{0}' or epanelid='{0}' or softwareid='{0}'";
            filter = string.Format(filter, dr.UserID);
            bs.Filter = filter;

            FormattingData();
            //bs.Filter = "championid = 'sdf'";
            //var cnt = bs.Count;
        }

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

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

        private void fpSpread1_CellDoubleClick(object sender, FarPoint.Win.Spread.CellClickEventArgs e)
        {
            var filter = "uid = '에라이'";
            var cur = this.bsUser.Current as DataRowView;
            if (cur == null)
            {

                return;
            }
            var dr = cur.Row as DSProjectSummary.ProjectCountForUserRow;
            if (dr == null)
            {

                return;
            }
            //var uid = dr.UserID;
            filter = "championid='{0}' or designid='{0}' or assemblyid='{0}' or epanelid='{0}' or softwareid='{0}'";
            filter = string.Format(filter, dr.UserID);

            var f = new fProjectListUserDetail(dr.UserName, filter, dsMSSQL.Projects);
            f.ShowDialog();
        }
    }
}