using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace FPJ0000
{
    public partial class fEboardData : FCOMMON.fBase
    {
        dsPRJ.EETGW_JobReport_EBoardRow dr = null;
        public fEboardData(dsPRJ.EETGW_JobReport_EBoardRow dr_)
        {
            InitializeComponent();
            this.UseFormSetting = false;
            this.dr = dr_;
            this.dsPRJ.ProjectsHistory.TableNewRow += ProjectsHistory_TableNewRow;
        }

        void ProjectsHistory_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {

        }

        delegate void SetComboboxItemsHandler(ComboBox ctl, string[] list);
        void SetComboboxItems(ComboBox ctl, string[] list)
        {
            //콤보박스의 아이템을 업데이트합니다.
            if (ctl.InvokeRequired)
            {
                this.BeginInvoke(new SetComboboxItemsHandler(SetComboboxItems), new object[] { ctl, list });
                return;
            }

            ctl.Items.Clear();
            ctl.Items.AddRange(list);
            ctl.Enabled = true;
            
        }

        private void fProjectData_Load(object sender, EventArgs e)
        {
            var db = new EEEntities();

            //자동완성목록 업데이트
            Task.Run(new Action(() =>
            {

                //UID목록
                var lst_uid = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.uid) == false).OrderBy(t => t.uid).GroupBy(t => t.uid).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbUID,lst_uid.Select(t => t.uid).ToArray());

                //요청자
                var lst_req = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.요청자) == false).OrderBy(t => t.요청자).GroupBy(t => t.요청자).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmb요청자,lst_req.Select(t => t.요청자).ToArray());

                //모델
                var lst_mod = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Model) == false).OrderBy(t => t.Model).GroupBy(t => t.Model).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbModel,lst_mod.Select(t => t.Model).ToArray());

                //BoardName
                var lst_bon = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.BoardName) == false).OrderBy(t => t.BoardName).GroupBy(t => t.BoardName).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbBoardName,lst_bon.Select(t => t.BoardName).ToArray());

                //BoardVender
                var lst_bvn = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.BoardVender) == false).OrderBy(t => t.BoardVender).GroupBy(t => t.BoardVender).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbBoardVender, lst_bvn.Select(t => t.BoardVender).ToArray());

                //SN
                var lst_srn = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.SN) == false).OrderBy(t => t.SN).GroupBy(t => t.SN).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbSN,lst_srn.Select(t => t.SN).ToArray());

                ////status
                //var lst_sta = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Status) == false).OrderBy(t => t.Status).GroupBy(t => t.Status).Select(t => t.FirstOrDefault());
                //SetComboboxItems(cmbStatus,lst_sta.Select(t => t.Status).ToArray());

                //분류
                var lst_cat = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.분류) == false).OrderBy(t => t.분류).GroupBy(t => t.분류).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmb분류,lst_cat.Select(t => t.분류).ToArray());

                //Site
                var lst_sit = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Site) == false).OrderBy(t => t.Site).GroupBy(t => t.Site).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbSite,lst_sit.Select(t => t.Site).ToArray());

                //Line
                var lst_lin = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Line) == false).OrderBy(t => t.Line).GroupBy(t => t.Line).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbLine,lst_lin.Select(t => t.Line).ToArray());

                //division
                var lst_div = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Division) == false).OrderBy(t => t.Division).GroupBy(t => t.Division).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbDivision,lst_div.Select(t => t.Division).ToArray());

                ////Team
                //var lst_tem = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Team) == false).OrderBy(t => t.Team).GroupBy(t => t.Team).Select(t => t.FirstOrDefault());
                //SetComboboxItems(cmbTeam,lst_tem.Select(t => t.Team).ToArray());

                //Process
                var lst_prc = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.Process) == false).OrderBy(t => t.Process).GroupBy(t => t.Process).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmbProcess,lst_prc.Select(t => t.Process).ToArray());

                //외주업체
                var lst_ext = db.EETGW_JobReport_EBoard.Where(t => string.IsNullOrEmpty(t.외주업체) == false).OrderBy(t => t.외주업체).GroupBy(t => t.외주업체).Select(t => t.FirstOrDefault());
                SetComboboxItems(cmb외주업체,lst_ext.Select(t => t.외주업체).ToArray());
            }));


            ///원인
            if (string.IsNullOrEmpty(dr.원인2))
            {
                this.richTextBoxEx1.Text = dr.원인;
            }
            else
            {
                try
                {
                    this.richTextBoxEx1.Rtf = dr.원인2;
                }
                catch (Exception ex)
                {
                    this.richTextBoxEx1.Text = dr.원인;
                }
            }

            ///결과
            if (string.IsNullOrEmpty(dr.결과2))
            {
                this.richTextBoxEx2.Text = dr.결과;
            }
            else
            {
                try
                {
                    this.richTextBoxEx2.Rtf = dr.결과2;
                }
                catch (Exception ex)
                {
                    this.richTextBoxEx2.Text = dr.결과;
                }
            }




            this.tbSdate.Text = dr.pdate;
            this.tbEdate.Text = dr.수리완료일;
            this.tbQty.Text = dr.QTY.ToString();
            this.tbCostNew.Text = dr.NPrice.ToString();
            this.tbCostOutSource.Text = dr.OPrice.ToString();
            this.tbCostRepair.Text = dr.RepairCost.ToString();
            this.tbCostReduct.Text = dr.CostReduction.ToString();
            this.bs.DataSource = dr;

        }



        private void btSave_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();

            var s1 = tbCostOutSource.Text.Trim();
            var s2 = tbCostRepair.Text.Trim();
            float v1;
            float v2;
            var b1 = float.TryParse(s1, out v1);
            var b2 = float.TryParse(s2, out v2);

            if (b1 == false)
            {
                FCOMMON.Util.MsgE("입력값이 올바르지 않습니다. 숫자로 입력하세요");
                tbCostOutSource.SelectAll();
                tbCostOutSource.Focus();
                return;
            }

            if (b2 == false)
            {
                FCOMMON.Util.MsgE("입력값이 올바르지 않습니다. 숫자로 입력하세요");
                tbCostRepair.SelectAll();
                tbCostRepair.Focus();
                return;
            }
          

            if(tbSdate.Text.isEmpty()==false)
            {
                if(tbSdate.Text.isDate()==false)
                {
                    FCOMMON.Util.MsgE("날짜형태로 입력하세요\n\n예) 2000-01-01");
                    tbSdate.SelectAll();
                    tbSdate.Focus();
                    return;
                }
            }
            if (tbEdate.Text.isEmpty() == false)
            {
                if (tbEdate.Text.isDate() == false)
                {
                    FCOMMON.Util.MsgE("날짜형태로 입력하세요\n\n예) 2000-01-01");
                    tbEdate.SelectAll();
                    tbEdate.Focus();
                    return;
                }
            }

            this.dr.원인 = richTextBoxEx1.Text;
            this.dr.원인2 = richTextBoxEx1.Rtf;

            this.dr.결과 = richTextBoxEx2.Text;
            this.dr.결과2 = richTextBoxEx2.Rtf;


            this.dr.pdate = tbSdate.Text.Trim();
            this.dr.수리완료일 = tbEdate.Text.Trim();
            this.dr.QTY = tbQty.Text.ToInt();
            this.dr.NPrice = tbCostNew.Text.ToDecimal();
            this.dr.OPrice = tbCostOutSource.Text.ToDecimal();
            this.dr.RepairCost = tbCostRepair.Text.ToDecimal();
            this.dr.CostReduction = tbCostReduct.Text.ToDecimal();
            this.dr.EndEdit();


            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
            //this.tableAdapterManager.UpdateAll(this.dsPRJ);
        }





        void SelectDate(TextBox ctl)
        {
            DateTime dt;
            var dateStr = ctl.Text.Trim();
            if (dateStr == "") dateStr = DateTime.Now.ToShortDateString();
            else
            {
                if (DateTime.TryParse(dateStr, out dt)) dateStr = dt.ToShortDateString();
                else
                {
                    FCOMMON.Util.MsgE("날짜 형식으로 변환할 수 없는 문자열 입니다.\n" +
                        "기준일자가 금일로 변경 됩니다");
                    dateStr = DateTime.Now.ToShortDateString();
                }
            }
            dt = DateTime.Parse(dateStr);
            var f = new FCOMMON.fSelectDay(dt);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ctl.Text = f.dtPick.SelectionStart.ToShortDateString();
            }
        }
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbSdate);
        }



        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbEdate);
            //if (edateTextBox.Text.isEmpty() == false)
            //    cmbStatus.Text = "완료";
        }



        private void bs_CurrentChanged(object sender, EventArgs e)
        {

        }




        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
        private void tbQty_TextChanged(object sender, EventArgs e)
        {
            //수량변경시 금액 업데이트           
            var qty = tbQty.Text.ToInt();
            var nAmt = tbCostNew.Text.ToDouble();
            var oAmt = (nAmt * qty) * 0.5f;
            var rAmt = tbCostRepair.Text.ToDouble();
            var reduction = oAmt - rAmt;
            this.tbCostOutSource.Text = oAmt.ToString();
            //this.tbCostReduct.Text = reduction.ToString();
        }

        private void costnTextBox_TextChanged(object sender, EventArgs e)
        {
            //Out source 가 변경되면 
            var oAmt = tbCostOutSource.Text.ToDouble();
            var rAmt = tbCostRepair.Text.ToDouble();
            var reduction = oAmt - rAmt;
            tbCostReduct.Text = reduction.ToString();
        }



    }
}
