using AR;
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 UniMarc
{
    public partial class Marc_Plan_PrintLabel : Form
    {
        Marc_Plan mp;
        Helper_DB db = new Helper_DB();
        public Marc_Plan_PrintLabel(Marc_Plan _mp)
        {
            InitializeComponent();
            mp = _mp;
        }

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

            String_Text st = new String_Text();
            // string[] Font = { "굴림", "굴림체", "돋움", "바탕체", "맑은 고딕", "HY강B", "HY강M" };
            // cb_TextFont.Items.AddRange(Font);
            cb_TextFont.Items.AddRange(st.callMyFont());

            SearchList();
        }

        private void tb_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SearchList();
        }
        #region Search
        /// <summary>
        /// 검색값을 토대로 DB에서 목록을 불러옴
        /// </summary>
        private void SearchList()
        {
            dataGridView1.Rows.Clear();

            string Text = tb_Search.Text;

            string Area = "`idx`, `name`, `user`";
            string Tabel = "PrintLabel";
            //string compidx = PUB.user.CompanyIdxProperties.Settings.Default.compidx;

            string cmd = string.Format(
                "SELECT {0} " +
                "FROM {1} " +
                "WHERE `compidx` = \"{2}\" AND `name` LIKE \"%{3}%\";", Area, Tabel, PUB.user.CompanyIdx, Text);
            string res = db.self_Made_Cmd(cmd);
            InputGrid(res);
        }

        /// <summary>
        /// Grid에 검색값을 표출
        /// </summary>
        /// <param name="DB_Data"></param>
        private void InputGrid(string DB_Data)
        {
            string[] SplitData = DB_Data.Split('|');

            string[] Grid = { "", "", "" };
            for (int a = 0; a < SplitData.Length; a++)
            {
                if (a % 3 == 0) Grid[0] = SplitData[a];
                if (a % 3 == 1) Grid[1] = SplitData[a];
                if (a % 3 == 2)
                {
                    Grid[2] = SplitData[a];
                    dataGridView1.Rows.Add(Grid);
                }
            }
        }
        #endregion

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;

            string Area =
                "`left`, `top`, `width`, `height`, `garogap`, " +
                "`serogap`, `garocount`, `serocount`, `vol`, `count`, " +
                "`textfont`, `fontsize`";
            string Table = "PrintLabel";
            string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();

            string cmd = string.Format("SELECT {0} FROM {1} WHERE `idx` = {2}", Area, Table, idx);
            string res = db.self_Made_Cmd(cmd);
            InputText(row, res);
        }
        #region CellClick_Sub

        private void InputText(int row, string DB_Data)
        {
            string[] SplitData = DB_Data.Split('|');

            tb_ListName.Text = dataGridView1.Rows[row].Cells["name"].Value.ToString();

            TextBox[] tb = { tb_Left, tb_Top, tb_Width, tb_Height, tb_GaroGap, tb_SeroGap, tb_Garo, tb_Sero };
            int count = 0;
            foreach (string Data in SplitData)
            {
                if (Data == "")
                    continue;

                if (count == 8)
                {
                    if (Data == "0")
                        chk_V.Checked = false;
                    else
                        chk_V.Checked = true;
                }
                else if (count == 9)
                {
                    if (Data == "0")
                        chk_C.Checked = false;
                    else
                        chk_C.Checked = true;
                }
                else if (count == 10)
                {
                    cb_TextFont.SelectedItem = Data;
                }
                else if (count == 11)
                {
                    tb_TextSize.Text = Data;
                }
                else if (tb.Length > count)
                {
                    tb[count].Text = Data;
                }
                count++;
            }
        }

        #endregion

        private void btn_Apply_Click(object sender, EventArgs e)
        {
            // 적용
            TextBox[] Box = { tb_Left, tb_Top, tb_Width, tb_Height, tb_GaroGap, tb_SeroGap, tb_Garo, tb_Sero, tb_TextSize };
            string Font = cb_TextFont.SelectedItem.ToString();
            bool[] ChkByC_V = { chk_C.Checked, chk_V.Checked };

            mp.BringPringLabel(Box, Font, ChkByC_V);
        }

        private void btn_Empty_Click(object sender, EventArgs e)
        {
            TextBox[] tb = { tb_Left, tb_Top, tb_Width, tb_Height, tb_GaroGap, tb_SeroGap, tb_Garo, tb_Sero, tb_TextSize };

            foreach (TextBox Box in tb)
            {
                Box.Text = "";
            }

            chk_C.Checked = false;
            chk_V.Checked = false;
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            // 삭제
            string listName = tb_ListName.Text;
            if (listName == "") return;

            int row = -1;
            if (dataGridView1.CurrentRow != null)
                row = dataGridView1.CurrentCell.RowIndex;
            else if (row > 0)
                return;

            string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();
            string cmd = string.Format("DELETE FROM `PrintLabel` WHERE `idx` = {0}", idx);

            Helper_DB.ExcuteNonQuery(cmd);
            dataGridView1.Rows.Remove(dataGridView1.Rows[row]);
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            // 저장
            string listName = tb_ListName.Text;
            if (listName == "") return;

            int row = -1;
            if (dataGridView1.CurrentRow != null)
                row = dataGridView1.CurrentCell.RowIndex;
            else if (row > 0)
                return;

            string User = PUB.user.UserName;// Properties.Settings.Default.User;
            string compidx = PUB.user.CompanyIdx;// Properties.Settings.Default.compidx;

            string CopyCheckCMD = string.Format(
                "SELECT * " +
                "FROM `PrintLabel` " +
                "WHERE `name` = \"{0}\" AND `compidx` = \"{1}\";", listName, compidx);
            string CopyCehck = db.DB_Send_CMD_Search(CopyCheckCMD);

            bool isCopy = false;

            if (CopyCehck.Length > 0)
                isCopy = true;

            if (isCopy)      // 중복 데이터가 있을 경우
            {
                string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();

                string[] editCol = {
                    "left", "top", "width", "height",
                    "garogap", "serogap", "garocount", "serocount",
                    "vol", "count",
                    "textfont", "fontsize"
                };
                string[] editData = {
                    tb_Left.Text, tb_Top.Text, tb_Width.Text, tb_Height.Text,
                    tb_GaroGap.Text, tb_SeroGap.Text, tb_Garo.Text, tb_Sero.Text,
                    ConvertBool(chk_V.Checked), ConvertBool(chk_C.Checked),
                    cb_TextFont.SelectedItem.ToString(), tb_TextSize.Text
                };
                string[] SearchCol = { "idx", "compidx" };
                string[] SearchData = { idx, compidx };

                string U_cmd = db.More_Update("PrintLabel", editCol, editData, SearchCol, SearchData);

                Helper_DB.ExcuteNonQuery(U_cmd);

                UTIL.MsgI(tb_ListName.Text + "가 성공적으로 수정되었습니다!");
            }
            else
            {
                string[] InsertCol = {
                    "compidx", "name", "user",
                    "left", "top", "width", "height",
                    "garogap", "serogap", "garocount", "serocount",
                    "vol", "count",
                    "textfont", "fontsize"
                };
                string[] InsertData = {
                    compidx, listName, User,
                    tb_Left.Text, tb_Top.Text, tb_Width.Text, tb_Height.Text,
                    tb_GaroGap.Text, tb_SeroGap.Text, tb_Garo.Text, tb_Sero.Text,
                    ConvertBool(chk_V.Checked), ConvertBool(chk_C.Checked),
                    cb_TextFont.SelectedItem.ToString(), tb_TextSize.Text
                };

                string Incmd = db.DB_INSERT("PrintLabel", InsertCol, InsertData);

                Helper_DB.ExcuteNonQuery(Incmd);

                UTIL.MsgI(tb_ListName.Text + "가 성공적으로 저장되었습니다!");
            }
        }

        #region Save_Sub

        string ConvertBool(bool Check)
        {
            if (Check)
                return "0";
            else
                return "1";
        }
        #endregion

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

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Print_Grid_Num(sender, e);
        }
    }
}
