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 System.IO;

using System.Xml.Linq;
using System.Data.SqlTypes;
using Microsoft.VisualBasic.Devices;
using AR;

namespace UniMarc
{
    public partial class Set_Macro : Form
    {
        Main main;
        Marc_Plan mp;
        Helper_DB db = new Helper_DB();
        DataGridView TargetGrid;
        string compidx = PUB.user.CompanyIdx;
        public string[] ViewMarcArray { get; set; }
        public string[] RunCode;

        public Set_Macro(Main _main)
        {
            InitializeComponent();
            main = _main;
        }

        public Set_Macro(Marc_Plan _mp, DataGridView mpGrid)
        {
            InitializeComponent();
            mp = _mp;
            TargetGrid = mpGrid;
        }

        public Set_Macro()
        {
            InitializeComponent();
        }
        private void Set_Macro_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
        }

        private void Set_Macro_Load(object sender, EventArgs e)
        {
            db.DBcon();

            Refresh_Macro_List();

            string cmd = String.Format("SELECT `idx`, `Tag`, `Macro`, `RunCode` FROM `SetMacro` ORDER BY tag ASC, macro ASC;");
            //db.DB_Send_CMD_Search_ApplyGrid(cmd, MacroGrid);
            db.DB_Send_CMD_Search_GetGridData(cmd, MacroGrid);
            RunCode = new string[MacroGrid.RowCount];
            //for (int a = 0; a < MacroGrid.RowCount; a++)
            //{
            //    //RunCode[a] = MacroGrid.Rows[a].Cells["Check"].Value.ToString();
            //}

            //MakeGridCheckReload();
        }
        private List<string> mSearchItem = new List<string>();
        private void Refresh_Macro_List()
        {
            string cmd = string.Format("SELECT `listname` FROM `Comp_SaveMacro` WHERE `compidx` = \"{0}\";", compidx);
            string res = db.DB_Send_CMD_Search(cmd);
            cb_SearchList.Items.Clear();
            mSearchItem = new List<string>();
            foreach (string tItems in res.Split('|'))
            {
                if (tItems == "")
                    continue;
                cb_SearchList.Items.Add(tItems);
                mSearchItem.Add(tItems);
            }
        }

        /// <summary>
        /// 표의 체크박스 초기화
        /// </summary>
        void MakeGridCheckReload()
        {
            //for (int a = 0; a < MacroGrid.Rows.Count; a++)
            //{
            //    //MacroGrid.Rows[a].Cells["Check"].Value = "F";
            //}
        }

        private void cb_SearchList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string listname = cb_SearchList.SelectedItem.ToString();
            string cmd = string.Format("SELECT `Macroidx` FROM `Comp_SaveMacro` WHERE `compidx` = \"{0}\" AND `listname` = \"{1}\";", compidx, listname);
            string res = db.DB_Send_CMD_Search(cmd).Replace("|", "");
            string[] tData = res.Split(new string[] { "^" }, StringSplitOptions.RemoveEmptyEntries);
            List<int> tIDX = tData.ToList().ConvertAll(x => {
                int tReturn = 1;
                int.TryParse(x, out tReturn);
                return tReturn;
                });
            dgvSetting.Rows.Clear();

            for (int i = 0; i < tData.Length; i++)
            {
                List<string> tRows = new List<string>();

                tRows.Add(tData[i]);
                DataGridViewRow tFindRow = MacroGrid.Rows.Cast<DataGridViewRow>().Where(x => x.Cells["idx"].Value.ToString().Equals(tData[i])).First();
                tRows.Add(MacroGrid.Rows[tFindRow.Index].Cells["TagNum"].Value.ToString());
                tRows.Add(MacroGrid.Rows[tFindRow.Index].Cells["Macro"].Value.ToString());
                tRows.Add(MacroGrid.Rows[tFindRow.Index].Cells["TagRun"].Value.ToString());
                dgvSetting.Rows.Add(tRows.ToArray());
            }

            //foreach (string l in res.Split('^'))
            //{
            //    for (int a = 0; a < MacroGrid.Rows.Count; a++)
            //    {
            //        if (MacroGrid.Rows[a].Cells["idx"].Value.ToString() == l)
            //        {
            //            //MacroGrid.Rows[a].Cells["Check"].Value = "T";
            //        }
            //    }
            //}

            //MakeGridCheckReload();
            
            
          
        }

        private void btn_ApplyMacro_Click(object sender, EventArgs e)
        {
            Macro_Gudu macro = new Macro_Gudu(db);
            List<string> idxArray = new List<string>();
            List<string> TagArray = new List<string>();
            List<string> RunCode = new List<string>();
            if (TargetGrid == null) return;

            //for (int a = 0; a < MacroGrid.Rows.Count; a++)
            //{
            //    //if (MacroGrid.Rows[a].Cells["Check"].Value.ToString().Contains("T"))
            //    {
            //        //idxArray.Add(MacroGrid.Rows[a].Cells["idx"].Value.ToString());
            //        //TagArray.Add(MacroGrid.Rows[a].Cells["TagNum"].Value.ToString());
            //        //RunCode.Add(this.RunCode[a]);
            //    }
            //}
            List<Macro> tMacroList = new List<Macro>();
            for (int i = 0; i < dgvSetting.Rows.Count; i++)
            {
                idxArray.Add(dgvSetting.Rows[i].Cells["SetIDX"].Value.ToString());
                TagArray.Add(dgvSetting.Rows[i].Cells["SetTag"].Value.ToString());
                RunCode.Add(dgvSetting.Rows[i].Cells["SetRuncode"].Value.ToString());
                tMacroList.Add(new Macro(dgvSetting.Rows[i].Cells["SetIDX"].Value.ToString(), dgvSetting.Rows[i].Cells["SetTag"].Value.ToString(), dgvSetting.Rows[i].Cells["SetRuncode"].Value.ToString()));
            }
            int count = 0;
            for (int a = 0; a < TargetGrid.Rows.Count; a++)
            {
                var marcstring = TargetGrid.Rows[a].Cells["marc"].Value?.ToString() ?? string.Empty;
                if (string.IsNullOrEmpty(marcstring))
                    continue;

                if ((TargetGrid.Rows[a].Cells["colCheck"].Value?.ToString() ?? string.Empty) != "T")
                    continue;

                TargetGrid.Rows[a].Cells["marc"].Value = macro.MacroMarc(ViewMarcArray[count], tMacroList);
                //TargetGrid.Rows[a].Cells["marc"].Value = macro.MacroMarc(ViewMarcArray[count], idxArray, TagArray, RunCode);
                count++;
            }
            UTIL.MsgI("적용되었습니다!");
        }

        private void btn_AddList_Click(object sender, EventArgs e)
        {
            Skill_Search_Text sst = new Skill_Search_Text();

            string value = "";
            if (sst.InputBox("생성할 목록명을 입력해주세요.", "목록 생성", ref value) == DialogResult.OK)
            {
                string user = PUB.user.UserName;
                string compidx = PUB.user.CompanyIdx;// UniMarc.Properties.Settings.Default.compidx;
                string MacroIndex = "";
                for (int a = 0; a < MacroGrid.Rows.Count; a++)
                {
                    //if (MacroGrid.Rows[a].Cells["Check"].Value.ToString() == "T")
                        //MacroIndex += MacroGrid.Rows[a].Cells["idx"].Value.ToString() + "^";
                }
                MacroIndex.TrimEnd('^');

                string Table = "Comp_SaveMacro";
                if (db.DB_Send_CMD_Search(string.Format("SELECT * FROM {0} WHERE `compidx` = \"{1}\" AND `{2}` = \"{3}\"", Table, compidx, "listname", value)).Length > 2)
                {
                    UTIL.MsgE("중복된 목록명이 있습니다!");
                    return;
                }
                string[] Insert_Tbl = { "compidx", "listname", "user", "Macroidx" };
                string[] Insert_Col = { compidx, value, user, MacroIndex };

                string cmd = db.DB_INSERT(Table, Insert_Tbl, Insert_Col);
                Helper_DB.ExcuteNonQuery(cmd);
                //cb_SearchList.Items.Add(value);
                Refresh_Macro_List();
            }
        }

        private void btn_ListSave_Click(object sender, EventArgs e)
        {
            if (cb_SearchList.SelectedIndex < 0)
            {
                UTIL.MsgE("선택된 목록이 없습니다!");
                return;
            }

            string MacroIndex = "";
            List<string> tIDXList = new List<string>();
            string compidx = PUB.user.CompanyIdx;
            string listname = cb_SearchList.Text;
            //for (int a = 0; a < MacroGrid.Rows.Count; a++)
            //{
            //    //if (MacroGrid.Rows[a].Cells["Check"].Value.ToString() == "T")
            //        MacroIndex += MacroGrid.Rows[a].Cells["idx"].Value.ToString() + "^";// 위에서부터 아래로 순서대로 합치는 부분
            //}
            //MacroIndex.TrimEnd('^');
            for (int i = 0; i < dgvSetting.Rows.Count; i++)
            {
                tIDXList.Add(dgvSetting.Rows[i].Cells["SetIDX"].Value.ToString());
            }
            MacroIndex=string.Join("^", tIDXList);

            string Table = "Comp_SaveMacro";
            string[] Search_T = { "compidx", "listname" };
            string[] Search_C = {  compidx ,  listname  };

            if (db.DB_Send_CMD_Search(db.More_DB_Search(Table, Search_T, Search_C)).Length < 2)
            {
                UTIL.MsgE("선택된 목록이 없습니다!");
                return;
            }

            string[] Update_T = { "Macroidx" };
            string[] Update_C = { MacroIndex };

            Helper_DB.ExcuteNonQuery(db.More_Update(Table, Update_T, Update_C, Search_T, Search_C));
            UTIL.MsgI("저장되었습니다!");
        }

        private void btn_ListRemove_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes != UTIL.MsgQ("현재 목록을 삭제하시겠습니까?"))
                return;

            string compidx = PUB.user.CompanyIdx;
            string listname = cb_SearchList.Text;

            string Table = "Comp_SaveMacro";
            string[] Search_T = { "compidx", "listname" };
            string[] Search_C = { compidx, listname };

            if (db.DB_Send_CMD_Search(db.More_DB_Search(Table, Search_T, Search_C)).Length < 2)
            {
                UTIL.MsgE("선택된 목록이 없습니다!");
                return;
            }

            Helper_DB.ExcuteNonQuery(db.DB_Delete_More_term(Table, "compidx", compidx, Search_T, Search_C));
            UTIL.MsgI("삭제되었습니다!");
            Refresh_Macro_List();
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //private void MacroGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (e.RowIndex < 0)
        //        return;

        //    if (e.ColumnIndex == 3)
        //    {
                
        //    }
        //        //if (MacroGrid.Rows[e.RowIndex].Cells["Check"].Value.ToString().Contains("T"))
        //        //{
        //        //    MacroGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "F";
        //        //    MacroGrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
        //        //}
        //        //else
        //        //{
        //        //    MacroGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "T";
        //        //    MacroGrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
        //        //}
        //}

        private void dgvSetting_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            e.PaintCells(e.ClipBounds, DataGridViewPaintParts.All);

            e.PaintHeader(DataGridViewPaintParts.Background
                | DataGridViewPaintParts.Border
                | DataGridViewPaintParts.Focus
                | DataGridViewPaintParts.SelectionBackground
                | DataGridViewPaintParts.ContentForeground);

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), this.Font, Brushes.Black, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 5);
            e.Handled = true;
        }

        private void MacroGrid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            e.PaintCells(e.ClipBounds, DataGridViewPaintParts.All);

            e.PaintHeader(DataGridViewPaintParts.Background
                | DataGridViewPaintParts.Border
                | DataGridViewPaintParts.Focus
                | DataGridViewPaintParts.SelectionBackground
                | DataGridViewPaintParts.ContentForeground);

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), this.Font, Brushes.Black, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 5);
            e.Handled = true;
        }

        private void MacroGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || cb_SearchList.SelectedIndex == -1)
                return;

            if (e.ColumnIndex == 4) //버튼 이벤트일 경우만 추가 기능 실행
            {
                List<string> tRows = new List<string>();
                tRows.Add(MacroGrid.Rows[e.RowIndex].Cells["idx"].Value.ToString());
                tRows.Add(MacroGrid.Rows[e.RowIndex].Cells["TagNum"].Value.ToString());
                tRows.Add(MacroGrid.Rows[e.RowIndex].Cells["Macro"].Value.ToString());
                tRows.Add(MacroGrid.Rows[e.RowIndex].Cells["TagRun"].Value.ToString());
                dgvSetting.Rows.Add(tRows.ToArray());
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if (dgvSetting.RowCount <= 0) return;
            if (dgvSetting.CurrentRow.Index <= 0) return;
            //
            int tTempCurrentRow = dgvSetting.CurrentRow.Index;
            DataGridViewRow _dgvRow = dgvSetting.Rows[tTempCurrentRow];
            dgvSetting.Rows.RemoveAt(tTempCurrentRow);
            dgvSetting.Rows.Insert(tTempCurrentRow - 1, _dgvRow);
            dgvSetting.Rows[tTempCurrentRow - 1].Selected = true;
            dgvSetting.CurrentCell = dgvSetting[dgvSetting.CurrentCell.ColumnIndex, tTempCurrentRow - 1];
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (dgvSetting.RowCount <= 0) return;
            if (dgvSetting.CurrentRow.Index < 0 || dgvSetting.CurrentRow.Index + 1 == dgvSetting.Rows.Count) return;
            
            int _iCurrentRow = dgvSetting.CurrentRow.Index;
            DataGridViewRow _dgvRow = dgvSetting.Rows[_iCurrentRow];
            dgvSetting.Rows.RemoveAt(_iCurrentRow);
            dgvSetting.Rows.Insert(_iCurrentRow + 1, _dgvRow);
            dgvSetting.Rows[_iCurrentRow + 1].Selected = true;
            dgvSetting.CurrentCell = dgvSetting[dgvSetting.CurrentCell.ColumnIndex, _iCurrentRow + 1];
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvSetting.RowCount <= 0) return;
            if (dgvSetting.CurrentRow.Index < 0  ||  dgvSetting.CurrentRow.Index <0 ) return;
            dgvSetting.Rows.Remove(dgvSetting.SelectedRows[0]) ;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            List<string> tSearch = mSearchItem.FindAll(x => x.Contains(tbSearch.Text));
            cb_SearchList.Items.Clear();
            cb_SearchList.Items.AddRange(tSearch.ToArray());
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            cb_SearchList.Items.Clear();
            cb_SearchList.Items.AddRange(mSearchItem.ToArray());
        }

       
    }
}
