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;

namespace SIDConvInfoEditorII
{
    public partial class fMain : Form
    {
        public fMain()
        {
            InitializeComponent();
            PUB.init();
            this.dataSet1.K4EE_Component_Reel_SID_Information.TableNewRow += Component_Reel_SID_Information_TableNewRow;
            this.FormClosed += FSIDInformation_FormClosed;
            this.Text = $"{Application.ProductName} v{Application.ProductVersion}";
            this.dvC.DataError += DvC_DataError;
            this.dvI.DataError += DvC_DataError;
            this.dvP.DataError += DvC_DataError;
            this.tbFindWMS.KeyDown += (s1, e1) => {
                if (e1.KeyCode == Keys.Enter)
                    btFindWMS.PerformClick();
            };
        }

        private void DvC_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void FSIDInformation_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void Component_Reel_SID_Information_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["MC"] = PUB.setting.McName;
            e.Row["wdate"] = DateTime.Now;
        }

        private void component_Reel_SID_ConvertBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsC.EndEdit();
            this.taC.Update(this.dataSet1.K4EE_Component_Reel_SID_Convert);
            //this.tam.UpdateAll(this.dataSet1);

        }

        void SelectCombo()
        {
            if (cmbRCode.Items.Count == 1) cmbRCode.SelectedIndex = 0;
            else
            {
                for (int i = 0; i < this.cmbRCode.Items.Count; i++)
                {
                    if (cmbRCode.Items[i].ToString().StartsWith($"[{PUB.setting.McName}]"))
                    {
                        cmbRCode.SelectedIndex = i;
                        break;
                    }
                }
            }

        }
        private void fSIDInformation_Load(object sender, EventArgs e)
        {
            // TODO: 이 코드는 데이터를 'dSWms.VW_GET_MAX_QTY_VENDOR_LOT' 테이블에 로드합니다. 필요 시 이 코드를 이동하거나 제거할 수 있습니다.
            this.Show();
            Application.DoEvents();


            SelectCombo();
            if (cmbRCode.SelectedIndex >= 0)
            {
                Refresh_SidInfo();
                Refresh_SidConv();
                Refresh_SidPrintInfo();
                this.Refresh_WMS();
            }
            else
            {
                this.Show();
                Application.DoEvents();
                UTIL.MsgE("대상장비를 선택하세요");
            }

        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            //update sidconv
            Refresh_SidConv();
        }
        void Refresh_SidPrintInfo()
        {
            // TODO: 이 코드는 데이터를 'dataSet1.Component_Reel_SID_Convert' 테이블에 로드합니다. 필요 시 이 코드를 이동하거나 제거할 수 있습니다.
            this.taP.Fill(this.dataSet1.K4EE_Component_Reel_Print_Information, PUB.setting.McName);
            dvP.AutoResizeColumns();
            this.bnP.Enabled = true;
        }


        void Refresh_SidConv()
        {
            // TODO: 이 코드는 데이터를 'dataSet1.Component_Reel_SID_Convert' 테이블에 로드합니다. 필요 시 이 코드를 이동하거나 제거할 수 있습니다.
            this.taC.Fill(this.dataSet1.K4EE_Component_Reel_SID_Convert);//, PUB.setting.McName);
            dvC.AutoResizeColumns();
            this.bnC.Enabled = true;
        }
        void Refresh_WMS()
        {
            try
            {
                this.taWMS.Fill(this.dSWms.VW_GET_MAX_QTY_VENDOR_LOT);
            }
            catch (Exception ex)
            {
                AR.UTIL.MsgE(ex.Message);
            }
            dvWMS.AutoResizeColumns();


        }
        void Refresh_SidInfo()
        {
            // TODO: 이 코드는 데이터를 'dataSet1.Component_Reel_SID_Information' 테이블에 로드합니다. 필요 시 이 코드를 이동하거나 제거할 수 있습니다.
            this.taI.Fill(this.dataSet1.K4EE_Component_Reel_SID_Information, PUB.setting.McName);
            dvI.AutoResizeColumns();
            this.bnI.Enabled = true;
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            //update sidinfo
            this.Validate();
            this.bsI.EndEdit();
            this.bsC.EndEdit();
            if (this.dataSet1.K4EE_Component_Reel_SID_Information.GetChanges() != null)
            {
                if (UTIL.MsgQ("새로고침을 진행하면 변경된 자료가 손실됩니다\n실행할까요?") != DialogResult.Yes) return;
            }
            Refresh_SidInfo();
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {

            var sg = "엑셀 파일 포맷은 아래와 같아야 합니다\n" +
                "SID From | SID To | Remark\n" +
                "열번호가 일치하는 엑셀을 사용하시기 바랍니다";
            UTIL.MsgI(sg);

            //엑셀을 읽어와서 처리한다.
            var od = new OpenFileDialog();
            if (od.ShowDialog() != DialogResult.OK) return;
            libxl.Book book;
            var fi = new System.IO.FileInfo(od.FileName);
            var ext = fi.Extension.ToLower();
            if (ext == ".xlsx") book = new libxl.XmlBook();
            else if (ext == ".xls") book = new libxl.BinBook();
            else
            {
                UTIL.MsgE("지원되지 않는 파일 입니다");
                return;
            }

            var keyinfo = Properties.Settings.Default.libxl.Split('/');
            book.setKey(keyinfo[0], keyinfo[1]);
            book.load(fi.FullName);
            var sheet = book.getSheet(0);


            var cs = sheet.firstCol();
            var ce = sheet.lastCol();
            var rs = sheet.firstRow();
            var re = sheet.lastRow();

            this.progressBar1.Minimum = 0;
            this.progressBar1.Maximum = re;
            this.progressBar1.Value = 0;

            if (rs == 0) rs += 1;

            int cntA = 0;
            int cntU = 0;
            for (int row = rs; row <= re; row++)
            {
                if (this.progressBar1.Value < this.progressBar1.Maximum)
                    this.progressBar1.Value += 1;

                var cSidFrom = sheet.readStr(row, 0);
                var cSidTo = sheet.readStr(row, 1);
                var cRemark = sheet.readStr(row, 2);

                if (cSidFrom.isEmpty() || cSidTo.isEmpty() || cRemark.isEmpty()) continue;

                //if (cSID.isEmpty() && cCustCode.isEmpty()) break; //
                //if (cSID.StartsWith("10"))
                //{
                EnumerableRowCollection<DataSet1.K4EE_Component_Reel_SID_ConvertRow> plist = null;
                plist = this.dataSet1.K4EE_Component_Reel_SID_Convert.Where(t => t.SIDFrom == cSidFrom && t.SIDTo == cSidTo);

                if (plist == null || plist.Any() == false)
                {
                    //존재하지않으면 추가한다.
                    var newdr = this.dataSet1.K4EE_Component_Reel_SID_Convert.NewK4EE_Component_Reel_SID_ConvertRow();
                    newdr.MC = PUB.setting.McName;
                    newdr.SIDFrom = cSidFrom;
                    newdr.SIDTo = cSidTo;
                    newdr.Remark = cRemark;
                    newdr.Chk = true;
                    newdr.wdate = DateTime.Now;
                    this.dataSet1.K4EE_Component_Reel_SID_Convert.AddK4EE_Component_Reel_SID_ConvertRow(newdr);
                    cntA += 1;
                }
                else
                {
                    //있다면 업데이트 해준다.
                    //foreach (var item in plist)
                    //{
                    //	if (cSID.isEmpty() == false)
                    //	{
                    //		item.SID = cSID; ;
                    //		item.EndEdit();
                    //		cntU += 1;
                    //	}

                    //}
                }
                //}

            }
            UTIL.MsgI(string.Format("추가:{0},변경:{1}", cntA, cntU));
            dvC.AutoResizeColumns();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsI.EndEdit();
            this.bsC.EndEdit();

            var sb = new System.Text.StringBuilder();
            sb.AppendLine("가져오는 파일의 열 순서는 아래와 같습니다");
            sb.AppendLine("CUST# SID# PART# BATCH QTY VLOT");
            sb.AppendLine("가져온 순서가 맞지 않다면 엑셀파일의 열 데이터를 확인하세요");
            UTIL.MsgI(sb.ToString());

            //엑셀을 읽어와서 처리한다.
            var od = new OpenFileDialog();
            if (od.ShowDialog() != DialogResult.OK) return;
            libxl.Book book;
            var fi = new System.IO.FileInfo(od.FileName);
            var ext = fi.Extension.ToLower();
            if (ext == ".xlsx") book = new libxl.XmlBook();
            else if (ext == ".xls") book = new libxl.BinBook();
            else
            {
                UTIL.MsgE("지원되지 않는 파일 입니다");
                return;
            }

            var keyinfo = Properties.Settings.Default.libxl.Split('/');
            book.setKey(keyinfo[0], keyinfo[1]);
            book.load(fi.FullName);
            var sheet = book.getSheet(0);


            var cs = sheet.firstCol();
            var ce = sheet.lastCol();
            var rs = sheet.firstRow();
            var re = sheet.lastRow();

            this.progressBar1.Minimum = 0;
            this.progressBar1.Maximum = re;
            this.progressBar1.Value = 0;

            if (rs == 0) rs += 1;

            int cntA = 0;
            int cntU = 0;
            for (int row = rs; row <= re; row++)
            {
                if (this.progressBar1.Value < this.progressBar1.Maximum)
                    this.progressBar1.Value += 1;

                var cCustCode = sheet.readStr(row, 0);
                var cSID = sheet.readStr(row, 1);
                var cPartNo = sheet.readStr(row, 2);
                var batch = string.Empty;
                var qty = 0;
                var vLot = string.Empty;

                if (ce > 2) batch = sheet.readStr(row, 3);
                if (ce > 3)
                {
                    var ct = sheet.cellType(row, 4);
                    if (ct == libxl.CellType.CELLTYPE_NUMBER) qty = (int)sheet.readNum(row, 4);
                    if (ct == libxl.CellType.CELLTYPE_STRING)
                    {
                        var str = sheet.readStr(row, 4).Replace(",", "").Trim();
                        int.TryParse(str, out qty);
                    }
                }
                if (ce > 4) //221013  vlot 추가
                    vLot = sheet.readStr(row, 5);

                if (cCustCode.isEmpty() == false && cCustCode.Length != 4)
                    cCustCode = cCustCode.PadLeft(4, '0');
                if (cSID.isEmpty() && cCustCode.isEmpty()) break; //

                if (cSID.Length > 9)
                {
                    UTIL.MsgI($"다음 SID의 길이가 9자리를 초과하여 앞자리만 사용합니다\n\n" +
                        $"변경전 : {cSID}, 길이={cSID.Length}\n" +
                        $"변경후 : {cSID.Substring(0, 9)}, 길이=9");
                    cSID = cSID.Substring(0, 9);
                }


                //if (cSID.StartsWith("10"))
                //{
                EnumerableRowCollection<DataSet1.K4EE_Component_Reel_SID_InformationRow> plist = null;

                if (vLot.isEmpty() == false)
                    plist = this.dataSet1.K4EE_Component_Reel_SID_Information.Where(t => t.SID == cSID && t.CustCode == cCustCode && t.PartNo == cPartNo && t.VenderLot == vLot);
                else
                    plist = this.dataSet1.K4EE_Component_Reel_SID_Information.Where(t => t.SID == cSID && t.CustCode == cCustCode && t.PartNo == cPartNo);

                if (plist == null || plist.Any() == false)
                {
                    //존재하지않으면 추가한다.
                    var newdr = this.dataSet1.K4EE_Component_Reel_SID_Information.NewK4EE_Component_Reel_SID_InformationRow();
                    newdr.CustCode = cCustCode;
                    newdr.SID = cSID;
                    newdr.PartNo = cPartNo;
                    newdr.MC = PUB.setting.McName;
                    newdr.CustName = string.Empty;
                    newdr.batch = batch;
                    newdr.qtymax = qty;
                    newdr.VenderName = string.Empty;
                    newdr.VenderLot = vLot; //221013
                    newdr.Remark = string.Empty;
                    newdr.wdate = DateTime.Now;
                    this.dataSet1.K4EE_Component_Reel_SID_Information.AddK4EE_Component_Reel_SID_InformationRow(newdr);
                    cntA += 1;
                }
                else
                {
                    //있다면 업데이트 해준다.
                    //foreach (var item in plist)
                    //{
                    //	if (cSID.isEmpty() == false)
                    //	{
                    //		item.SID = cSID; ;
                    //		item.EndEdit();
                    //		cntU += 1;
                    //	}

                    //}
                }
                //}

            }
            UTIL.MsgI(string.Format("추가:{0},변경:{1}", cntA, cntU));
            dvI.AutoResizeColumns();
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsI.EndEdit();
            this.bsC.EndEdit();

            if (UTIL.MsgQ("현재 자료를 삭제 할까요?") != DialogResult.Yes) return;
            this.taI.DeleteMC(PUB.setting.McName);
            Refresh_SidInfo();
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("현재 자료를 삭제 할까요?") != DialogResult.Yes) return;
            dataSet1.K4EE_Component_Reel_SID_Convert.Clear();
            taC.DeleteAll();
            Refresh_SidConv();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsI.EndEdit();
            this.bsC.EndEdit();

            this.taI.Update(this.dataSet1.K4EE_Component_Reel_SID_Information);
        }

        private void cmbRCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //cmbRCode.Enabled = false;
            if (cmbRCode.SelectedIndex < 0) return;

            //업데이트 데이터 변경 감지
            var newmc = cmbRCode.Text.Substring(1, 2);
            if (PUB.setting.McName.Equals(newmc) == false)
            {
                //변경여부확인
                if (this.dataSet1.HasChanges())
                {
                    if (UTIL.MsgQ("변경된 자료가 있습니다. 대상장비를 변경할까요?\n현재 변경된 자료를 손실 됩니다") != DialogResult.Yes)
                    {
                        SelectCombo(); //다시 콤보를 선택해준다.
                        return;
                    }
                }

                PUB.setting.McName = cmbRCode.Text.Substring(1, 2);
                PUB.setting.Save();
                Refresh_SidInfo();
                Refresh_SidConv();
                Refresh_SidPrintInfo();

            }
            else
            {
                //같은자료이므로 처리하지 않는다.
            }

        }


        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            var tb = sender as TextBox;

            if (e.KeyCode == Keys.Enter)
            {
                FindText(tb);
            }
        }
        void FindText(TextBox tb)
        {
            var skey = tb.Text.Trim();
            if (skey.isEmpty())
            {
                bsI.Filter = string.Empty;
                tb.BackColor = Color.White;
            }
            else
            {
                List<string> cols = new List<string>();
                foreach (DataColumn col in this.dataSet1.K4EE_Component_Reel_SID_Information.Columns)
                {
                    if (col.ColumnName.ToString().ToUpper() == "IDX") continue;
                    if (col.ColumnName.ToString().ToUpper() == "WDATE") continue;
                    if (col.DataType == typeof(Int32)) continue;
                    if (col.DataType == typeof(Int16)) continue;
                    if (col.DataType == typeof(Guid)) continue;
                    cols.Add(col.ColumnName);
                }

                // liek like '' or
                var filter = string.Join($"  like '%{skey.Replace("'", "''")}%' or ", cols);
                filter += $"  like '%{skey.Replace("'", "''")}%'";
                try
                {
                    bsI.Filter = filter;
                    tb.BackColor = Color.Lime;
                }
                catch (Exception ex)
                {
                    UTIL.MsgE(ex.Message);
                    tb.BackColor = Color.Tomato;
                }

            }

            tb.SelectAll();
            tb.Focus();
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            var tb = sender as TextBox;

            if (e.KeyCode == Keys.Enter)
            {
                var skey = tb.Text.Trim();
                if (skey.isEmpty())
                {
                    bsC.Filter = string.Empty;
                    tb.BackColor = Color.White;
                }
                else
                {
                    List<string> cols = new List<string>();
                    foreach (DataColumn col in this.dataSet1.K4EE_Component_Reel_SID_Convert.Columns)
                    {
                        if (col.ColumnName.ToString().ToUpper() == "IDX") continue;
                        if (col.ColumnName.ToString().ToUpper() == "WDATE") continue;
                        cols.Add(col.ColumnName);
                    }

                    // liek like '' or
                    var filter = string.Join($"  like '%{skey.Replace("'", "''")}%' or ", cols);
                    filter += $"  like '%{skey.Replace("'", "''")}%'";
                    try
                    {
                        bsC.Filter = filter;
                        tb.BackColor = Color.Lime;
                    }
                    catch
                    {
                        tb.BackColor = Color.Tomato;
                    }

                }

                tb.SelectAll();
                tb.Focus();
            }
        }

        private void toolStripButton21_Click(object sender, EventArgs e)
        {
            //update sidconv
            Refresh_SidPrintInfo();
        }

        private void toolStripButton20_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsP.EndEdit();
            this.taP.Update(this.dataSet1.K4EE_Component_Reel_Print_Information);
            //this.tam.UpdateAll(this.dataSet1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var f = new Project.Dialog.fTouchKeyFull("검색", textBox1.Text);
            if (f.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = f.ValueString;
                FindText(textBox1);
            }
        }

        private void btFineWMS_Click(object sender, EventArgs e)
        {
            var search = tbFindWMS.Text.Trim();
            try
            {
                if(search.isEmpty())
                {
                    bsWMS.Filter = "";
                    tbFindWMS.BackColor = SystemColors.Control;
                }
                else
                {
                    tbFindWMS.BackColor = Color.HotPink;
                    var cols = new string[] { "SID", "PART_NO", "VENDOR_NM", "BATCH_NO", "CUST_CODE", "VENDOR_LOT" };
                    var filter = string.Join($" like '%{search}%' or ", cols) + $" like '%{search}%'";
                    bsWMS.Filter = filter;
                    tbFindWMS.BackColor = Color.Lime;
                }
            }
            catch (Exception ex)
            {
                bsWMS.Filter = "";
                tbFindWMS.BackColor = Color.HotPink;
            }
            tbFindWMS.Focus();
            tbFindWMS.SelectAll();
        }
    }
}
