using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AR;

namespace Project.Dialog
{
    public partial class fSelectJob : Form
    {
        public fSelectJob()
        {
            InitializeComponent();
            this.tabControl1.Visible = false;
            this.UpdateHeight();

            this.KeyPreview = true;
            this.FormClosing += __Closing;
            this.lbTitle.MouseMove += LbTitle_MouseMove;
            this.lbTitle.MouseUp += LbTitle_MouseUp;
            this.lbTitle.MouseDown += LbTitle_MouseDown;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };

            if (System.Diagnostics.Debugger.IsAttached == false)
            {
                //// = new Dialog.fBlurPanel();
                //fb.Show();
            }
            this.Text = $"Job Start ({PUB.Result.vModel.Title})";

            PUB.flag.set(eVarBool.FG_SCR_JOBSELECT, true, "selectjbo");
            PUB.dio.IOValueChanged += Dio_IOValueChanged;

            //var visionoff = PUB.Result.vModel.DisableCamera || (SETTING.Data.Enable_Unloader_QRValidation == false);
            List<string> offlist = new List<string>();
            if (SETTING.Data.SystemBypass || PUB.Result.vModel.DisableCamera || SETTING.Data.Enable_Unloader_QRValidation == false)
                offlist.Add("Camera");
            if (SETTING.Data.SystemBypass || PUB.Result.vModel.DisablePrinter || (SETTING.Data.Disable_PrinterL && SETTING.Data.Disable_PrinterR))
                offlist.Add("Printer");
            if (offlist.Any())
            {
                var msg = "(" + string.Join("/", offlist) + ") usage is turned OFF";
                lbMsgCamoff.Text = msg;
            }

            lbMsgCamoff.Visible = offlist.Any();
        }

        List<string> custlist = new List<string>();
        private void __LoaD(object sender, EventArgs e)
        {
            label1.Text = VAR.BOOL[eVarBool.Use_Conveyor] ? "CONVEYOR ON" : "CONVEYOR OFF";
            lbTitle.Text = PUB.Result.vModel.Title;
            var codelist = PUB.Result.vModel.Code.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            this.cmbCustCode.Items.Clear();
            foreach (var item in codelist)
                if (item.isEmpty() == false) cmbCustCode.Items.Add(item);

            //마지막에 등록된데이터 기준으로 추가
            custlist = SETTING.User.customerlist.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (var item in custlist)
            {
                cmbCustCode.Items.Add(item.Trim());
            }


            if (cmbCustCode.Items.Count > 0)
                cmbCustCode.SelectedIndex = 0;

            //자료를 조회하고 대표 코드가 잇으면 처리한다. 221013
            var taSID = new DataSet1TableAdapters.SidinfoCustGroupTableAdapter();
            var dtcustgrp = taSID.GetData();
            if (dtcustgrp != null && dtcustgrp.Count == 1)
                cmbCustCode.Text = dtcustgrp.First().CustCode;

            //프리셋가져온다
            var ta = new DataSet1TableAdapters.K4EE_Component_Reel_PreSetTableAdapter();
            ta.Fill(this.dataSet11.K4EE_Component_Reel_PreSet, "R1");

            //작업형태를 다시 시작해준다. - 210329
            if (PUB.Result.JobType2.isEmpty()) PUB.Result.JobType2 = "Model Info";
            Func_SelectJobType("M");
        }

        //그룹박스내의 아이템중에 Black,blue  아이템갯수를 반환한다
        Tuple<int, int> CheckDataIn(GroupBox g)
        {
            int black = 0;
            int blue = 0;
            foreach (var item in g.Controls)
            {
                if (item.GetType() == typeof(CheckBox))
                {
                    var chk = item as CheckBox;
                    if (chk.Checked == false) continue;
                    if (chk.ForeColor == Color.Blue)
                        blue += 1;
                    else black += 1;
                }
            }
            return new Tuple<int, int>(black, blue);

        }

        private void Dio_IOValueChanged(object sender, arDev.DIO.IOValueEventArgs e)
        {
            if (AR.SETTING.Data.Enable_ButtonStart)
            {
                var pin = (eDIName)e.ArrIDX;
                if (DIO.GetIOInput(pin) == true)
                {
                    if (pin == eDIName.BUT_STARTF) this.Confirm();
                    else if (pin == eDIName.BUT_STOPF || pin == eDIName.BUT_RESETF) this.Cancel();
                }
            }
        }


        void Confirm()
        {
            if (this.InvokeRequired)
                this.BeginInvoke(new MethodInvoker(Confirm), null);
            else
            {
                if (System.Diagnostics.Debugger.IsAttached) this.TopMost = false;
                this.Validate();

                if (this.ModeData.isEmpty() || this.ModeData == "--")
                {
                    UTIL.MsgE("Work method is not selected");
                    return;
                }
                if (this.ModeData == "--")
                {
                    UTIL.MsgE("Unusable work method");
                    return;
                }
                if (GrpSidConvData.Enabled)
                {
                    //검색조건확인
                    var v = CheckDataIn(GrpSidConvData);
                    if (v.Item1 < 1)
                    {
                        UTIL.MsgE("Target item is not specified among server record items");
                        return;
                    }
                    if (v.Item2 < 1)
                    {
                        UTIL.MsgE("Search item is not specified among server record items");
                        return;
                    }
                }
                if (grpapplyjob.Enabled)
                {
                    //검색조건확인
                    var v = CheckDataIn(grpapplyjob);
                    if (v.Item1 < 1)
                    {
                        UTIL.MsgE("Target item is not specified among daily work items");
                        return;
                    }
                    if (v.Item2 < 1)
                    {
                        UTIL.MsgE("Search item is not specified among daily work items");
                        return;
                    }
                }
                if (grpApplyWMSinfo.Enabled)
                {
                    //검색조건확인
                    var v = CheckDataIn(grpApplyWMSinfo);
                    if (v.Item1 < 1)
                    {
                        UTIL.MsgE("Target item is not specified among WMS information items");
                        return;
                    }
                    if (v.Item2 < 1)
                    {
                        UTIL.MsgE("Search item is not specified among WMS information items");
                        return;
                    }
                }
                if (grpApplySidinfo.Enabled)
                {
                    //검색조건확인
                    var v = CheckDataIn(grpApplySidinfo);
                    if (v.Item1 < 1)
                    {
                        UTIL.MsgE("Target item is not specified among SID information items");
                        return;
                    }
                    if (v.Item2 < 1)
                    {
                        UTIL.MsgE("Search item is not specified among SID information items");
                        return;
                    }
                }

                if (chkCustom.Checked) PUB.MCCode = AR.SETTING.Data.McName;
                else PUB.MCCode = "R0";

                var curcust = this.cmbCustCode.Text.Trim();
                if (curcust.isEmpty() == false)
                {
                    //신규코드는 저장한다
                    if (this.custlist.Contains(curcust) == false)    //
                    {
                        this.custlist.Insert(0, curcust);
                        if (this.custlist.Count > 10) this.custlist.RemoveAt(custlist.Count - 1);
                        SETTING.User.customerlist = string.Join(";", this.custlist);
                        SETTING.User.Save();
                    }
                }

                //230509
                if (chkSIDConv.Checked)
                {
                    try
                    {
                        //sid정보테이블을 다시 불러온다
                        var taConv = new DataSet1TableAdapters.K4EE_Component_Reel_SID_ConvertTableAdapter();
                        PUB.Result.DTSidConvert.Clear();
                        taConv.Fill(PUB.Result.DTSidConvert);
                        PUB.Result.DTSidConvert.AcceptChanges();
                        PUB.Result.DTSidConvertEmptyList.Clear();
                        PUB.Result.DTSidConvertMultiList.Clear();
                        PUB.log.Add($"sid conversion table {PUB.Result.DTSidConvert.Rows.Count} cases confirmed");
                    }
                    catch (Exception ex)
                    {
                        UTIL.MsgE("SID conversion information check failed\n" + ex.Message);
                        return;
                    }
                }

                //작업형태 지정
                PUB.Result.JobType2 = this.ModeData;



                PUB.flag.set(eVarBool.FG_ENABLE_LEFT, AR.SETTING.Data.Disable_Left == false, "START");
                PUB.flag.set(eVarBool.FG_ENABLE_RIGHT, AR.SETTING.Data.Disable_Right == false, "START");

                //옵션사항 설정 210121
                VAR.BOOL[eVarBool.Opt_UserConfim] = chkUserConfirm.Checked;
                VAR.BOOL[eVarBool.Opt_ServerQty] = chkQtyServer.Checked;
                VAR.BOOL[eVarBool.Opt_NewReelID] = chkNew.Checked;
                VAR.BOOL[eVarBool.Opt_UserQtyRQ] = chkQtyMRQ.Checked;
                VAR.BOOL[eVarBool.Opt_SIDConvert] = chkSIDConv.Checked;

                VAR.BOOL[eVarBool.Opt_ApplySIDConv] = chkApplySIDConv.Checked;
                VAR.BOOL[eVarBool.Opt_ApplyJobInfo] = chkApplyJobInfo.Checked;
                VAR.BOOL[eVarBool.Opt_ApplyWMSInfo] = chkApplyWMSInfo.Checked;
                VAR.BOOL[eVarBool.Opt_ApplySIDInfo] = chkApplySidInfo.Checked;
                VAR.BOOL[eVarBool.Opt_CheckSIDExist] = PUB.Result.vModel.CheckSIDExsit;

                //모델에서  카메라  사용을  끄거나, 환경설정에서  QRValidation 을  사용하지  않는  경우
                if (SETTING.Data.SystemBypass) VAR.BOOL[eVarBool.Opt_DisableCamera] = true;
                else VAR.BOOL[eVarBool.Opt_DisableCamera] = PUB.Result.vModel.DisableCamera || (SETTING.Data.Enable_Unloader_QRValidation == false);

                //BYPASS MODEL,모델에서  프린터가  껴져있거나, 환경설정에서  양쪽의 프린터를  사용하지 않는 경우
                if (SETTING.Data.SystemBypass) VAR.BOOL[eVarBool.Opt_DisablePrinter] = true;
                else VAR.BOOL[eVarBool.Opt_DisablePrinter] = PUB.Result.vModel.DisablePrinter || (SETTING.Data.Disable_PrinterL && SETTING.Data.Disable_PrinterR);


                //WMS Information
                VAR.BOOL[eVarBool.Opt_WMS_Apply_PartNo] = checkBox47.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Apply_CustCode] = checkBox46.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Apply_SID] = checkBox45.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Apply_VenderName] = checkBox41.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Apply_batch] = chkWMSApplyBatch.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Apply_qty] = false;// chkInfoApplyQty.Checked;

                VAR.BOOL[eVarBool.Opt_WMS_Where_PartNo] = checkBox44.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Where_CustCode] = checkBox43.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Where_SID] = checkBox42.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Where_VLOT] = checkBox36.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_Where_MC] = false;// chkInfoWhereMC.Checked;
                VAR.BOOL[eVarBool.Opt_WMS_WriteServer] = false;// chkInfoSave.Checked;

                //SID Information
                VAR.BOOL[eVarBool.Opt_SID_Apply_PartNo] = chkInfoApplyPart.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Apply_CustCode] = chkInfoApplyCust.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Apply_SID] = chkInfoApplySID.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Apply_VenderName] = chkInfoApplyVender.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Apply_PrintPos] = chkInfoApplyPrint.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Apply_batch] = chkInfoApplyBatch.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Apply_qty] = false;// chkInfoApplyQty.Checked;

                VAR.BOOL[eVarBool.Opt_SID_Where_PartNo] = chkInfoWherePart.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Where_CustCode] = chkInfoWhereCust.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Where_SID] = chkInfoWhereSID.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Where_VLOT] = chkInfoWhereLot.Checked;
                VAR.BOOL[eVarBool.Opt_SID_Where_MC] = false;// chkInfoWhereMC.Checked;
                VAR.BOOL[eVarBool.Opt_SID_WriteServer] = chkInfoSave.Checked;


                VAR.BOOL[eVarBool.Opt_Job_Apply_PartNo] = chkDayApplyPart.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Apply_CustCode] = chkDayApplyCust.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Apply_SID] = chkDayApplySID.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Apply_VenderName] = chkDayApplyVender.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Apply_PrintPos] = chkDayApplyPrint.Checked;

                VAR.BOOL[eVarBool.Opt_Job_Where_PartNo] = chkDayWherePart.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Where_CustCode] = chkDayWhereCust.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Where_SID] = chkDayWhereSID.Checked;
                VAR.BOOL[eVarBool.Opt_Job_Where_VLOT] = chkDayWhereLot.Checked;

                VAR.BOOL[eVarBool.Opt_Conv_Apply_PartNo] = chkCVApplyPartno.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Apply_CustCode] = chkCVApplyCust.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Apply_SID] = chkCVApplySID.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Apply_VenderName] = chkCVApplyVender.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Apply_PrintPos] = chkCVApplyPrint.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Apply_Batch] = chkCVApplyBatch.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Apply_QtyMax] = false;// chkCVApplyQtyMax.Checked;

                VAR.BOOL[eVarBool.Opt_Conv_Where_PartNo] = chkCVWherePart.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Where_CustCode] = chkCVWhereCust.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Where_SID] = chkCVWhereSID.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_Where_VLOT] = chkCVWhereLot.Checked;
                VAR.BOOL[eVarBool.Opt_Conv_WriteServer] = chkCVSave.Checked;

                VAR.STR[eVarString.JOB_CUSTOMER_CODE] = cmbCustCode.Text.Trim();
                //VAR.STR[eVarString.JOB_BYPASS_SID] = tbBypassSID.Text.Trim(); //add bypass sid 230511
                // VAR.STR[eVarString.JOB_TYPE] = tbJobtype.Text.Trim();
                this.DialogResult = DialogResult.OK;
            }

        }
        void Cancel()
        {
            if (this.InvokeRequired)
                this.BeginInvoke(new MethodInvoker(Cancel), null);
            else
                this.Close();
        }

        void __Closing(object sender, FormClosingEventArgs e)
        {
            // if (fb != null) fb.Dispose();
            PUB.dio.IOValueChanged -= Dio_IOValueChanged;
            PUB.flag.set(eVarBool.FG_SCR_JOBSELECT, false, "selectjbo");
        }


        #region "Mouse Form Move"

        private Boolean fMove = false;
        private Point MDownPos;
        private void LbTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (fMove)
            {
                Point offset = new Point(e.X - MDownPos.X, e.Y - MDownPos.Y);
                this.Left += offset.X;
                this.Top += offset.Y;
                offset = new Point(0, 0);
            }
        }
        private void LbTitle_MouseUp(object sender, MouseEventArgs e)
        {
            fMove = false;
        }
        private void LbTitle_MouseDown(object sender, MouseEventArgs e)
        {
            MDownPos = new Point(e.X, e.Y);
            fMove = true;
        }

        #endregion



        private void btCancle_Click(object sender, EventArgs e)
        {
            Cancel();
        }


        arCtl.arLabel[] btsMOD;
        string ModeData = string.Empty;
        void Func_SelectJobType(string mode)
        {
            if (mode.Equals("--"))
            {
                UTIL.MsgE("Unusable button");
                return;
            }
            ModeData = mode;

            var dr = PUB.Result.vModel;

            //update checkbox
            foreach (var c in tabPage1.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Checked = UTIL.GetBitState(dr.vOption, int.Parse(chk.Tag.ToString()));
            }
            foreach (var c in grpApplyWMSinfo.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Checked = UTIL.GetBitState(dr.vWMSInfo, int.Parse(chk.Tag.ToString()));
            }
            foreach (var c in grpApplySidinfo.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Checked = UTIL.GetBitState(dr.vSIDInfo, int.Parse(chk.Tag.ToString()));
            }
            foreach (var c in grpapplyjob.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Checked = UTIL.GetBitState(dr.vJobInfo, int.Parse(chk.Tag.ToString()));
            }
            foreach (var c in GrpSidConvData.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Checked = UTIL.GetBitState(dr.vSIDConv1, int.Parse(chk.Tag.ToString()));
            }

            //프린터를 사용하지 않는다면 코드입력창 비활성화
            if (dr.DisablePrinter)
            {
                cmbCustCode.Text = "0000";
                cmbCustCode.Enabled = false;
                button1.Enabled = false;
            }

        }



        private void checkBox1_CheckStateChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckBox;
            chk.ForeColor = chk.Checked ? Color.Blue : Color.Gray;

            if (chk.Name.Equals(chkApplyJobInfo.Name))
            {
                grpapplyjob.Enabled = chk.Checked;
            }
            if(chk.Name.Equals(chkApplyWMSInfo.Name))
            {
                grpApplyWMSinfo.Enabled = chk.Checked;
            }
            if (chk.Name.Equals(chkApplySidInfo.Name))
            {
                grpApplySidinfo.Enabled = chk.Checked;
            }
            if (chk.Name.Equals(chkApplySIDConv.Name))
            {
                GrpSidConvData.Enabled = chk.Checked;
            }
        }



        private void btOK_MouseClick(object sender, MouseEventArgs e)
        {

      


        }


        private void 옵션적용ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //현재선택된 옵션을 변경한다
            var ctl = UTIL.GetContextOwnerControl(sender);
            if (ctl == null) return;
            var bt = ctl as arCtl.arLabel;
            var txt = bt.Text.Trim();

            var tagstr = bt.Tag.ToString();
            if (tagstr == "M")   //모델기본
            {
                UTIL.MsgI("This model is a default model. Please update it on the [Work Model] screen");
            }
            else
            {
                var dlg = UTIL.MsgQ($"Do you want to change the {txt} item option to the current value??");
                if (dlg != DialogResult.Yes) return;

                var dr = this.dataSet11.K4EE_Component_Reel_PreSet.Where(t => t.Title == txt).FirstOrDefault();
                if (dr == null)
                {
                    UTIL.MsgE("Preset information not found, creating new preset");
                    return;
                }
                dr.MC = "R1";// AR.SETTING.Data.McName;
                             // dr.jobtype = tbJobtype.Text;
                             //dr.bypasssid = tbBypassSID.Text;
                             //assig check events
                foreach (var c in tabPage1.Controls)
                {
                    if (c.GetType() != typeof(CheckBox)) continue;
                    var chk = c as CheckBox;
                    if (chk.Tag == null) continue;
                    dr.vOption = UTIL.SetBitState((ushort)dr.vOption, int.Parse(chk.Tag.ToString()), chk.Checked);
                }
                foreach (var c in grpApplyWMSinfo.Controls)
                {
                    if (c.GetType() != typeof(CheckBox)) continue;
                    var chk = c as CheckBox;
                    if (chk.Tag == null) continue;
                    dr.vWMSInfo = UTIL.SetBitState((ushort)dr.vWMSInfo, int.Parse(chk.Tag.ToString()), chk.Checked);
                }
                foreach (var c in grpApplySidinfo.Controls)
                {
                    if (c.GetType() != typeof(CheckBox)) continue;
                    var chk = c as CheckBox;
                    if (chk.Tag == null) continue;
                    dr.vSidInfo = UTIL.SetBitState((ushort)dr.vSidInfo, int.Parse(chk.Tag.ToString()), chk.Checked);
                }
                foreach (var c in grpapplyjob.Controls)
                {
                    if (c.GetType() != typeof(CheckBox)) continue;
                    var chk = c as CheckBox;
                    if (chk.Tag == null) continue;
                    dr.vJobInfo = UTIL.SetBitState((ushort)dr.vJobInfo, int.Parse(chk.Tag.ToString()), chk.Checked);
                }
                foreach (var c in GrpSidConvData.Controls)
                {
                    if (c.GetType() != typeof(CheckBox)) continue;
                    var chk = c as CheckBox;
                    if (chk.Tag == null) continue;
                    dr.vServerWrite = UTIL.SetBitState((ushort)dr.vServerWrite, int.Parse(chk.Tag.ToString()), chk.Checked);
                }
                dr.EndEdit();

                var ta = new DataSet1TableAdapters.K4EE_Component_Reel_PreSetTableAdapter();
                var rlt = ta.Update(this.dataSet11.K4EE_Component_Reel_PreSet) == 1;
                if (rlt == false) UTIL.MsgE("Change failed");
            }


        }


        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.TopMost = false;
            var f = new AR.Dialog.fTouchKeyFull("CUSTOMER CODE", cmbCustCode.Text.Trim());
            if (f.ShowDialog() == DialogResult.OK)
            {
                cmbCustCode.Text = f.tbInput.Text.Trim();
                if (cmbCustCode.Text.isEmpty() == false)
                {
                    if (cmbCustCode.Text.Length == 3)
                        cmbCustCode.Text = "0" + cmbCustCode.Text;
                }
            }
            this.TopMost = true;
        }

        private void lbTitle_Click(object sender, EventArgs e)
        {
            this.tabControl1.Visible = !tabControl1.Visible;
            UpdateHeight();
        }

        void UpdateHeight()
        {
            if (this.tabControl1.Visible) this.Height = 755;
            else this.Height = 380;
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            Confirm();
        }
    }
}
