using FarPoint.CalcEngine;
using FCM0000;
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 fProjectListUserDetail : FCOMMON.fBase
    {
        string fn_fpcolsize1 = "";
        public fProjectListUserDetail(string name,string filter,dsPRJ.ProjectsDataTable dt)
        {
            InitializeComponent();
            fn_fpcolsize1 = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + "_1.ini");
            //this.dsMSSQL.Projects.TableNewRow += Projects_TableNewRow;
            this.FormClosed += __Closed;
            this.dsMSSQL.Projects.Merge(dt);
            this.dsMSSQL.Projects.AcceptChanges();
            this.Text = $"({name}) 업무현황";
            this.bs.Filter = filter;
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
        }

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

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

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


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

        void FormattingData()
        {

            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var statindex = this.fpSpread1.ActiveSheet.Columns["Status"].Index;
            var majorindex = this.fpSpread1.ActiveSheet.Columns["Highlight"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var major = this.fpSpread1.ActiveSheet.GetValue(i, majorindex);
                var state = this.fpSpread1.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.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.Lime;
                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_fpcolsize1);
            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_fpcolsize1);
            }
            catch (System.Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

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

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

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

        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 (System.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;

        }

      
        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 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 timer1_Tick(object sender, EventArgs e)
        {
            if (Alert_DDate)
            {
           
            }
           
        }

     

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

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