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;
        Boolean bInit = false;

        public fProjectSchedule(int project_,bool enbEdit=true)
        {
            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;
            this.dsPRJ.EETGW_ProjectsSchedule.TableNewRow += ProjectsSchedule_TableNewRow;
            //this.dsPRJ.EETGW_ProjectReson.TableNewRow += EETGW_ProjectReson_TableNewRow;

            this.KeyDown += FProjectSchedule_KeyDown;
            button2.Enabled = enbEdit;
        }

        private void FProjectSchedule_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F11)
            {
                var cur = this.panel2.Visible;
                panel4.Visible = !cur;
                panel2.Visible = !cur;
            }
        }

        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.TableNewRow -= ProjectsSchedule_TableNewRow;
            this.dsPRJ.EETGW_ProjectsSchedule.RowChanged += EETGW_ProjectsSchedule_RowChanged;
        }
        private void EETGW_ProjectReson_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            if (e.Row["wuid"] == null) e.Row["wuid"] = FCOMMON.info.Login.no;
            if (e.Row["wdate"] == null) e.Row["wdate"] = DateTime.Now;
            if (e.Row["project"] == null) e.Row["project"] = this.projectindex;
            if (e.Row["gcode"] == null) e.Row["gcode"] = FCOMMON.info.Login.gcode;
        }

        void ProjectsSchedule_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["project"] = this.projectindex;
            e.Row["appoval"] = 0; //신규추가는 확정안되는 데이터이다
            e.Row["no"] = int.Parse(this.comboBox1.Text);
        }

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

            //var da2 = new System.Data.SqlClient.SqlDataAdapter();
            //da2.SelectCommand = new System.Data.SqlClient.SqlCommand("", ta.Connection);
            //da2.SelectCommand.CommandText = $"select * from Projects where gcode='{FCOMMON.info.Login.gcode}' and idx = {projectindex}";
            //da2.Fill(this.dsPRJ.Projects);
            //da2.Dispose();
            this.taProjectInfo.FillByIDX(this.dsPRJ.Projects, this.projectindex);

            //스케쥴 그룹(no)
            var db = new dsPRJTableAdapters.EETGW_ProjectsSchedule_NoListTableAdapter();// EEEntities();
            var nolist = db.GetData(FCOMMON.info.Login.gcode, this.projectindex);//.AsNoTracking().Where(t => t.gcode == FCOMMON.info.Login.gcode && t.project == this.projectindex).GroupBy(t => t.no).ToList();
            this.comboBox1.Items.Clear();
            if (nolist.Any())
            {
                foreach (var item in nolist)
                {
                    this.comboBox1.Items.Add(item.no.ToString());
                }
            }

            db.Dispose();

            if (this.comboBox1.Items.Count == 0)
            {
                util.MsgE("이 프로젝트에는 스케쥴이 등록되지 않았습니다\n" +
                    "스케쥴을 등록한 후 에는 관리자이 승인과정이 필요하며 승인이 완료되면 계획은 수정할 수 없습니다");
                this.comboBox1.Items.Add("1");
                this.comboBox1.SelectedIndex = 0;
            }

            // this.comboBox1.Items.Add("스케쥴 추가");


            RefreshData();
            RefreshGraph();
            this.dsPRJ.EETGW_ProjectsSchedule.RowChanged += EETGW_ProjectsSchedule_RowChanged;


            //시작할떄 cww 를 가져오낟.
            var sql = "select dbo.getWorkWeek('" + DateTime.Now.ToString("yyyy-MM-dd") + "')";
            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();
            bInit = true;


            if (this.comboBox1.Items.Count > 0)
            {
                this.comboBox1.SelectedIndex = this.comboBox1.Items.Count - 1;
            }

        }

        int CWW = 0;

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

        void RefreshGraph()
        {
            panel1.Invalidate();
        }
        void RefreshData()
        {
            //  var scno = int.Parse(comboBox1.Text);
            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.taReason.Fill(this.dsPRJ.EETGW_ProjectReson, FCOMMON.info.Login.gcode, 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);
            }
            Application.DoEvents();



        }
        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;
            newdr.no = int.Parse(comboBox1.Text);
            newdr.memo = string.Empty;
            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;  //해당데이터만 처리하게 한다

                if (int.TryParse(comboBox1.Text, out int pno))
                {
                    var filter_reason = $"no={pno} and pseq={ dr.idx}";
                    this.bsReason.Filter = filter_reason;
                }

            }
        }

        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;
            newdr.gcode = FCOMMON.info.Login.gcode;
            newdr.no = int.Parse(comboBox1.Text);
            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();
            this.bsReason.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 cnt3 = this.taReason.Update(this.dsPRJ.EETGW_ProjectReson);
                var cnt = cnt1 + cnt2 + cnt3;// this.tam.UpdateAll(this.dsPRJ);
                if (cnt == 0)
                {
                    FCOMMON.Util.MsgE("저장된 자료가 없습니다");
                }
                else
                {
                    FCOMMON.Util.MsgI($"{cnt}건의 자료가 저장 되었습니다");
                }
            }


        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            if (int.TryParse(comboBox1.Text, out int scno) == false) return;

            var list = this.dsPRJ.EETGW_ProjectsSchedule.Where(t => t.RowState != DataRowState.Deleted).Where(t => t.RowState != DataRowState.Detached).Where(t => t.no == scno).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 totalProgress = list.Sum(t => t.progress) / list.Count();

            var vsw_s = list.Max(t => t.sw);
            var vew_s = list.Max(t => t.ew);
            var vswa_s = list.Max(t => t.swa);
            var vewa_s = list.Max(t => t.ewa);

            var vsw = int.Parse(vsw_s.Replace("-", ""));//.Split('-')[1]);
            var vew = int.Parse(vew_s.Replace("-", ""));//.Split('-')[1]);
            var vswa = int.Parse(vswa_s.Replace("-", ""));//.Split('-')[1]);
            var vewa = int.Parse(vewa_s.Replace("-", ""));//.Split('-')[1]);

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


            var mvsw_s = list.Min(t => t.sw);
            var mvew_s = list.Min(t => t.ew);
            var mvswa_s = list.Min(t => t.swa);
            var mvewa_s = list.Min(t => t.ewa);



            var bufsw = mvsw_s.Split('-');
            var bufew = mvew_s.Split('-');
            var bufswa = mvswa_s.Split('-');
            var bufewa = mvewa_s.Split('-');
            if (bufsw.Length < 2)
            {
                if (bufsw[0].Length == 1) bufsw[0] = "0" + bufsw[0];
                mvsw_s = DateTime.Now.Year.ToString("00") + "-" + bufsw[0];
            }
            if (bufew.Length < 2)
            {
                if (bufew[0].Length == 1) bufew[0] = "0" + bufew[0];
                mvew_s = DateTime.Now.Year.ToString("00") + "-" + bufew[0];
            }
            if (bufswa.Length < 2)
            {
                if (bufswa[0].Length == 1) bufswa[0] = "0" + bufswa[0];
                mvswa_s = DateTime.Now.Year.ToString("00") + "-" + bufswa[0];
            }
            if (bufewa.Length < 2)
            {
                if (bufewa[0].Length == 1) bufewa[0] = "0" + bufewa[0];
                mvewa_s = DateTime.Now.Year.ToString("00") + "-" + bufewa[0];
            }



            var mvsw = int.Parse(mvsw_s.Replace("-", ""));//.Split('-')[1]);
            var mvew = int.Parse(mvew_s.Replace("-", ""));//.Split('-')[1]);


            var mvswa = int.Parse(mvswa_s.Replace("-", ""));//.Split('-')[1]);
            var mvewa = int.Parse(mvewa_s.Replace("-", ""));//.Split('-')[1]);


            var minw = 9999;
            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 == 9999) return; //값이 없다.

            var curyw = $"{DateTime.Now.Year.ToString("0000").Substring(2)}y{this.CWW:00}w";
            var curww = int.Parse($"{DateTime.Now.Year.ToString("0000").Substring(2)}{this.CWW:00}");
            var ProjecComplete = totalProgress > 99;
            if (ProjecComplete == false)
            {
                maxw = Math.Max(curww, maxw);
            }
            var wwcnt = maxw - minw + 1;
            for (int i = 1; i <= wwcnt; i++)
            {
                var yy = (int)((minw + (i - 1)) / 100);
                var ww = (minw + (i - 1) - yy * 100);
                if (ww > 52 || ww < 1) continue;
                cols.Add($"{yy}y{ww:00}w");//  "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);
                if (col == curyw)
                {
                    e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rect);
                    e.Graphics.DrawString(col, this.Font, Brushes.Black, rect, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
                }
                else
                {
                    e.Graphics.FillRectangle(Brushes.DimGray, rect);
                    e.Graphics.DrawString(col, this.Font, Brushes.White, rect, new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
                }
                e.Graphics.DrawRectangle(Pens.Black, rect.Left, rect.Top, rect.Width, rect.Height);

                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(new SolidBrush(Color.FromArgb(25, 25, 25)), rect.Left, rect.Top, rect.Width, rect.Height);
                else
                    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(35, 35, 35)), rect.Left, rect.Top, rect.Width, rect.Height);

                Color PBg = Color.SkyBlue;
                Color ABg = Color.Gold;
                var sw_s = dr.sw;
                var ew_s = dr.ew;
                var swa_s = dr.swa;
                var ewa_s = dr.ewa;

                int sw, ew, swa, ewa;
                sw = ew = swa = ewa = 0;

                try
                {
                    sw = int.Parse(dr.sw.Replace("-", ""));//.Split('-')[1]); ;// ;// ; ;
                }
                catch { sw = 0; }

                try
                {
                    ew = int.Parse(dr.ew.Replace("-", ""));//.Split('-')[1]);//.Split('-')[1]);
                }
                catch { ew = 0; }
                try
                {
                    swa = int.Parse(dr.swa.Replace("-", ""));//.Split('-')[1]);//.Split('-')[1]);
                }
                catch { }

                try
                {
                    ewa = int.Parse(dr.ewa.Replace("-", ""));//.Split('-')[1]);
                }
                catch { }




                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 = int.Parse(DateTime.Now.Year.ToString().Substring(2) + this.CWW.ToString("00")); // swa;
                if (isBusy && ABg != Color.Transparent) ABg = Color.Pink;


                ci = 0;
                foreach (var col in cols)
                {
                    var ww = ci == 0 ? 0 : int.Parse(col.Substring(0, 2) + col.Substring(3, 2));// 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 = 1f;
                    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)
                    {
                        //각 담당자 이름과 항목 이름을 표시한다
                        if (isBusy == false)
                        {
                            e.Graphics.DrawString(str + "\n" + dr.uid,
                            this.Font,
                            (isBusy ? Brushes.WhiteSmoke : Brushes.Lime),
                            rect2,
                            new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center }
                            );
                        }
                        else
                        {
                            if (dr.progress < 1)
                            {
                                e.Graphics.DrawString(str + "\n" + dr.uid + $"\n\n[시작 안함]",
                            this.Font,
                            (isBusy ? (dr.progress < 1 ? Brushes.Yellow : Brushes.WhiteSmoke) : Brushes.Lime),
                            rect2,
                            new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center }
                            );
                            }
                            else
                            {
                                e.Graphics.DrawString(str + "\n" + dr.uid + $"\n\n[{dr.progress:N1}% 진행 중]",
                            this.Font,
                            (isBusy ? (dr.progress < 1 ? Brushes.Yellow : Brushes.WhiteSmoke) : Brushes.Lime),
                            rect2,
                            new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center }
                            );
                            }

                        }

                    }
                    else
                    {
                        if (col == "22y02w" && ew == 2202)
                            Console.WriteLine("sdf");

                        //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 dsJobReportTableAdapters.CommonTableAdapter();// EEEntities();
            var list = db.GetData(FCOMMON.info.Login.gcode, "21");//.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);
        }

        private void chkapp1_Click(object sender, EventArgs e)
        {
            //권한이 있어야한다.
            var db = new dsPRJTableAdapters.AuthTableAdapter();// EEEntities();
            var dr = db.GetByUser(FCOMMON.info.Login.gcode, FCOMMON.info.Login.no).FirstOrDefault();//.Auth.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.user == FCOMMON.info.Login.no).FirstOrDefault();
            if (dr == null || dr.IsscheappNull() || dr.scheapp < 1)
            {
                util.MsgE("'승인권한1'이 없습니다");
                return;
            }
            if (chkapp1.Checked)
            {
                util.MsgE("'승인해제1'는 현재 구현 중");
            }
            else
            {
                chkapp1.Checked = true;
                foreach (var item in this.dsPRJ.EETGW_ProjectsSchedule)
                {
                    if (item.RowState == DataRowState.Deleted || item.RowState == DataRowState.Deleted) continue;
                    item.appoval = 1;
                }
            }
        }

        private void chkapp2_Click(object sender, EventArgs e)
        {
            //권한이 있어야한다.
            var db = new dsPRJTableAdapters.AuthTableAdapter();// EEEntities();
            var dr = db.GetByUser(FCOMMON.info.Login.gcode, FCOMMON.info.Login.no).FirstOrDefault();//.Auth.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.user == FCOMMON.info.Login.no).FirstOrDefault();
            if (dr == null || dr.IsscheappNull() || dr.scheapp < 2)
            {
                util.MsgE("'승인권한2'이 없습니다");
                return;
            }
            if (chkapp2.Checked)
            {
                util.MsgE("승인해제2'는 현재 구현 중");
            }
            else
            {
                chkapp2.Checked = true;
                foreach (var item in this.dsPRJ.EETGW_ProjectsSchedule)
                {
                    if (item.RowState == DataRowState.Deleted || item.RowState == DataRowState.Deleted) continue;
                    item.appoval = 2;
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bInit == false) return;

            //해당 데이터만 표시한다.
            this.bs.Filter = "no = " + this.comboBox1.Text;
            this.bs.Sort = "seq";
            this.bsReason.Filter = "no = " + this.comboBox1.Text;


            //해당스케쥴의 승인상태를 확인
            var scno = int.Parse(comboBox1.Text);
            var db = new dsPRJTableAdapters.EETGW_ProjectsScheduleTableAdapter();// EEEntities();
            var dr = db.GetByNo(FCOMMON.info.Login.gcode, this.projectindex, scno).FirstOrDefault();
            //.Where(t => t.project == this.projectindex && t.no == scno).FirstOrDefault();

            if (dr == null || dr.appoval == 0)
            {
                chkapp1.Checked = false;
                chkapp2.Checked = false;


            }
            else if (dr.appoval == 1)
            {
                chkapp1.Checked = true;
                chkapp2.Checked = false;

                this.fpSpread1.Sheets[0].Columns[2].Locked = true;
                this.fpSpread1.Sheets[0].Columns[3].Locked = true;
                this.fpSpread1.Sheets[0].Columns[2].BackColor = Color.FromArgb(230, 230, 230);
                this.fpSpread1.Sheets[0].Columns[3].BackColor = Color.FromArgb(230, 230, 230);

            }
            else
            {
                chkapp1.Checked = true;
                chkapp2.Checked = true;

                this.fpSpread1.Sheets[0].Columns[2].Locked = true;
                this.fpSpread1.Sheets[0].Columns[3].Locked = true;
                this.fpSpread1.Sheets[0].Columns[2].BackColor = Color.FromArgb(230, 230, 230);
                this.fpSpread1.Sheets[0].Columns[3].BackColor = Color.FromArgb(230, 230, 230);
            }
            this.panel1.Refresh();
        }

        private void toolStripButton15_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_ProjectReson.NewEETGW_ProjectResonRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pidx = this.projectindex;
            newdr.pdate = DateTime.Now.ToString("yyyy-MM-dd");
            newdr.pseq = dr.idx;
            newdr.gcode = FCOMMON.info.Login.gcode;
            newdr.no = int.Parse(comboBox1.Text);
            this.dsPRJ.EETGW_ProjectReson.AddEETGW_ProjectResonRow(newdr);

            bsReason.EndEdit();
            this.dataGridView1.Focus();

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

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

        private void toolStripButton16_Click(object sender, EventArgs e)
        {
            bsReason.RemoveCurrent();
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void toolStripButton19_Click(object sender, EventArgs e)
        {

            

            int maxno = 0;
            var maxdata = dsPRJ.EETGW_ProjectsSchedule.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.project == this.projectindex);
            if (maxdata.Any() == true) maxno = maxdata.Max(t => t.no);

            var currentno = int.Parse(comboBox1.Text);
            var newno = maxno + 1;

            var dlg = util.MsgQ($"스케쥴을 추가 하시겠습니까? 스케쥴 추가는 각 관리자에 협의 후 하시기 바랍니다\n소스:{currentno},신규번호:{newno}");
            if (dlg != DialogResult.Yes) return;

            this.comboBox1.Items.Add($"{newno}");

            //기존목록을 복사함
            var seq = 1;
            foreach (dsPRJ.EETGW_ProjectsScheduleRow dr in this.dsPRJ.EETGW_ProjectsSchedule.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.project == this.projectindex && t.no == currentno).OrderBy(t => t.seq))
            {
                var newdr = this.dsPRJ.EETGW_ProjectsSchedule.NewEETGW_ProjectsScheduleRow();
                newdr.no = newno;
                newdr.seq = seq++;
                newdr.wuid = FCOMMON.info.Login.no;
                newdr.wdate = DateTime.Now;
                newdr.gcode = dr.gcode;
                newdr.project = dr.project;
                newdr.title = dr.title;
                newdr.sw = dr.sw;
                newdr.ew = dr.ew;
                newdr.swa = dr.swa;
                newdr.ewa = dr.ewa;
                newdr.memo = dr.memo;
                newdr.progress = dr.progress;
                newdr.uidname = dr.uidname;
                newdr.uid = dr.uid;
                newdr.appoval = 0;
                newdr.cate = dr.cate;
                if (newdr.IsmemoNull()) newdr.memo = string.Empty;
                dsPRJ.EETGW_ProjectsSchedule.AddEETGW_ProjectsScheduleRow(newdr);
                newdr.EndEdit();
            }

            this.comboBox1.SelectedIndex = this.comboBox1.Items.Count - 1;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            var drv = this.bsPrjinfo.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)
            {
                this.Validate();
                this.bsPrjinfo.EndEdit();
                try
                {
                    var ta = new dsPRJTableAdapters.ProjectsTableAdapter();
var cnt =                    ta.Update(this.dsPRJ.Projects);//.UpdateAll(this.dsMSSQL.Projects);
                    dsPRJ.Projects.AcceptChanges();
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE(ex.Message);
                }
            }
        }
    }
}
