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;

namespace FEQ0000
{
    public partial class fEquipment : Form
    {
        public enum eTabletype
        {
            MOLD,
            FOL,
            BUMP
        }
        string tableName = string.Empty;
        eTabletype dataType = eTabletype.FOL;

        public fEquipment(eTabletype type_)
        {
            InitializeComponent();
            dataType = type_;
            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
            {

                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.BUMP) dtList = taDateList.GetDateListB();
            else if (dataType == eTabletype.FOL) dtList = taDateList.GetDateListF();
            else dtList = taDateList.GetDateListME();

            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)
        {
            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 grpList = DatabaseManager.getEQGroupLiist("grp", this.tableName);
            var lcList = DatabaseManager.getEQGroupLiist("linecode", this.tableName);
            var manuList = DatabaseManager.getEQGroupLiist("manu", this.tableName);
            var typeList = DatabaseManager.getEQGroupLiist("type", this.tableName);

            cmbGrp.Items.Add("-- All --");
            cmbLine.Items.Add("-- All --");
            cmbManu.Items.Add("-- All --");
            cmbType.Items.Add("-- All --");

            foreach (var item in grpList) this.cmbGrp.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);

            if (this.cmbGrp.Items.Count > 0) cmbGrp.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;

        }

        private void equipmentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bsB.EndEdit();
            this.bsF.EndEdit();
            this.bsME.EndEdit();
            try
            {
                if (dataType == eTabletype.BUMP)
                {
                    this.taB.Update(this.dsEQ.EquipmentB);
                }
                else if (dataType == eTabletype.MOLD)
                {
                    this.taME.Update(this.dsEQ.EquipmentME);
                }
                else
                {
                    this.taF.Update(this.dsEQ.EquipmentF);
                }
                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;
                if (dataType == eTabletype.BUMP) dRows = this.dsEQ.EquipmentB.Select(filter);
                else if (dataType == eTabletype.MOLD) dRows = this.dsEQ.EquipmentME.Select(filter);
                else dRows = this.dsEQ.EquipmentF.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
                {
                    if (dataType == eTabletype.MOLD) this.bsME.Filter = filter;
                    else if (dataType == eTabletype.BUMP) this.bsB.Filter = filter;
                    else this.bsF.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)
        {
            var f = new rpt_equipmentB(dataType, this.cmbDate.Text);
            f.Show();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {

        }

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

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



            //select query
            string newSQL = "select * from {0}";
            string newWhere = string.Empty;
            if (cmbGrp.SelectedIndex != 0 && !cmbGrp.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += "grp='" + cmbGrp.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 ";
                newWhere += "[type]='" + cmbType.Text + "'";
            }
            if (!this.tbSearch.Text.isEmpty())
            {
                if (!newWhere.isEmpty()) newWhere += " and ";
                newWhere += string.Format("(asset like '%{0}%' or model like '%{0}%' or serial like '%{0}%')", tbSearch.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");
            }


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

            switch (dataType)
            {
                case eTabletype.MOLD:
                    //select command
                    if (this.taME.Adapter.SelectCommand == null)
                        this.taME.Adapter.SelectCommand = new System.Data.SqlClient.SqlCommand();
                    this.taME.Adapter.SelectCommand.CommandText = string.Format(CommandText, "equipmentME");
                    this.dsEQ.EquipmentME.Clear();
                    taME.Fill(this.dsEQ.EquipmentME, this.cmbDate.Text);
                    this.dsEQ.EquipmentME.AcceptChanges();
                    dv.DataSource = bsME;
                    bn.BindingSource = bsME;
                    break;
                case eTabletype.BUMP:
                    //select command
                    if (this.taB.Adapter.SelectCommand == null)
                        this.taB.Adapter.SelectCommand = new System.Data.SqlClient.SqlCommand();
                    this.taB.Adapter.SelectCommand.CommandText = string.Format(CommandText, "equipmentB");
                    this.dsEQ.EquipmentB.Clear();
                    taB.Fill(this.dsEQ.EquipmentB, this.cmbDate.Text);
                    this.dsEQ.EquipmentB.AcceptChanges();
                    dv.DataSource = bsB;
                    bn.BindingSource = bsB;
                    break;
                case eTabletype.FOL:
                    //select command
                    if (this.taF.Adapter.SelectCommand == null)
                        this.taF.Adapter.SelectCommand = new System.Data.SqlClient.SqlCommand();
                    this.taF.Adapter.SelectCommand.CommandText = string.Format(CommandText, "equipmentF");
                    this.dsEQ.EquipmentF.Clear();
                    taF.Fill(this.dsEQ.EquipmentF, this.cmbDate.Text);
                    this.dsEQ.EquipmentF.AcceptChanges();
                    dv.DataSource = bsF;
                    bn.BindingSource = bsF;
                    break;
            }

        }

        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(dataType);
            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 f = new EQfilterManager(this.tableName);
            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");
        }
    }
}

