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 static FPJ0000.Project.ctlLayout;
using util = FCOMMON.Util;

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

        }

        int project = -1;
        int no = 0;
        private void CtlLayout1_itemclick(itemdata item, MouseEventArgs e)
        {
            project = item.project;
            no = item.no;

            if (project < 1) return;

            Console.WriteLine("project:" + project.ToString());
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {
            this.ctlLayout1.itemclick -= CtlLayout1_itemclick;
        }

        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.Show();
            Application.DoEvents();
            refreshData();


        }

        void refreshData()
        {
            if (ctlLayout1.items == null || ctlLayout1.items.Count != 10)
            {
                if (ctlLayout1.items != null) ctlLayout1.items.Clear();
                for (int i = 1; i <= 12; i++)
                {
                    ctlLayout1.items.Add(new itemdata()
                    {
                        no = i,
                        body = "",
                        champion = "",
                        duedate = "미사용"
                    });

                }

            }
            foreach (var item in ctlLayout1.items)
            {
                item.body = string.Empty;
                item.duedate = "미사용";
                item.champion = "--";
                item.bodyColor = ctlLayout1.BackColor;
            }
            ctlLayout1.Refresh();

            var ta = new dsPRJTableAdapters.vEETGW_Project_LayoutListTableAdapter();
            var dtlay = ta.GetData(FCOMMON.info.Login.gcode);


            var list = dtlay.OrderBy(t => t.no).ToList();
            if (list.Any())
            {
                //this.cmsview1.GridCount = new Point(maxcol + 1, maxrow + 1);
                foreach (var dr in list)
                {
                    var data = ctlLayout1.items[dr.no - 1];
                    //var drprj = db.vEETGW_Project_LayoutList.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.idx == dr.project).FirstOrDefault();
                    if (dr.IsprojectNull() || dr.project < 1)
                    {
                        data.bodyColor = Color.DarkMagenta;
                        data.body = string.Empty;
                        data.champion = string.Empty;
                        data.duedate = "미 할당";
                        data.project = -1;
                        data.reserve = dr.reserve; // string.Empty; 예약자는 그대로 한다.
                    }
                    else
                    {
                        data.reserve = dr.reserve;
                        data.project = dr.project;
                        data.body = "[" + dr.status + "] " + dr.name;
                        data.champion = dr.champion;
                        data.duedate = dr.ddate;
                        var isdate = DateTime.TryParse(dr.ddate, out DateTime dt);
                        if (isdate)
                        {
                            if (DateTime.Now >= dt) data.bodyColor = Color.Tomato;
                            else data.bodyColor = ctlLayout1.BackColor;
                        }
                        else
                        {
                            data.bodyColor = ctlLayout1.BackColor;
                        }

                    }

                }
            }
            ctlLayout1.Refresh();
        }



        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.tam.UpdateAll(this.dsMSSQL);
                dsMSSQL.AcceptChanges();
            }
            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)
        {

        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btSearch_Click(object sender, EventArgs e)
        {

        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            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 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)
        {
            if (this.project < 1) return;

            var dt = ta.GetbyIDX(this.project);
            if (dt == null || dt.Rows.Count < 1)
            {
                util.MsgE("프로젝트가 존재하지 않습니다");
                return;
            }
            var dr = dt.Rows[0] as dsPRJ.ProjectsRow;
            var f = new fProjectData(dr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (util.MsgQ("저장 할까요?") == DialogResult.Yes)
                {
                    dr.EndEdit();
                    ta.Update(dr);
                    refreshData();
                }
            }
        }

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

        }

        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.progress = 0;
            newdr.userprocess = FCOMMON.info.Login.process;
            newdr.costn = 0;
            newdr.costo = 0;
            newdr.cnt = 1;
            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;

        }

        private void 편집ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var currentime = this.ctlLayout1.items[this.no - 1];
            if (currentime.project == -1 && String.IsNullOrEmpty(currentime.reserve) == false)
            {
                //프로젝트가 할당된 상태가 아니다.
                if (currentime.reserve != FCOMMON.info.Login.nameK)
                {
                    FCOMMON.Util.MsgE($"다음 예약자 {currentime.reserve} 가 아닙니다.\r\n해당 예약자가 취소해야 등록 가능 합니다");
                    return;
                }
            }
            var keyword = "진행";
            var f = new FCM0000.fLovProject(string.Empty, keyword,true);
            if (f.ShowDialog() == DialogResult.OK)
            {
                //yfmf 
                var ta = new dsPRJTableAdapters.EETGW_Project_LayoutTableAdapter();
                var dt = ta.GetData(FCOMMON.info.Login.gcode);
                var dr = dt.Where(t => t.no == this.no && t.project == this.project).FirstOrDefault();
                if (dr == null)
                {
                    //없으면 추가 해야하마
                    var newdr = dt.NewEETGW_Project_LayoutRow();
                    newdr.gcode = FCOMMON.info.Login.gcode;
                    newdr.no = this.no;
                    newdr.project = f.val_Index;
                    newdr.remark = string.Empty;
                    newdr.reserve = string.Empty;
                    newdr.row = 1;
                    newdr.col = 1;
                    newdr.rowspan = 1;
                    newdr.colspan = 1;
                    newdr.wdate = DateTime.Now;
                    newdr.wuid = FCOMMON.info.Login.no;
                    dt.AddEETGW_Project_LayoutRow(newdr);
                    ta.Update(dt);
                }
                else
                {
                    dr.project = f.val_Index;
                    dr.EndEdit();
                    ta.Update(dr);
                    util.MsgI("프로젝트를 변경했습니다");
                }
                refreshData();
            }
        }

        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 == "[namme]") this.bs.Sort = "[namme] desc";
            //        else this.bs.Sort = "[namme]";
            //        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;
            //    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 예약변경ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.no < 1) return;

            var f = new Project.fLayoutEdit(this.no);
            if (f.ShowDialog() == DialogResult.OK)
                refreshData();
        }

        private void 프로젝트해제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.project < 1)
            {
                FCOMMON.Util.MsgE("선택된 프로젝트가 없습니다");
                return;
            }
            var dlg = FCOMMON.Util.MsgQ("슬롯 " + this.no.ToString() + "의 프로젝트를 해제 할까요?\n" +
                "해당 슬롯은 '미사용'이 됩니다");
            if (dlg == DialogResult.Yes)
            {
                //자료를 삭제한다.
                var ta = new dsPRJTableAdapters.EETGW_Project_LayoutTableAdapter();
                ta.DeleteNo(FCOMMON.info.Login.gcode, this.no);
                refreshData();
            }
        }
    }
}