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 fProjectSchedule : FCOMMON.fBase
    {
        string fn_fpcolsize1 = "";
        string fn_fpcolsize2 = "";
        int projectindex = 0;
        EEEntities db;
        List<EETGW_ProjectsSchedule> list;
        Boolean bini = false;
        public fProjectSchedule(int project_)
        {
            InitializeComponent();
            projectindex = project_;
            db = new EEEntities();//this.dsPRJ.ProjectsSchedule.TableNewRow += ProjectsSchedule_TableNewRow;
            fn_fpcolsize1 = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            fn_fpcolsize2 = util.MakeFilePath(util.CurrentPath, "formSetting", "fp2_" + this.Name + ".ini");
            this.FormClosed += FProjectSchedule_FormClosed;
            this.FormClosing += FProjectSchedule_FormClosing;
        }

        private void FProjectSchedule_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.bsTodo.EndEdit();
            
            if (dsPRJ.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경된 자료가 있습니다. 지금 화면을 닫으면 해당 자료는 손실됩니다\n화면을 닫을까요?");
                if (dlg != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void FProjectSchedule_FormClosed(object sender, FormClosedEventArgs e)
        {

            this.dsPRJ.EETGW_ProjectsSchedule.RowChanged += EETGW_ProjectsSchedule_RowChanged;
        }

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

        private void fProjectSchedule_Load(object sender, EventArgs e)
        {
            RefreshData();
            RefreshGraph();
            this.dsPRJ.EETGW_ProjectsSchedule.RowChanged += EETGW_ProjectsSchedule_RowChanged;
            bini = true;

            //시작할떄 cww 를 가져오낟.
            var sql = "select dbo.getWorkWeek('" + DateTime.Now.ToShortDateString() + "')";
            var cmd = new System.Data.SqlClient.SqlCommand(sql, this.ta.Connection);
            cmd.Connection.Open();
            var wccstr = cmd.ExecuteScalar();
            CWW = int.Parse(wccstr.ToString());
            cmd.Connection.Close();
            cmd.Dispose();

        }

        int CWW = 0;

        private void EETGW_ProjectsSchedule_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (bini == false) return;
            RefreshGraph();
        }

        void RefreshGraph()
        {
            panel1.Invalidate();
        }
        void RefreshData()
        {
            try
            {
                //list = db.EETGW_ProjectsSchedule.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.project == this.projectindex).OrderBy(t => t.seq).ToList();
                this.ta.Fill(this.dsPRJ.EETGW_ProjectsSchedule, FCOMMON.info.Login.gcode, this.projectindex);
                this.taTodo.Fill(this.dsPRJ.EETGW_ProjectToDo, this.projectindex);
                //this.bs.DataSource = list;//.ToList();// db.EETGW_ProjectsSchedule.Local;
                //this.fpSpread1_Sheet1.DataSource = this.bs;
                FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize1);
                FPUtil.ColSizeLoad(ref this.fpSpread2, fn_fpcolsize2);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
        private void projectsScheduleBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.ta.Update(this.dsPRJ.EETGW_ProjectsSchedule);
            dsPRJ.EETGW_ProjectsSchedule.AcceptChanges();
            RefreshGraph();
        }

        private void fillToolStripButton_Click(object sender, EventArgs e)
        {


        }

        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.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 exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fpSpread1.SaveExcel("schedule.xls",
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            //새로운 데이터 추가
            var newdr = this.dsPRJ.EETGW_ProjectsSchedule.NewEETGW_ProjectsScheduleRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.project = this.projectindex;
            newdr.seq = this.bs.Count + 1;
            newdr.gcode = FCOMMON.info.Login.gcode;
            dsPRJ.EETGW_ProjectsSchedule.AddEETGW_ProjectsScheduleRow(newdr);

            this.bs.EndEdit();
            this.fpSpread1.Focus();
            if (this.bs.Count > 0)
                this.bs.Position = this.bs.Count - 1;
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            this.bs.RemoveCurrent();
        }

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

        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.EETGW_ProjectsScheduleRow;
            if (dr.idx == -1)
            {
                this.fpSpread2.Enabled = false;
                bnTodo.Enabled = false;
            }
            else
            {
                this.fpSpread2.Enabled = true;
                bnTodo.Enabled = true;
                this.bsTodo.Filter = "pseq=" + dr.idx;  //해당데이터만 처리하게 한다
            }
        }

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


            //토도추가
            var newdr = this.dsPRJ.EETGW_ProjectToDo.NewEETGW_ProjectToDoRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pidx = this.projectindex;
            newdr.pseq = dr.idx;
            this.dsPRJ.EETGW_ProjectToDo.AddEETGW_ProjectToDoRow(newdr);

            bsTodo.EndEdit();
            this.fpSpread2.Focus();

            if (this.bsTodo.Count > 0)
                this.bsTodo.Position = this.bsTodo.Count - 1;
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            //todo만 다ㅣㅅ 불렁노다
            taTodo.Fill(this.dsPRJ.EETGW_ProjectToDo, this.projectindex);
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            bsTodo.RemoveCurrent();
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsTodo.EndEdit();
            var cnt = taTodo.Update(this.dsPRJ.EETGW_ProjectToDo);
            FCOMMON.Util.MsgI($"{cnt}건의 자료가 업데이트 되었습니다");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.bsTodo.EndEdit();
            if (this.dsPRJ.HasChanges() == false)
            {
                FCOMMON.Util.MsgE("변경된 내용이 없습니다");
                return;
            }
            else
            {
                var cnt1 = this.ta.Update(this.dsPRJ.EETGW_ProjectsSchedule);
                var cnt2 = this.taTodo.Update(this.dsPRJ.EETGW_ProjectToDo);
                var cnt = cnt1 + cnt2;// this.tam.UpdateAll(this.dsPRJ);
                if (cnt == 0)
                {
                    FCOMMON.Util.MsgE("저장된 자료가 없습니다");
                }
                else
                {
                    FCOMMON.Util.MsgI($"{cnt}건의 자료가 저장 되었습니다");
                }
            }


        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            var list = this.dsPRJ.EETGW_ProjectsSchedule.Where(t => t.RowState != DataRowState.Deleted).Where(t => t.RowState != DataRowState.Detached).OrderBy(t => t.seq).ToList();
            e.Graphics.Clear(Color.DimGray);
            //e.Graphics.DrawString(list.Count.ToString(), this.Font, Brushes.White, 10, 10);
            var colsize = new int[] { 50 };
            var cols = new List<string>();
            cols.Add("Item");

            if (list == null || list.Count < 1) return;

            var vsw = list.Max(t => t.sw);
            var vew = list.Max(t => t.ew);
            var vswa = list.Max(t => t.swa);
            var vewa = list.Max(t => t.ewa);

            var maxw = Math.Max(vsw, vew);
            maxw = Math.Max(maxw, vswa);
            maxw = Math.Max(maxw, vewa);
            if (maxw == 0) return; //값이 없다.


            var mvsw = list.Min(t => t.sw);
            var mvew = list.Min(t => t.ew);
            var mvswa = list.Min(t => t.swa);
            var mvewa = list.Min(t => t.ewa);

            var minw = 999;
            if (mvsw > 0) minw = Math.Min(minw, mvsw);
            if (mvew > 0) minw = Math.Min(minw, mvew);
            if (mvswa > 0) minw = Math.Min(minw, mvswa);
            if (mvewa > 0) minw = Math.Min(minw, mvewa);
            if (minw == 999) return; //값이 없다.


            var wwcnt = maxw - minw + 1;
            for (int i = 1; i <= wwcnt; i++)
            {
                cols.Add("ww" + (minw + i - 1).ToString());//
            }


            var rect_title = new Rectangle(3, 3, panel1.Width - 6, 30);
            var rect_body = new Rectangle(rect_title.Left, rect_title.Bottom + 1, rect_title.Width, panel1.Height - rect_title.Height - 5);
            var lineheight = (rect_body.Height - list.Count * 2) / list.Count;
            var linewidth = rect_body.Width;// - 6;

            //제목줄표시
            var ci = 0;
            var titlewi = 200f;
            var twidth = (rect_title.Width - titlewi) / (cols.Count - 1);
            foreach (var col in cols)
            {
                var titleWidth = ci == 0 ? titlewi : twidth;
                var padX = ci > 0 ? ((ci - 1) * twidth + titlewi) : 0;
                var rect = new RectangleF(rect_title.Left + padX, rect_title.Top, titleWidth, rect_title.Height);
                e.Graphics.DrawRectangle(Pens.Black, rect.Left, rect.Top, rect.Width, rect.Height);
                e.Graphics.DrawString(col, this.Font, Brushes.Gold, rect, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
                ci += 1;
            }

            for (int i = 0; i < list.Count; i++)
            {
                var dr = list[i];
                var rect = new RectangleF(rect_body.Left, rect_body.Top + i * lineheight + ((i + 1) * 2), linewidth, lineheight);

                if (i % 2 == 0)
                    e.Graphics.FillRectangle(Brushes.Gray, rect.Left, rect.Top, rect.Width, rect.Height);
                else
                    e.Graphics.FillRectangle(Brushes.DimGray, rect.Left, rect.Top, rect.Width, rect.Height);

                Color PBg = Color.SkyBlue;
                Color ABg = Color.Gold;
                var sw = dr.sw;
                var ew = dr.ew;
                var swa = dr.swa;
                var ewa = dr.ewa;
                if (sw == 0) { sw = minw; PBg = Color.Transparent; }
                if (ew == 0) ew = sw;

                var isEmpty = swa == 0;
                if (swa == 0) { swa = minw; ABg = Color.Transparent; };
                var isBusy = ewa == 0; //아직 완료되지 않았다
                if (ewa == 0) ewa = swa;
                if (isBusy && ABg != Color.Transparent) ABg = Color.Pink;


                ci = 0;
                foreach (var col in cols)
                {
                    var ww = minw + (ci - 1);
                    var titleWidth = ci == 0 ? titlewi : twidth;
                    var padX = ci > 0 ? ((ci - 1) * twidth + titlewi) : 0;

                    var rect2 = new RectangleF(rect.Left + padX, rect.Top, titleWidth, rect.Height);
                    var rect2T = new RectangleF(rect.Left + padX, rect.Top, titleWidth, rect.Height / 2f);
                    var rect2L = new RectangleF(rect2T.Left, rect2T.Bottom, rect2T.Width, rect2T.Height);


                    var spacing = 3f;
                    var rect2TP = new RectangleF(rect2T.Left + spacing, rect2T.Top + spacing, rect2T.Width - spacing * 2, rect2T.Height - spacing * 2);
                    var rect2BP = new RectangleF(rect2L.Left + spacing, rect2L.Top + spacing, rect2L.Width - spacing * 2, rect2L.Height - spacing * 2);

                    var str = ci == 0 ? dr.title : ww.ToString();
                    if (ci == 0)
                    {
                        //e.Graphics.DrawRectangle(Pens.Black, rect2.Left, rect2.Top, rect2.Width, rect2.Height);
                        e.Graphics.DrawString(str + "\n" + dr.uid,
                            this.Font,
                            Brushes.Gold,
                            rect2,
                            new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center }
                            );
                    }
                    else
                    {
                        //plan
                        if (ww >= sw && ww <= ew)
                            e.Graphics.FillRectangle(new SolidBrush(PBg), rect2TP.Left, rect2TP.Top, rect2TP.Width, rect2TP.Height);

                        using (Pen p = new Pen(Color.FromArgb(50, 50, 50)))
                        {
                            e.Graphics.DrawRectangle(p, rect2TP.Left, rect2TP.Top, rect2TP.Width, rect2TP.Height);
                        }



                        //actual
                        if (ww >= swa && ww <= ewa)
                            e.Graphics.FillRectangle(new SolidBrush(ABg), rect2BP.Left, rect2BP.Top, rect2BP.Width, rect2BP.Height);
                        else if (isEmpty == false && isBusy && ww >= swa && ww <= this.CWW  )
                        {
                            e.Graphics.FillRectangle(new SolidBrush(Color.Pink), rect2BP.Left, rect2BP.Top, rect2BP.Width, rect2BP.Height);
                        }


                        e.Graphics.DrawRectangle(Pens.Black, rect2BP.Left, rect2BP.Top, rect2BP.Width, rect2BP.Height);

                        //title
                        if (ci == 1)
                        {
                            using (Font f = new Font("맑은 고딕", 7, FontStyle.Bold))
                            {
                                var fsizeT = e.Graphics.MeasureString("PLAN", f);
                                var fsizeB = e.Graphics.MeasureString("ACTUAL", f);
                                e.Graphics.DrawString("PLAN", f, Brushes.White, rect2TP.Left - fsizeT.Width * 1.1f, rect2TP.Top + (rect2TP.Height - fsizeT.Height) / 2f);
                                e.Graphics.DrawString("ACTUAL", f, Brushes.White, rect2BP.Left - fsizeB.Width * 1.1f, rect2BP.Top + (rect2BP.Height - fsizeB.Height) / 2f);
                            }

                        }

                    }
                    ci += 1;
                }
            }


        }

        private void panel1_MouseClick(object sender, MouseEventArgs e)
        {
            RefreshGraph();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            //if (this.dsPRJ.EETGW_ProjectsSchedule.Rows.Count > 0)
            //{
            //    var dlg = FCOMMON.Util.MsgQ("기존 목록을 삭제할까요?");
            //    if (dlg == DialogResult.Yes)
            //    {
            //        for (int i = this.dsPRJ.EETGW_ProjectsSchedule.Count; i > 0; i--)
            //        {
            //            dsPRJ.EETGW_ProjectsSchedule.Rows[i - 1].Delete();
            //        }
            //    }
            //}


            var db = new EEEntities();
            var list = db.Common.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.grp == "21")
                .OrderBy(t => t.code)
                .ToList();


            foreach (var item in list)
            {
                var newdr = this.dsPRJ.EETGW_ProjectsSchedule.NewEETGW_ProjectsScheduleRow();
                newdr.wuid = FCOMMON.info.Login.no;
                newdr.wdate = DateTime.Now;
                newdr.seq += dsPRJ.EETGW_ProjectsSchedule.Rows.Count + 1;
                newdr.title = item.memo;
                newdr.project = this.projectindex;
                newdr.gcode = FCOMMON.info.Login.gcode;
                dsPRJ.EETGW_ProjectsSchedule.AddEETGW_ProjectsScheduleRow(newdr);
            }
        }

        private void fProjectSchedule_SizeChanged(object sender, EventArgs e)
        {
            this.panel1.Invalidate();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            fpSpread2.SaveExcel("scheduleTodo.xls",
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            this.fpSpread2.ActiveSheet.DataAutoSizeColumns = true;

            for (int i = 0; i < this.fpSpread2.ActiveSheet.Rows.Count; i++)
                this.fpSpread2.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread2.ActiveSheet.Columns)
            {
                col.Width = 100;
            }
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            //save
            FPUtil.ColsizeSave(this.fpSpread2, fn_fpcolsize2);
        }

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