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 System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using FCOMMON;

namespace FEQ0000
{
    public partial class fEquipment : fBase
    {
        public enum eTabletype
        {
            ALL,
            //MOLD,
            //FOL,
            //BUMP,
            //ING,
            //OTHER
        }
        string tableName = string.Empty;
        eTabletype dataType = eTabletype.ALL;

        public fEquipment(eTabletype type_)
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = FCOMMON.info.CS;

            dataType = type_;

            this.tbSearch.KeyDown += (s1, e1) => { 
                if(e1.KeyCode == Keys.Enter)
                {
                    btRefresh.PerformClick();
                }
            };
            //if (dataType == eTabletype.MOLD)
            //{

            //    tableName = "EquipmentME";
            //    this.dsEQ.EquipmentME.TableNewRow += Equipment_TableNewRow;
            //    dvc_param.Visible = false;
            //}
            //else if (dataType == eTabletype.FOL)
            //{

            //    tableName = "EquipmentF";
            //    this.dsEQ.EquipmentF.TableNewRow += Equipment_TableNewRow;
            //    dvc_param.Visible = false;
            //}
            //else if (dataType == eTabletype.ING)
            //{

            //    tableName = "EETGW_EquipmentIng";
            //    this.dsEQ.EETGW_EquipmentIng.TableNewRow += Equipment_TableNewRow;
            //    dvc_param.Visible = false;
            //}
            //else if (dataType == eTabletype.OTHER)
            //{

            //    tableName = "EETGW_EquipmentOther";
            //    this.dsEQ.EETGW_EquipmentOther.TableNewRow += Equipment_TableNewRow;
            //    dvc_param.Visible = false;
            //}
            //else
            //if (dataType == eTabletype.ALL)
            //{

                tableName = "EETGW_Equipment";
                //this.dsEQ.EETGW_EquipmentOther.TableNewRow += Equipment_TableNewRow;
                dvc_param.Visible = false;
                panel1.Visible = true; //필터창보이게
            //}
            //else
            //{

            //    tableName = "EquipmentB";
            //    //this.dsEQ.EquipmentB.TableNewRow += Equipment_TableNewRow;
            //    dvc_param.Visible = true;
            //}
            this.FormClosed += fEquipment_FormClosed;

        }

        void fEquipment_FormClosed(object sender, FormClosedEventArgs e)
        {
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name + this.tableName, false);
        }

        void RefreshDate()
        {
            //등록된 날짜 목록을 가져온다.
            var taDateList = new dsEQTableAdapters.EqDateListTableAdapter();
            DataTable dtList = null;

            if (dataType == eTabletype.ALL) dtList = taDateList.GetData(FCOMMON.info.Login.gcode);
            else dtList = taDateList.GetData(FCOMMON.info.Login.gcode);

            this.cmbDate.Items.Clear();
            if (dtList != null)
            {
                foreach (DataRow dr in dtList.Rows)
                {
                    this.cmbDate.Items.Add(dr["pdate"].ToString());
                }
            }
            if (this.cmbDate.Items.Count > 0) this.cmbDate.SelectedIndex = 0;
        }
     
        private void __Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            this.Text = string.Format("Equipment List({0})", this.dataType);
            var form = this as Form;
            FCOMMON.Util.SetFormStatus(ref form, this.Name + this.tableName, true);
            this.Show();
            Application.DoEvents();

            RefreshDate();

            //목록을 가져온다.
            var tlList = DatabaseManager.getEQGroupLiist("linet +'-' + linep ", this.tableName);
            var lcList = DatabaseManager.getEQGroupLiist("linecode", this.tableName);
            var manuList = DatabaseManager.getEQGroupLiist("manu", this.tableName);
            var typeList = DatabaseManager.getEQGroupLiist("type", this.tableName);
            var plantList = DatabaseManager.getEQGroupLiist("plant", this.tableName);
            //var grp2List = DatabaseManager.getEQGroupLiist("grp2", this.tableName);

            cbTeamPart.Items.Add("-- All --");
            cmbLine.Items.Add("-- All --");
            cmbManu.Items.Add("-- All --");
            cmbType.Items.Add("-- All --");
            cmbPlant.Items.Add("-- All --");
            // cmbCate.Items.Add("-- All --");

            foreach (var item in tlList) this.cbTeamPart.Items.Add(item);
            foreach (var item in lcList) this.cmbLine.Items.Add(item);
            foreach (var item in manuList) this.cmbManu.Items.Add(item);
            foreach (var item in typeList) this.cmbType.Items.Add(item);
            foreach (var item in plantList) this.cmbPlant.Items.Add(item);
            // foreach (var item in grp2List) this.cmbCate.Items.Add(item);

            if (this.cbTeamPart.Items.Count > 0) cbTeamPart.SelectedIndex = 0;
            if (this.cmbLine.Items.Count > 0) cmbLine.SelectedIndex = 0;
            if (this.cmbManu.Items.Count > 0) cmbManu.SelectedIndex = 0;
            if (this.cmbType.Items.Count > 0) cmbType.SelectedIndex = 0;
            if (this.cmbPlant.Items.Count > 0) cmbPlant.SelectedIndex = 0;
            //if (this.cmbCate.Items.Count > 0) cmbCate.SelectedIndex = 0;

            //if (this.dataType == eTabletype.ING)
            //    dvc_param.HeaderText = "RCS Flag";
            //else
            dvc_param.HeaderText = "Wafer Size";

        }

        private void equipmentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsAll.EndEdit();

            try
            {
                taAll.Update(this.dsEQ.EETGW_Equipment);
                this.dsEQ.AcceptChanges();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }
        }


        void Equipment_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
        }


        private int applyFilter(string filter, string apply)
        {
            if (filter.isEmpty() || apply.isEmpty()) return -1;

            try
            {
                DataRow[] dRows = null;
                dRows = this.dsEQ.EETGW_Equipment.Select(filter);

                int cnt = 0;
                foreach (DataRow dr in dRows)
                {
                    var appList = apply.Split(';');
                    foreach (var item in appList)
                    {
                        if (item.isEmpty()) continue;
                        var field = item.Split('=')[0].Trim();
                        var value = item.Split('=')[1].Trim();
                        dr[field] = value;
                    }
                    cnt += 1;
                }
                //this.bsB.Filter = filter;
                //Util.MsgI(string.Format("{0} 건의 자료가 업데이트 되었습니다.",cnt));
                return cnt;
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
                return -1;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                string key = tbFilter.Text.Trim();
                string filter = "";
                if (!key.isEmpty())
                {
                    filter = "asset like @ or type like @ or manu like @ or model like @ or linecode like @  or serial like @";
                    filter = filter.Replace("@", "'%" + key.Replace("'", "''") + "%'");
                }
                try
                {
                    this.bsAll.Filter = filter;

                    if (key.isEmpty()) this.tbFilter.BackColor = Color.White;
                    else this.tbFilter.BackColor = Color.Lime;
                }
                catch (Exception ex)
                {
                    tbFilter.BackColor = Color.HotPink;
                    FCOMMON.Util.MsgE("filter error\n" + ex.Message);
                }
                tbFilter.Focus();
                tbFilter.SelectAll();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }

        }


        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (this.dsEQ.EETGW_Equipment.Count < 1)
            {
                FCOMMON.Util.MsgE("자료가 없습니다. 자료를 조회하고 시도하세요");
                return;
            }
            var f = new rpt_equipmentAll(this.dsEQ.EETGW_Equipment, "Equipment");
            f.Show();

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            var f = new fImpEquipment(dataType);
            f.ShowDialog();
            RefreshDate();
        }

        //string grp2name = string.Empty;
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (cmbDate.SelectedIndex < 0)
            {
                FCOMMON.Util.MsgE("No Date");
                return;
            }


            // this.grp2name = this.cmbCate.Text;


            //select query
            string newSQL = "select * from {0}";
            string newWhere = "pdate = '{1}'";
            if (cbTeamPart.SelectedIndex != 0 && !cbTeamPart.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += "linet +'-' + linep ='" + cbTeamPart.Text + "'";
            }
            if (this.cmbManu.SelectedIndex != 0 && !cmbManu.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += "manu='" + cmbManu.Text + "'";
            }
            if (this.cmbLine.SelectedIndex != 0 && !cmbLine.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += "linecode='" + cmbLine.Text + "'";
            }
            if (this.cmbType.SelectedIndex != 0 && !cmbType.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";

                var lists = cmbType.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if(lists.Length == 1)
                    newWhere += "[type]='" + cmbType.Text + "'";
                else
                {
                    newWhere += "[type] in ('" + string.Join("','", lists) + "')";
                }
            }
            if (!this.tbSearch.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += string.Format("(asset like '%{0}%' or type like '%{0}%' or manu like '%{0}%' or model like '%{0}%' or linet like '%{0}%' or linep like '%{0}%' or linecode like '%{0}%' or serial like '%{0}%')", tbSearch.Text);
            }
            if (this.cmbPlant.SelectedIndex > 0 && !this.cmbPlant.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += "[plant]='" + cmbPlant.Text + "'";
            }

            if (radexpn.Checked)
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += string.Format("isnull([except],0) = 0");
            }
            if (radexpy.Checked)
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += string.Format("isnull([except],0) = 1");
            }
            if (radioButton1.Checked) //yes
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += string.Format("isnull([ing],0) = 1");
            }
            if (radioButton3.Checked) //no
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += string.Format("isnull([ing],0) = 0");
            }

            string CommandText = newSQL;
            if (!newWhere.isEmpty()) CommandText += " where " + newWhere;



            CommandText = string.Format(CommandText, "EETGW_Equipment", this.cmbDate.Text);
            var cmd = new System.Data.SqlClient.SqlCommand(CommandText, this.taAll.Connection);
            var da = new System.Data.SqlClient.SqlDataAdapter(cmd);
            dsEQ.EETGW_Equipment.Clear();
            da.Fill(this.dsEQ.EETGW_Equipment);
            dsEQ.EETGW_Equipment.AcceptChanges();


            ////select command
            //if (this.taAll.Adapter.SelectCommand == null)
            //    this.taAll.Adapter.SelectCommand = new System.Data.SqlClient.SqlCommand();
            //this.taAll.Adapter.SelectCommand.CommandText = string.Format(CommandText, "EETGW_Equipment");
            //this.dsEQ.EETGW_Equipment.Clear();
            //taAll.Fill(this.dsEQ.EETGW_Equipment, this.cmbDate.Text);
            //this.dsEQ.EETGW_Equipment.AcceptChanges();
            dv.DataSource = bsAll;
            bn.BindingSource = bsAll;

        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            panel1.Visible = !panel1.Visible;
        }

        private void autosizeColumnsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.dv.AutoResizeColumns();
        }

        private void applyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new EQFilterApply("E");
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var dlg = FCOMMON.Util.MsgQ("매크로를 적용 하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;

                int cnt = 0;
                foreach (ListViewItem lvitem in f.listView1.CheckedItems)
                {
                    //filter =2 , apply=3l
                    var filter = lvitem.SubItems[2].Text;
                    var apply = lvitem.SubItems[3].Text;

                    cnt += applyFilter(filter, apply);
                }

                FCOMMON.Util.MsgI(string.Format("{0}건의 매크로를 적용했습니다", cnt));
            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            //var eqdiv = this.dataType == eTabletype.ING ? "I" : "E";
            var f = new EQfilterManager("E");
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var filter = f.filter;
                var apply = f.apply;
                if (filter.isEmpty() || apply.isEmpty())
                {
                    FCOMMON.Util.MsgE("no data");
                    return;
                }

                var dlg = FCOMMON.Util.MsgQ("다음 매크로를 적용 하시겠습니까?\nFilter:" + filter + "\n" +
                    "apply : " + apply);
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;

                var cnt = applyFilter(filter, apply);
                if (cnt == -1) FCOMMON.Util.MsgE("오류로 인해 실행되지 않았습니다.");
                else FCOMMON.Util.MsgI(cnt.ToString() + "건의 자료가 변경되었습니다.");
            }
        }

        private void tbFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void 장비모델생성공통07ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cn1 = FCOMMON.DBM.getCn();
            var cn2 = FCOMMON.DBM.getCn();
            cn1.Open();
            cn2.Open();

            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("", cn1);
            System.Data.SqlClient.SqlCommand cmd2 = new System.Data.SqlClient.SqlCommand("", cn2);


            cmd.CommandText = "select * from common where grp ='07' and svalue <> '' and isnull(code,'') = ''";
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                string manu = rdr["svalue"].ToString();
                cmd2.CommandText = "select code from common where grp ='06' and memo='" + manu + "'";
                var manu_data = cmd2.ExecuteScalar();
                if (manu_data == null) continue;

                var manu_code = manu_data.ToString();

                cmd2.CommandText = "update common set code = '" + manu_code + "'  where grp = '07' and isnull(code,'') = '' and svalue = '" + manu + "'";
                cmd2.ExecuteNonQuery();
            }


            cmd.Dispose();
            cn1.Close();
            cn2.Close();
            cn1.Dispose();
            cn2.Dispose();

            FCOMMON.Util.MsgI("ok");
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("Plant 정보를 서버의 정보로 변경 할까요?");
            if (dlg != DialogResult.Yes) return;

            this.prb1.Minimum = 0;
            this.prb1.Value = 0;


            var ucnt = 0;
            var taLIne = new dsEQTableAdapters.LineCodeTableAdapter();
            var dtLineCode = taLIne.GetData(FCOMMON.info.Login.gcode);


            this.prb1.Maximum = this.dsEQ.EETGW_Equipment.Count;
            foreach (dsEQ.EETGW_EquipmentRow dr in this.dsEQ.EETGW_Equipment)
            {
                if (this.prb1.Value < this.prb1.Maximum) this.prb1.Value += 1;
                if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached) continue;
                var linedata = dtLineCode.Where(t => t.code == dr.linecode).FirstOrDefault();
                if (linedata != null)
                {
                    if (dr.grp2 != linedata.grp2 || dr.lineP != linedata.part || dr.lineT != linedata.team || dr.plant != linedata.plant)
                    {
                        //dr.lineP = linedata.part;
                        //dr.lineT = linedata.team;
                        dr.plant = linedata.plant;
                        //dr.grp2 = linedata.grp2;
                        dr.EndEdit();
                        ucnt += 1;
                    }
                }
            }
            FCOMMON.Util.MsgI($"{ucnt} 건의 자료가 변경 되었습니다. 적용하려면 '저장' 버튼을 누르세요");
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var list = new List<string>();
            foreach (string item in cmbType.Items)
            {
                if (item.StartsWith("--")) continue;
                if (string.IsNullOrEmpty(item) == false) list.Add(item);
            }

            var curlist = new string[] { };
            if(cmbType.Text.StartsWith("--")==false && cmbType.Text.Length > 0) //뭔가 선택했다
            {
                curlist  = cmbType.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }

            var f = new FCOMMON.fSelectProcess(list.ToArray(),curlist);
            if (f.ShowDialog() == DialogResult.OK)
            {
                this.cmbType.Text = string.Join(",", f.values);
                btRefresh.PerformClick();
            }
        }

        private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {

        }
    }
}

