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

namespace Project.Dialog
{
    public partial class fSelectSIDInformation : Form
    {
        Boolean autoconf = false;
        Boolean warn = false;
        Boolean samesidwarn = false;
        bool NewReelId = false;
        public fSelectSIDInformation()
        {
            InitializeComponent();
            VAR.BOOL[eVarBool.FG_WAIT_INFOSELECT] = true;
            this.WindowState = FormWindowState.Normal;
            var sql = VAR.STR[eVarString.MULTISID_QUERY];
            var fields = VAR.STR[eVarString.MULTISID_FIELDS];
            this.lbExecuteSQL.Text = sql;
            this.FormClosed += FLoaderInfo_FormClosed;
        }


        private void FLoaderInfo_FormClosed(object sender, FormClosedEventArgs e)
        {
            VAR.BOOL[eVarBool.FG_WAIT_INFOSELECT] = false;
            PUB.Result.ItemDataC.VisionData.PropertyChanged -= VisionData_PropertyChanged;

            ////사용자가 정보를 정확히 입력하지 않고 닫았다
            //if (PUB.Result.ItemDataC.VisionData.Confirm == false)
            //{
            //    if (PUB.sm.Step == eSMStep.RUN)
            //        PUB.Result.SetResultMessage(eResult.OPERATION, eECode.INCOMPLETE_INFOSELECT, eNextStep.PAUSE, 1);
            //}
        }

        private void fLoaderInfo_Load(object sender, EventArgs e)
        {
            var sql = VAR.STR[eVarString.MULTISID_QUERY];
            var fields = VAR.STR[eVarString.MULTISID_FIELDS];

            try
            {
                var cn = DBHelper.GetConnection();
                var cmd = new SqlCommand(sql, cn);
                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                int i = 0;
                this.dsWMS.VW_GET_MAX_QTY_VENDOR_LOT.Clear();
                foreach (DataRow dr in dt.Rows)
                {
                    var newdr = this.dsWMS.VW_GET_MAX_QTY_VENDOR_LOT.NewVW_GET_MAX_QTY_VENDOR_LOTRow();
                    newdr.idx = dsWMS.VW_GET_MAX_QTY_VENDOR_LOT.Count + 1;
                    if (dt.Columns.Contains("SID")) newdr.SID = dr["SID"]?.ToString() ?? string.Empty;
                    else newdr.SID = string.Empty;
                    if (dt.Columns.Contains("PART_NO")) newdr.PART_NO = dr["PART_NO"]?.ToString() ?? string.Empty;
                    else newdr.PART_NO = string.Empty;
                    if (dt.Columns.Contains("VENDOR_LOT")) newdr.VENDOR_LOT = dr["VENDOR_LOT"]?.ToString() ?? string.Empty;
                    else newdr.VENDOR_LOT = string.Empty;
                    if (dt.Columns.Contains("VENDOR_NM")) newdr.VENDOR_NM = dr["VENDOR_NM"]?.ToString() ?? string.Empty;
                    else newdr.VENDOR_NM = string.Empty;
                    if (dt.Columns.Contains("BATCH_NO")) newdr.BATCH_NO = dr["BATCH_NO"]?.ToString() ?? string.Empty;
                    else newdr.BATCH_NO = string.Empty;
                    if (dt.Columns.Contains("CUST_CODE")) newdr.CUST_CODE = dr["CUST_CODE"]?.ToString() ?? string.Empty;
                    else newdr.CUST_CODE = string.Empty;
                    if (dt.Columns.Contains("MFG_DATE")) newdr.MFG_DATE = dr["MFG_DATE"]?.ToString() ?? string.Empty;
                    else newdr.MFG_DATE = string.Empty;
                    if (dt.Columns.Contains("QTY")) newdr.QTY = (dr["QTY"]?.ToString() ?? "0").toInt();
                    else newdr.QTY = 0;


                    this.dsWMS.VW_GET_MAX_QTY_VENDOR_LOT.AddVW_GET_MAX_QTY_VENDOR_LOTRow(newdr);//?.ToString() ??
                                                                                                //string.Empty;
                }

                dsWMS.VW_GET_MAX_QTY_VENDOR_LOT.AcceptChanges();
                //this.dv1.DataSource = null;
                //this.dv1.Rows.Clear();
                //this.dv1.Columns.Clear();

                //var cols = new String[] { "No", "SID", "PartNo", "VendorLot", "VendorName", "MFGDate", "Qty" };
                //foreach (var colname in cols)
                //    this.dv1.Columns.Add($"col_{colname}", colname);

                //foreach (dsWMS.VW_GET_MAX_QTY_VENDOR_LOTRow row in dsWMS.VW_GET_MAX_QTY_VENDOR_LOT)
                //{
                //    this.dv1.Rows.Add(new string[] { });
                //}
            }
            catch (Exception ex)
            {
                UTIL.MsgE($"Data Query Error\n{ex.Message}");
            }

            //현재 바코드가 읽었단 자료를 모두 표시한다.
            var item = PUB.Result.ItemDataC;
            NewReelId = item.VisionData.RIDNew;
            tbSID.Text = item.VisionData.SID;
            tbLot.Text = item.VisionData.VLOT;
            tbMFG.Text = item.VisionData.MFGDATE;
            tbVName.Text = item.VisionData.VNAME;
            tbPart.Text = item.VisionData.PARTNO;
            TbCustCode.Text = item.VisionData.CUSTCODE;
            tbBatch.Text = item.VisionData.BATCH;
            

            selectInput(this.tbSID);

            if (tbVName.Text.isEmpty())
                if (PUB.Result.vModel.Def_Vname.isEmpty() == false)
                    tbVName.Text = PUB.Result.vModel.Def_Vname;

            if (tbMFG.Text.isEmpty())
                if (PUB.Result.vModel.Def_MFG.isEmpty() == false)
                    tbMFG.Text = PUB.Result.vModel.Def_MFG;

            item.VisionData.PropertyChanged += VisionData_PropertyChanged;

            this.Show();
            this.dv1.AutoResizeColumns();
        }

        delegate void UpdateTextHandler(Control ctrl, string value);
        public void UpdateText(Control ctrl, string value)
        {
            if (ctrl is Label || ctrl is TextBox)
            {
                if (ctrl.InvokeRequired)
                {
                    ctrl.BeginInvoke(new UpdateTextHandler(UpdateText), new object[] { ctrl, value });
                }
                else if (ctrl is Label)
                    ((Label)ctrl).Text = value;
                else if (ctrl is TextBox)
                    ((TextBox)ctrl).Text = value;
            }

        }

        private void VisionData_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //값이 바뀌었으나 현재 값이 입력되지 않았따면 처리해준다. 220712
            var item = PUB.Result.ItemDataC;

            if (e.PropertyName.Equals("MFGDATE") && tbMFG.Text.isEmpty())
                UpdateText(tbMFG, item.VisionData.MFGDATE);

            if (e.PropertyName.Equals("VNAME") && tbVName.Text.isEmpty())
                UpdateText(tbVName, item.VisionData.VNAME);

            if (e.PropertyName.Equals("PARTNO") && tbPart.Text.isEmpty())
                UpdateText(tbPart, item.VisionData.PARTNO);

            if (e.PropertyName.Equals("CUSTCODE") && TbCustCode.Text.isEmpty())
                UpdateText(TbCustCode, item.VisionData.CUSTCODE); //210317

            if (e.PropertyName.Equals("SID") && tbSID.Text.isEmpty())
                UpdateText(tbSID, item.VisionData.SID);

            if (e.PropertyName.Equals("VLOT") && tbLot.Text.isEmpty())
                UpdateText(tbLot, item.VisionData.VLOT);
        }


        string TagStr = string.Empty;
        void selectInput(Control c)
        {
            TagStr = string.Empty;
            if (c is TextBox)
            {
                var tb = c as TextBox;
                TagStr = tb.Tag.ToString();
            }
            else if (c is Label)
            {
                var lb = c as Label;
                TagStr = lb.Tag.ToString();
            }

            //동일태그를 가진 textbox 의 배경색을 업데이트한다
            foreach (Control tb in panel3.Controls)
            {
                if (tb is TextBox)
                {
                    if (tb.Tag.ToString() == TagStr)
                    {
                        tb.BackColor = Color.SkyBlue;
                    }
                    else tb.BackColor = SystemColors.Control;
                }
            }
        }




        private void tbDate_Click(object sender, EventArgs e)
        {
            selectInput(sender as TextBox);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            var dtstr = this.tbMFG.Text.Trim().Replace("-", "").Replace("/", "");
            if (dtstr.Length == 8)
            {
                dt = new DateTime(
                    int.Parse(dtstr.Substring(0, 4)),
                    int.Parse(dtstr.Substring(4, 2)),
                    int.Parse(dtstr.Substring(6, 2)));
            }

            var f = new Dialog.fSelectDay(dt);
            if (f.ShowDialog() == DialogResult.OK)
            {
                this.tbMFG.Text = f.dt.ToShortDateString();
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UTIL.TouchKeyShow(tbSID, "INPUT SID");
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UTIL.TouchKeyShow(tbLot, "INPUT VENDER LOT");
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UTIL.TouchKeyShow(tbMFG, "INPUT MFG DATE");
        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UTIL.TouchKeyShow(tbVName, "INPUT SUPPLY NAME");
        }

        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //tbpartno
            UTIL.TouchKeyShow(tbPart, "INPUT CUSTOMER PART NO.");
        }


        private void linkLabel8_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UTIL.TouchKeyShow(TbCustCode, "INPUT SUPPLY CODE");
        }


        private void btOK_Click(object sender, EventArgs e)
        {
            bool topmost = this.TopMost;
            //var IsBypas = VAR.STR[eVarString.JOB_TYPE] == "BP";
            if (System.Diagnostics.Debugger.IsAttached)
                this.TopMost = false;

            var itemC = PUB.Result.ItemDataC;

            //manu 목록에 없다면 추가 해준다.
            var manuName = tbVName.Text.Trim().ToLower();
            if (manuName.isEmpty() == false)
            {
                lock (PUB.Result.dsList)
                {
                    if (PUB.Result.dsList.Supply.Where(t => t.TITLE.ToLower() == manuName).Any() == false)
                    {
                        //기존 manu 목록에 없으니 추가한다.
                        var newdr = PUB.Result.dsList.Supply.NewSupplyRow();
                        newdr.TITLE = tbVName.Text.Trim();
                        PUB.Result.dsList.Supply.AddSupplyRow(newdr);
                        PUB.Result.SaveListDB();
                    }
                }
            }

            //필수값 입력 확인
            #region "Check iNput Data"
            if (tbSID.Text.isEmpty())
            {
                UTIL.MsgE("SID was not entered");
                tbSID.Focus();
                return;
            }

            //if (tbLot.Text.isEmpty())
            //{
            //    UTIL.MsgE("VLOT 가 입력되지 않았습니다");
            //    tbLot.Focus();
            //    return;
            //}

            //if (tbMFG.Text.isEmpty())
            //{
            //    UTIL.MsgE("MFG-DATE 가 입력되지 않았습니다");
            //    tbMFG.Focus();
            //    return;
            //}

            //if (this.tbPart.Text.isEmpty())
            //{
            //    UTIL.MsgE("PART No 가 입력되지 않았습니다");
            //    tbPart.Focus();
            //    return;
            //}

            #endregion

            //현재 작업모드와 SID가 일치하는지 확인한다.
            var sidNew = this.tbSID.Text.Trim();
            var partNo = this.tbPart.Text.Trim();
            var custCode = this.TbCustCode.Text.Trim();

            //모든자료는 존재한다 저장가능하다
            if (AR.SETTING.Data.OnlineMode)
            {
                //시드정보테이블의 데이터를 역으로 저장한 경우
                if (VAR.BOOL[eVarBool.Opt_ApplySIDInfo] && VAR.BOOL[eVarBool.Opt_SID_WriteServer])
                {
                    Dictionary<string, string> wheres = new Dictionary<string, string>();
                    Dictionary<string, string> columns = new Dictionary<string, string>();

                    //조건절생성
                    if (VAR.BOOL[eVarBool.Opt_SID_Where_CustCode]) wheres.Add("CustCode", TbCustCode.Text);
                    if (VAR.BOOL[eVarBool.Opt_SID_Where_PartNo]) wheres.Add("PartNo", tbPart.Text);
                    if (VAR.BOOL[eVarBool.Opt_SID_Where_SID]) wheres.Add("SID", tbSID.Text);
                    if (VAR.BOOL[eVarBool.Opt_SID_Where_VLOT]) wheres.Add("VenderLot", tbLot.Text);

                    //Make Target COlumns
                    if (VAR.BOOL[eVarBool.Opt_SID_Apply_CustCode]) columns.Add("CustCode", TbCustCode.Text);
                    if (VAR.BOOL[eVarBool.Opt_SID_Apply_PartNo]) columns.Add("PartNo", tbPart.Text);
                    //if (VAR.BOOL[eVarBool.Opt_SID_Apply_PrintPos]) columns.Add("PrintPosition", this.PrintPos);
                    if (VAR.BOOL[eVarBool.Opt_SID_Apply_SID])
                    {
                        //SID변환기능이 동작한상태에서는 변환된 SID정보를 저장하지 않는다 230510
                        if (VAR.BOOL[eVarBool.Opt_SIDConvert])
                        {
                            PUB.log.AddAT($"SID information is not updated due to the use of SID conversion function");
                        }
                        else columns.Add("SID", tbSID.Text);
                    }
                    if (VAR.BOOL[eVarBool.Opt_SID_Apply_VenderName]) columns.Add("VenderName", tbVName.Text);

                    //EE-SID정보에 데이터를 저장한다
                    ServerWriteINF_EED(columns, wheres);
                    //ServerWriteINF_WMS(columns, wheres);
                }
            }

            //값을 설정해주고 빠져나간다
            if (tbSID.Text.isEmpty() &&
                itemC.VisionData.SID.isEmpty() == false &&
                itemC.VisionData.SID.Equals(tbSID.Text.Trim()) == false)
                itemC.VisionData.SID0 = itemC.VisionData.SID;

            //값이있는것들만 기록해준다.
            if (tbSID.Text.isEmpty() == false) itemC.VisionData.SID = tbSID.Text.Trim();
            if (tbBatch.Text.isEmpty() == false) itemC.VisionData.BATCH = tbBatch.Text.Trim();
            if (tbLot.Text.isEmpty() == false) itemC.VisionData.VLOT = tbLot.Text.Trim();
            if (tbMFG.Text.isEmpty() == false) itemC.VisionData.MFGDATE = tbMFG.Text.Trim();
            if (tbVName.Text.isEmpty() == false) itemC.VisionData.VNAME = tbVName.Text.Trim();
            if (tbPart.Text.isEmpty() == false) itemC.VisionData.PARTNO = tbPart.Text.Trim();

            this.TopMost = topmost;
            this.Close();
        }


        /// <summary>
        /// 지정한 자료를 서버에 기록합니다. 조건절과 대상 열을 제공해야합니다
        /// </summary>
        void ServerWriteINF_WMS(Dictionary<string, string> columns, Dictionary<string, string> wheres)
        {
            //변경된 값만 저장여부를 확인할 것이므로 기존 값을 모두 가져온다
            var SQL = "select  top 1 " + string.Join(",", columns.Select(t => "isnull([" + t.Key + "],'') as " + t.Key + "")) +
                " from K4EE_Component_Reel_SID_Information WITH(NOLOCK)";

            var WSQL = $" where MC='{PUB.MCCode}'";
            for (int i = 0; i < wheres.Count; i++)
            {
                var col = wheres.ElementAt(i);
                var colname = col.Key;
                var colvalue = col.Value;
                WSQL += " AND ";
                WSQL += $" {colname}='{colvalue.Replace("'", "''")}'";
            }
            SQL += WSQL;

            Dictionary<String, string> UpdateTarget = new Dictionary<string, string>();
            var CN = new System.Data.SqlClient.SqlConnection();
            CN.ConnectionString = Properties.Settings.Default.CS;
            var CMD = new System.Data.SqlClient.SqlCommand(SQL, CN);
            CN.Open();
            var DAR = CMD.ExecuteReader();
            var NoData = true;
            Dictionary<String, string> InsertTarget = new Dictionary<string, string>();
            while (DAR.Read())
            {
                NoData = false;
                foreach (var col in columns)
                {
                    var vStr = DAR[col.Key].ToString();
                    var cStr = col.Value;
                    if (vStr.Equals(cStr) == false)
                    {
                        //differenct value
                        UpdateTarget.Add(col.Key, cStr);
                    }
                }
            }
            DAR.Close();
            //자료가 없다면 데이터를 추가한다.
            if (NoData)
            {
                foreach (var col in columns)
                {
                    InsertTarget.Add(col.Key, col.Value);
                }
                foreach (var item in wheres)
                {
                    if (InsertTarget.ContainsKey(item.Key) == false)
                        InsertTarget.Add(item.Key, item.Value);
                }
            }

            if (UpdateTarget.Count > 0) //if update target 
            {

                var dlgMsg = $"다음 값을 서버(SID정보)에 저장 하시겠습니까?\n";
                foreach (var item in UpdateTarget)
                    dlgMsg += $"Item:{item.Key} => {item.Value}\n";

                var dlg = UTIL.MsgQ(dlgMsg);
                if (dlg == DialogResult.Yes)
                {

                    //check double data 220706
                    var CSQL = "select count(*) from K4EE_Component_Reel_SID_Information WITH(NOLOCK) ";
                    CSQL += WSQL;
                    CMD.CommandText = CSQL;
                    var cnt = int.Parse(CMD.ExecuteScalar().ToString());
                    var whke = string.Join(",", wheres.Select(t => t.Key).ToList());
                    if (cnt < 1)
                    {
                        PUB.log.AddAT("SQL=" + CSQL);
                        UTIL.MsgE($"Cannot update information because there is no target reel information\n" + whke);
                    }
                    else if (cnt > 1)
                    {

                        PUB.log.AddAT("SQL=" + CSQL);
                        UTIL.MsgE($"Multiple target reel information({cnt} records) exists, cannot update information\n" + whke);
                    }
                    else
                    {
                        var USQL = $"update K4EE_Component_Reel_SID_Information set [MC]='{PUB.MCCode}'," +
                        string.Join(",", UpdateTarget.Select(t => "[" + t.Key + "]='" + t.Value + "'"));

                        USQL += WSQL;
                        try
                        {
                            CMD.CommandText = USQL;
                            var UpdateOK = CMD.ExecuteNonQuery() == 1;
                            if (UpdateOK == false)
                            {
                                UTIL.MsgE("Save Error");
                            }
                        }
                        catch (Exception ex)
                        {
                            UTIL.MsgE("Save Error\n" + ex.Message);
                        }
                    }
                }
            }
            if (InsertTarget.Count > 0)
            {

                var dlgMsg = $"다음 값을 서버에 저장 하시겠습니까?\n";
                foreach (var item in InsertTarget)
                    dlgMsg += $"Item:{item.Key} => {item.Value}\n";

                var dlg = UTIL.MsgQ(dlgMsg);
                if (dlg == DialogResult.Yes)
                {
                    var ISQL = $"insert into K4EE_Component_Reel_SID_Information ([MC],wdate," +
                        string.Join(",", InsertTarget.Select(t => "[" + t.Key + "]")) + ") values(" +
                        $"'{PUB.MCCode}',getdate()," +
                        string.Join(",", InsertTarget.Select(t => "'" + t.Value.Replace("'", "''") + "'")) + ")";

                    //ISQL += WSQL;
                    try
                    {
                        CMD.CommandText = ISQL;
                        var UpdateOK = CMD.ExecuteNonQuery() == 1;
                        if (UpdateOK == false)
                        {
                            UTIL.MsgE("Save Error");
                        }
                    }
                    catch (Exception ex)
                    {
                        UTIL.MsgE("Save Error\n" + ex.Message);
                    }
                }

            }
            CN.Close();
            CN.Dispose();
        }

        /// <summary>
        /// 지정한 자료를 서버에 기록합니다. 조건절과 대상 열을 제공해야합니다
        /// </summary>
        void ServerWriteINF_EED(Dictionary<string, string> columns, Dictionary<string, string> wheres)
        {
            //변경된 값만 저장여부를 확인할 것이므로 기존 값을 모두 가져온다
            var SQL = "select  top 1 " + string.Join(",", columns.Select(t => "isnull([" + t.Key + "],'') as " + t.Key + "")) +
                " from K4EE_Component_Reel_SID_Information WITH(NOLOCK)";

            var WSQL = $" where MC='{PUB.MCCode}'";
            for (int i = 0; i < wheres.Count; i++)
            {
                var col = wheres.ElementAt(i);
                var colname = col.Key;
                var colvalue = col.Value;
                WSQL += " AND ";
                WSQL += $" {colname}='{colvalue.Replace("'", "''")}'";
            }
            SQL += WSQL;

            Dictionary<String, string> UpdateTarget = new Dictionary<string, string>();
            var CN = new System.Data.SqlClient.SqlConnection();
            CN.ConnectionString = Properties.Settings.Default.CS;
            var CMD = new System.Data.SqlClient.SqlCommand(SQL, CN);
            CN.Open();
            var DAR = CMD.ExecuteReader();
            var NoData = true;
            Dictionary<String, string> InsertTarget = new Dictionary<string, string>();
            while (DAR.Read())
            {
                NoData = false;
                foreach (var col in columns)
                {
                    var vStr = DAR[col.Key].ToString();
                    var cStr = col.Value;
                    if (vStr.Equals(cStr) == false)
                    {
                        //differenct value
                        UpdateTarget.Add(col.Key, cStr);
                    }
                }
            }
            DAR.Close();
            //자료가 없다면 데이터를 추가한다.
            if (NoData)
            {
                foreach (var col in columns)
                {
                    InsertTarget.Add(col.Key, col.Value);
                }
                foreach (var item in wheres)
                {
                    if (InsertTarget.ContainsKey(item.Key) == false)
                        InsertTarget.Add(item.Key, item.Value);
                }
            }

            if (UpdateTarget.Count > 0) //if update target 
            {
                var dlgMsg = $"다음 값을 EED서버(SID정보)에 저장 하시겠습니까?\n";
                foreach (var item in UpdateTarget)
                    dlgMsg += $"Item:{item.Key} => {item.Value}\n";

                var dlg = UTIL.MsgQ(dlgMsg);
                if (dlg == DialogResult.Yes)
                {
                    //check double data 220706
                    var CSQL = "select count(*) from K4EE_Component_Reel_SID_Information WITH(NOLOCK) ";
                    CSQL += WSQL;
                    CMD.CommandText = CSQL;
                    var cnt = int.Parse(CMD.ExecuteScalar().ToString());
                    var whke = string.Join(",", wheres.Select(t => t.Key).ToList());
                    if (cnt < 1)
                    {
                        PUB.log.AddAT("SQL=" + CSQL);
                        UTIL.MsgE($"Cannot update information because there is no target reel information\n" + whke);
                    }
                    else if (cnt > 1)
                    {

                        PUB.log.AddAT("SQL=" + CSQL);
                        UTIL.MsgE($"Multiple target reel information({cnt} records) exists, cannot update information\n" + whke);
                    }
                    else
                    {
                        var USQL = $"update K4EE_Component_Reel_SID_Information set [MC]='{PUB.MCCode}'," +
                        string.Join(",", UpdateTarget.Select(t => "[" + t.Key + "]='" + t.Value + "'"));

                        USQL += WSQL;
                        try
                        {
                            CMD.CommandText = USQL;
                            var UpdateOK = CMD.ExecuteNonQuery() == 1;
                            if (UpdateOK == false)
                            {
                                UTIL.MsgE("Save Error");
                            }
                        }
                        catch (Exception ex)
                        {
                            UTIL.MsgE("Save Error\n" + ex.Message);
                        }
                    }
                }
            }
            if (InsertTarget.Count > 0)
            {
                var dlgMsg = $"다음 값을 EED서버에 저장 하시겠습니까?\n";
                foreach (var item in InsertTarget)
                    dlgMsg += $"Item:{item.Key} => {item.Value}\n";

                var dlg = UTIL.MsgQ(dlgMsg);
                if (dlg == DialogResult.Yes)
                {
                    var ISQL = $"insert into K4EE_Component_Reel_SID_Information ([MC],wdate," +
                        string.Join(",", InsertTarget.Select(t => "[" + t.Key + "]")) + ") values(" +
                        $"'{PUB.MCCode}',getdate()," +
                        string.Join(",", InsertTarget.Select(t => "'" + t.Value.Replace("'", "''") + "'")) + ")";

                    //ISQL += WSQL;
                    try
                    {
                        CMD.CommandText = ISQL;
                        var UpdateOK = CMD.ExecuteNonQuery() == 1;
                        if (UpdateOK == false)
                        {
                            UTIL.MsgE("Save(EED) Error");
                        }
                    }
                    catch (Exception ex)
                    {
                        UTIL.MsgE("Save(EED) Error\n" + ex.Message);
                    }
                }

            }
            CN.Close();
            CN.Dispose();
        }
        /// <summary>
        /// 지정한 자료를 서버에 기록합니다. 조건절과 대상 열을 제공해야합니다
        /// </summary>
        void ServerWriteCNV(Dictionary<string, string> columns, Dictionary<string, string> wheres)
        {
            //변경된 값만 저장여부를 확인할 것이므로 기존 값을 모두 가져온다
            var tableName = "K4EE_Component_Reel_SID_Convert";
            var SQL = "select  top 1 " + string.Join(",", columns.Select(t => "isnull([" + t.Key + "],'') as " + t.Key + "")) +
                $" from {tableName} WITH(NOLOCK) ";

            var WSQL = $" where isnull(MC,'{PUB.MCCode}')='{PUB.MCCode}'";
            for (int i = 0; i < wheres.Count; i++)
            {
                var col = wheres.ElementAt(i);
                var colname = col.Key;
                var colvalue = col.Value;
                WSQL += " AND ";
                WSQL += $" {colname}='{colvalue.Replace("'", "''")}'";
            }
            SQL += WSQL;

            Dictionary<String, string> UpdateTarget = new Dictionary<string, string>();
            var CN = new System.Data.SqlClient.SqlConnection();
            CN.ConnectionString = Properties.Settings.Default.CS;
            var CMD = new System.Data.SqlClient.SqlCommand(SQL, CN);
            CN.Open();
            var DAR = CMD.ExecuteReader();
            var NoData = true;
            Dictionary<String, string> InsertTarget = new Dictionary<string, string>();
            while (DAR.Read())
            {
                NoData = false;
                foreach (var col in columns)
                {
                    var vStr = DAR[col.Key].ToString();
                    var cStr = col.Value;
                    if (vStr.Equals(cStr) == false)
                    {
                        //differenct value
                        UpdateTarget.Add(col.Key, cStr);
                    }
                }
            }
            DAR.Close();

            //자료가 없다면 데이터를 추가한다.
            if (NoData)
            {
                foreach (var col in columns)
                {
                    InsertTarget.Add(col.Key, col.Value);
                }
                foreach (var item in wheres)
                {
                    if (InsertTarget.ContainsKey(item.Key) == false)
                        InsertTarget.Add(item.Key, item.Value);
                }
            }

            if (UpdateTarget.Count > 0) //if update target 
            {

                var dlgMsg = $"다음 SID변환값을 서버에 업데이트 하시겠습니까?\n";
                foreach (var item in UpdateTarget)
                    dlgMsg += $"Item:{item.Key} => {item.Value}\n";

                var dlg = UTIL.MsgQ(dlgMsg);
                if (dlg == DialogResult.Yes)
                {

                    //check double data 220706
                    var CSQL = $"select count(*) from {tableName}";
                    CSQL += WSQL;
                    CMD.CommandText = CSQL;
                    var cnt = int.Parse(CMD.ExecuteScalar().ToString());
                    var whke = string.Join(",", wheres.Select(t => t.Key).ToList());
                    if (cnt < 1)
                    {
                        PUB.log.AddAT("SQL=" + CSQL);
                        UTIL.MsgE($"No target reel information exists, cannot update conversion information\n" + whke);
                    }
                    else if (cnt > 1)
                    {

                        PUB.log.AddAT("SQL=" + CSQL);
                        UTIL.MsgE($"Multiple target reel conversion information({cnt} records) exists, cannot update information\n" + whke);
                    }
                    else
                    {
                        var USQL = $"update {tableName} set isnull([MC],'{PUB.MCCode}')='{PUB.MCCode}'," +
                        string.Join(",", UpdateTarget.Select(t => "[" + t.Key + "]='" + t.Value + "'"));

                        USQL += WSQL;
                        try
                        {
                            CMD.CommandText = USQL;
                            var UpdateOK = CMD.ExecuteNonQuery() == 1;
                            if (UpdateOK == false)
                            {
                                UTIL.MsgE("(CNV)Save Error");
                            }
                        }
                        catch (Exception ex)
                        {
                            UTIL.MsgE("(CNV)Save Error\n" + ex.Message);
                        }
                    }
                }
            }
            if (InsertTarget.Count > 0)
            {

                var dlgMsg = $"다음 변환값을 서버에 추가 하시겠습니까?\n";
                foreach (var item in InsertTarget)
                    dlgMsg += $"Item:{item.Key} => {item.Value}\n";


                var dlg = UTIL.MsgQ(dlgMsg);
                if (dlg == DialogResult.Yes)
                {
                    var ISQL = $"insert into {tableName} ([MC]," +
                        string.Join(",", InsertTarget.Select(t => "[" + t.Key + "]")) + ") values(" +
                        $"'{PUB.MCCode}'," +
                        string.Join(",", InsertTarget.Select(t => "'" + t.Value.Replace("'", "''") + "'")) + ")";

                    //ISQL += WSQL;
                    try
                    {
                        CMD.CommandText = ISQL;
                        var UpdateOK = CMD.ExecuteNonQuery() == 1;
                        if (UpdateOK == false)
                        {
                            UTIL.MsgE("Save(CNV) Error");
                        }
                    }
                    catch (Exception ex)
                    {
                        UTIL.MsgE("Save(CNV) Error\n" + ex.Message);
                    }
                }

            }
            CN.Close();
            CN.Dispose();

            if (UpdateTarget.Any() || InsertTarget.Any())
            {
                PUB.GetSIDConverDB();
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            if (tbPart.Text.isEmpty()) tbPart.Text = "N/A";
            else
            {
                var dlg = UTIL.MsgQ("Would you like to change the current Part No value to N/A?");
                if (dlg == DialogResult.Yes) tbPart.Text = "N/A";
            }
        }



        private void button5_Click_2(object sender, EventArgs e)
        {
            if (tbVName.Text.isEmpty()) tbVName.Text = "N/A";
            else
            {
                var dlg = UTIL.MsgQ("Would you like to change the current VenderName value to N/A?");
                if (dlg == DialogResult.Yes) tbVName.Text = "N/A";
            }
        }

        private void lnkBatch_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UTIL.TouchKeyShow(tbBatch, "INPUT BATCH");
        }

        void ValueUpdate(TextBox tb, string value, string colname)
        {
            var tagstring = tb.Tag?.ToString() ?? string.Empty;
            if (value.isEmpty() == false)
            {
                tb.Tag = tb.Text;
                tb.Text = value;
            }
            //else if (tagstring.isEmpty() == false && value.isEmpty() == false && tb.Text != value)
            //{
            //    //한번설정된 값인데 다른 값을 선택했다
            //    if (UTIL.MsgQ($"{colname} 값을 변경할까요?\n{tb.Text} -> {value}") == DialogResult.Yes)
            //    {
            //        tb.Text = value;
            //    }
                    
            //}
        }


        private void vW_GET_MAX_QTY_VENDOR_LOTDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var col = this.dv1.Columns[e.ColumnIndex];
            if (col.DataPropertyName.Equals("SID") == false) return;
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsWMS.VW_GET_MAX_QTY_VENDOR_LOTRow;
            if (dr == null) return;

            var dlg = UTIL.MsgQ("Would you like to enter the values of the selected items?\nEmpty values will be entered automatically and user confirmation will be required for existing values");
            if (dlg != DialogResult.Yes) return;

            //SID값은 반드시 있다
            ValueUpdate(tbSID, dr.SID, "SID");
            ValueUpdate(tbLot, dr.VENDOR_LOT, "LOT");
            ValueUpdate(tbPart, dr.PART_NO, "PARTNO");
            ValueUpdate(TbCustCode, dr.CUST_CODE, "CUST_CODE");
            ValueUpdate(tbVName, dr.VENDOR_NM, "VENDER_NM");
            ValueUpdate(tbMFG, dr.MFG_DATE, "MFG_DATE");
            ValueUpdate(tbBatch, dr.BATCH_NO, "BATCH_NO");
        }
    }
}