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 AR;

namespace UniMarc
{
    public partial class Transaction_manage : Form
    {
        Helper_DB db = new Helper_DB();
        public string compidx;
        Main main;
        public Transaction_manage(Main _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Transaction_manage_Load(object sender, EventArgs e)
        {
            string[] gubun1 = { "전체", "납품처", "거래처" };
            cb_gubun1.Items.AddRange(gubun1);
            cb_gubun1.SelectedIndex = 0;

            string[] dlsArea = {
                "서울", "부산", "대구", "인천", "광주",
                "대전", "울산", "세종", "경기", "강원",
                "충북", "충남", "전북", "전남", "경북",
                "경남", "제주"
            };
            cb_dlsArea.Items.AddRange(dlsArea);

            compidx = PUB.user.CompanyIdx;
            panel4.Visible = false;
            db.DBcon();

            //저자기호 셋팅값 251022
            AuthorSymbol.Symbol sb = new AuthorSymbol.Symbol();
            cb_FirstAuthor.Items.AddRange(sb.authorBook);
            cb_authorTypeK.Items.AddRange(sb.authorType);
            cb_authorTypeE.Items.AddRange(sb.authorType);
            cb_FirstBook.Items.AddRange(sb.authorFirst);
            cb_author_four.Items.AddRange(sb.authorFour);

            string[] divType = { "KDC", "DDC" };
            cb_divType.Items.AddRange(divType);

            string[] divNum = { "4", "5", "6" };
            cb_divNum.Items.AddRange(divNum);

            //저자기호 관련 컬럼추가
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_first", HeaderText = "dvc_author_first", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_typeK", HeaderText = "dvc_author_typeK", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_typeE", HeaderText = "dvc_author_typeE", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_firstbook", HeaderText = "dvc_author_firstbook", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_divtype", HeaderText = "dvc_author_divtype", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_divnum", HeaderText = "dvc_author_divnum", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_four", HeaderText = "dvc_author_four", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_pijunja", HeaderText = "dvc_pijunja", Visible = false });
            dv1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "dvc_author_four_use", HeaderText = "dvc_author_four_use", Visible = false });


        }
        private void Made_Grid()
        {
            string seartempdb = "`idx`, `c_sangho`, `c_gu`, `c_boss`, `c_bubin`, " +
                                "`c_uptae`, `c_jongmok`, `c_tel`, `c_fax`, `c_email`, " +
                                "`c_man`, `c_mantel`, `c_user`, `c_zip`, `c_addr`, " +
                                "`c_dlsArea`, `c_dlsID`, `c_dlsPW`, `c_division`, `c_label`, " +
                                "`c_program`, `c_etc`";
            string cmd = db.DB_Select_Search(seartempdb, "Client", "campanyidx", compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            dv1.Rows.Clear();
            string[] data = db_res.Split('|');
            string[] result = { "", "", "", "", "",
                                "", "", "", "", "",
                                "", "", "", "", "",
                                "", "", "", "", "",
                                "", "" };
            int ea = 0;
            for (int a = 0; a < data.Length; a++)
            {
                if (ea == 11)
                {
                    result[10] += " | " + data[a];
                }
                else if (a % 21 == ea)
                {
                    if (ea > 11)
                    {
                        result[ea - 1] = data[a];
                        if (ea == 20)
                        {
                            dv1.Rows.Add(result);
                            ea = 0;
                        }
                    }
                    else
                    {
                        result[ea] = data[a];
                    }
                }
                ea++;
            }
        }
        public void TextInit()
        {
            lbl_idx.Text = "";
            tb_sangho.Text = "";
            tb_boss.Text = "";
            tb_bubin.Text = "";
            tb_uptae.Text = "";
            tb_jongmok.Text = "";
            tb_tel.Text = "";
            tb_fax.Text = "";
            tb_mail.Text = "";
            tb_man.Text = "";
            tb_man1.Text = "";
            tb_user.Text = PUB.user.UserName;
            tb_zip.Text = "";
            tb_addr.Text = "";
            tb_id.Text = "";
            tb_pw.Text = "";
            tb_division.Text = "";
            tb_label.Text = "";
            tb_program.Text = "";
            rtb_etc.Text = "";
            cb_gubun1.SelectedIndex = 0;
            cb_authorTypeK.SelectedIndex = -1;
            cb_authorTypeE.SelectedIndex = -1;
            cb_FirstAuthor.SelectedIndex = -1;
            cb_FirstBook.SelectedIndex = -1;
            cb_divNum.SelectedIndex = -1;
            cb_divType.SelectedIndex = -1;
            cb_author_four.SelectedIndex = -1;
            chk_pijunja.Checked = false;
            chk_authorFour.Checked = false;
        }
        private bool Check_Data(string pText)
        {
            string CopyCheckCMD = string.Format("SELECT {0} FROM {1} WHERE {0} = \"{2}\";", "`c_sangho`", "`Client`", tb_sangho.Text);
            string CopyCheck = db.DB_Send_CMD_Search(CopyCheckCMD).Replace("|", "");
            bool isCopy = CopyCheck == pText;
            return isCopy;
        }
        private void btnInit_Click(object sender, EventArgs e)
        {
            TextInit();
        }

        public void btn_add_Click(object sender, EventArgs e)
        {
            if (dv1.CurrentCell == null) return;
            int RowIndex = dv1.CurrentCell.RowIndex;
            if (RowIndex < 0)
                return;
            string tText = string.Format("{0} 를 추가 하시겠습니까?", tb_sangho.Text);
            if (UTIL.MsgQ(tText) != DialogResult.Yes) return;

            if (tb_sangho.Text == "")
            {
                UTIL.MsgE("업체명이 비어있습니다.");
                return;
            }
            if (cb_gubun1.SelectedIndex == 0)
            {
                UTIL.MsgE("구분을 선택해주세요.");
                return;
            }
            if (cb_gubun2.SelectedIndex == 0)
            {
                UTIL.MsgE("구분을 선택해주세요.");
                return;
            }
            if (cb_gubun2.SelectedItem.ToString() == "학교" && cb_dlsArea.SelectedIndex < 0 && tb_id.Text != "")
            {
                UTIL.MsgE("DLS 지역을 선택해주세요.");
                return;
            }
            //string CopyCheckCMD = string.Format("SELECT {0} FROM {1} WHERE {0} = \"{2}\";", "`c_sangho`", "`Client`", tb_sangho.Text);
            //string CopyCheck = db.DB_Send_CMD_Search(CopyCheckCMD).Replace("|","");
            //bool isCopy = CopyCheck == tb_sangho.Text;
            bool isCopy = Check_Data(tb_sangho.Text);
            if (isCopy)
            {
                UTIL.MsgE("중복된 상호명이 존재합니다!");
                return;
            }

            string[] tmpdb = { "c_sangho", "c_gu", "c_boss", "c_bubin", "c_uptae",
                                   "c_jongmok", "c_tel", "c_fax", "c_email", "c_man",
                                   "c_mantel", "c_user", "c_zip", "c_addr", "c_dlsID",
                                   "c_dlsPW", "c_division", "c_label", "c_program", "c_etc",
                                   "campanyidx", "c_dlsArea" ,
                                   "c_author_first", "c_author_typeK","c_author_typeE", "c_author_firstbook",
                                   "c_author_divtype", "c_author_divnum","c_author_four","c_pijunja","c_author_four_use"};

            string[] tmpdb1 = { tb_sangho.Text, cb_gubun2.Text, tb_boss.Text, tb_bubin.Text, tb_uptae.Text,
                                    tb_jongmok.Text, tb_tel.Text, tb_fax.Text, tb_mail.Text, tb_man.Text,
                                    tb_man1.Text, tb_user.Text, tb_zip.Text, tb_addr.Text, tb_id.Text,
                                    tb_pw.Text, tb_division.Text, tb_label.Text, tb_program.Text, rtb_etc.Text,
                                    compidx, cb_dlsArea.Text, cb_FirstAuthor.Text, cb_authorTypeK.Text,
                                cb_authorTypeE.Text,cb_FirstBook.Text, cb_divType.Text, cb_divNum.Text ,cb_author_four.Text,
                                (chk_pijunja.Checked ? "1":"0"),(chk_authorFour.Checked ? "1":"0") };
            string[] tOldData = {
                };
            string Incmd = db.DB_INSERT("Client", tmpdb, tmpdb1);

            Helper_DB.ExcuteNonQuery(Incmd);
            SearchList();
            UTIL.MsgI(string.Format("[{0}]가 성공적으로 저장되었습니다.", tb_sangho.Text));
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            if (dv1.SelectedRows.Count == 0)
            {
                UTIL.MsgE("수정 할 업체를 선택해 주세요.");
                return;
            }
            int tRowIndex = dv1.SelectedRows[0].Index;
            if (tRowIndex < 0)
                return;
            string tText = string.Format("{0} 를 수정 하시겠습니까?", dv1.Rows[tRowIndex].Cells["sangho"].Value.ToString());
            if (UTIL.MsgQ(tText) != DialogResult.Yes) return;
            if (tb_sangho.Text == "")
            {
                UTIL.MsgE("업체명이 비어있습니다.");
                return;
            }
            if (cb_gubun1.SelectedIndex == 0)
            {
                UTIL.MsgE("구분을 선택해주세요.");
                return;
            }
            if (cb_gubun2.SelectedIndex == 0)
            {
                UTIL.MsgE("구분을 선택해주세요.");
                return;
            }
            if (cb_gubun2.SelectedItem.ToString() == "학교" && cb_dlsArea.SelectedIndex < 0 && tb_id.Text != "")
            {
                UTIL.MsgE("DLS 지역을 선택해주세요.");
                return;
            }
            //string CopyCheckCMD = string.Format("SELECT {0} FROM {1} WHERE {0} = \"{2}\";", "`c_sangho`", "`Client`", tb_sangho.Text);
            //string CopyCheck = db.DB_Send_CMD_Search(CopyCheckCMD).Replace("|","");
            //bool isCopy = CopyCheck == tb_sangho.Text;
            //bool isCopy = Check_Data(tb_sangho.Text);

            //if (isCopy)     // 중복 데이터가 있을 경우
            //{
            int RowIndex = dv1.CurrentCell.RowIndex;
            string[] editcol = { "c_sangho", "c_gu", "c_boss", "c_bubin", "c_uptae",
                                     "c_jongmok", "c_tel", "c_fax", "c_email", "c_man",
                                     "c_mantel", "c_user", "c_zip", "c_addr", "c_dlsID",
                                     "c_dlsPW", "c_division", "c_label", "c_program", "c_etc",
                                     "c_dlsArea" ,
                                    "c_author_first", "c_author_typeK", "c_author_typeE","c_author_firstbook",
                "c_author_divtype", "c_author_divnum","c_author_four","c_pijunja","c_author_four_use"};

            string[] editname = { tb_sangho.Text, cb_gubun2.Text, tb_boss.Text, tb_bubin.Text, tb_uptae.Text,
                                      tb_jongmok.Text, tb_tel.Text, tb_fax.Text, tb_mail.Text, tb_man.Text,
                                      tb_man1.Text, tb_user.Text, tb_zip.Text, tb_addr.Text, tb_id.Text,
                                      tb_pw.Text, tb_division.Text, tb_label.Text, tb_program.Text, rtb_etc.Text,
                                      cb_dlsArea.Text,
                                    cb_FirstAuthor.Text, cb_authorTypeK.Text,cb_authorTypeE.Text, cb_FirstBook.Text,
                cb_divType.Text, cb_divNum.Text ,cb_author_four.Text,(chk_pijunja.Checked ? "1":"0") ,(chk_authorFour.Checked ? "1":"0") };

            string[] searchcol = { "idx", "campanyidx" };
            string[] searchname = { lbl_idx.Text, compidx };

            string U_cmd = db.More_Update("Client", editcol, editname, searchcol, searchname);

            Helper_DB.ExcuteNonQuery(U_cmd);
            UTIL.MsgI(tb_sangho.Text + "가 성공적으로 수정되었습니다.");
            //}
            //else
            //{
            //    string[] tmpdb = { "c_sangho", "c_gu", "c_boss", "c_bubin", "c_uptae",
            //                       "c_jongmok", "c_tel", "c_fax", "c_email", "c_man",
            //                       "c_mantel", "c_user", "c_zip", "c_addr", "c_dlsID",
            //                       "c_dlsPW", "c_division", "c_label", "c_program", "c_etc",
            //                       "campanyidx", "c_dlsArea" };
            //    string[] tmpdb1 = { tb_sangho.Text, cb_gubun2.Text, tb_boss.Text, tb_bubin.Text, tb_uptae.Text,
            //                        tb_jongmok.Text, tb_tel.Text, tb_fax.Text, tb_mail.Text, tb_man.Text,
            //                        tb_man1.Text, tb_user.Text, tb_zip.Text, tb_addr.Text, tb_id.Text,
            //                        tb_pw.Text, tb_division.Text, tb_label.Text, tb_program.Text, rtb_etc.Text, 
            //                        compidx, cb_dlsArea.Text };
            //    string[] tOldData = { 
            //    };
            //    string Incmd = db.DB_INSERT("Client", tmpdb, tmpdb1);

            //    Helper_DB.ExcuteNonQuery(Incmd);

            //    UTIL.MsgI(string.Format("[{0}]가 성공적으로 저장되었습니다.", tb_sangho.Text));
            //}
            SearchList();
            dv1.Rows[RowIndex].Selected = true;

        }
        private void btn_delete_Click(object sender, EventArgs e)
        {
            if (dv1.CurrentCell == null) return;
            int RowIndex = dv1.CurrentCell.RowIndex;
            if (RowIndex < 0)
                return;
            string tText = string.Format("{0} 를 삭제 하시겠습니까?", dv1.Rows[RowIndex].Cells["sangho"].Value.ToString());
            if (UTIL.MsgQ(tText) != DialogResult.Yes) return;
            string D_cmd = db.DB_Delete("Client", "idx", dv1.Rows[RowIndex].Cells["idx"].Value.ToString(), "c_sangho", tb_sangho.Text);
            Helper_DB.ExcuteNonQuery(D_cmd);
            Made_Grid();
            SearchList();
            UTIL.MsgI("삭제되었습니다.");
        }

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

            if (RowIndex < 0)
                return;

            TextInit();

            Infor_Client(RowIndex);

            lookup(panel4.Visible);
        }

        void Infor_Client(int RowIndex)
        {
            if (RowIndex < 0)
                return;

            lbl_idx.Text = dv1.Rows[RowIndex].Cells["idx"].Value.ToString();

            tb_sangho.Text = dv1.Rows[RowIndex].Cells["sangho"].Value.ToString();
            tb_boss.Text = dv1.Rows[RowIndex].Cells["boss"].Value.ToString();
            tb_bubin.Text = dv1.Rows[RowIndex].Cells["bubin"].Value.ToString();
            tb_division.Text = dv1.Rows[RowIndex].Cells["division"].Value.ToString();
            tb_jongmok.Text = dv1.Rows[RowIndex].Cells["jongmok"].Value.ToString();
            tb_label.Text = dv1.Rows[RowIndex].Cells["label"].Value.ToString();
            tb_mail.Text = dv1.Rows[RowIndex].Cells["mail"].Value.ToString();
            tb_man.Text = dv1.Rows[RowIndex].Cells["man"].Value.ToString();
            tb_man1.Text = dv1.Rows[RowIndex].Cells["mantel"].Value.ToString();
            tb_program.Text = dv1.Rows[RowIndex].Cells["program"].Value.ToString();
            tb_id.Text = dv1.Rows[RowIndex].Cells["DLSid"].Value.ToString();
            tb_pw.Text = dv1.Rows[RowIndex].Cells["DLSpw"].Value.ToString();
            tb_uptae.Text = dv1.Rows[RowIndex].Cells["uptae"].Value.ToString();
            tb_zip.Text = dv1.Rows[RowIndex].Cells["post_num"].Value.ToString();
            tb_user.Text = dv1.Rows[RowIndex].Cells["assumer"].Value.ToString();
            tb_tel.Text = dv1.Rows[RowIndex].Cells["tel"].Value.ToString();
            tb_fax.Text = dv1.Rows[RowIndex].Cells["fax"].Value.ToString();
            tb_addr.Text = dv1.Rows[RowIndex].Cells["addr"].Value.ToString();
            rtb_etc.Text = dv1.Rows[RowIndex].Cells["bigo"].Value.ToString();
            cb_dlsArea.Text = dv1.Rows[RowIndex].Cells["dlsArea"].Value.ToString();

            //저자기호값 셋팅
            var author_first = dv1.Rows[RowIndex].Cells["dvc_author_first"].Value?.ToString() ?? string.Empty;
            var author_typeK = dv1.Rows[RowIndex].Cells["dvc_author_typeK"].Value?.ToString() ?? string.Empty;
            var author_typeE = dv1.Rows[RowIndex].Cells["dvc_author_typeE"].Value?.ToString() ?? string.Empty;
            var author_firstbook = dv1.Rows[RowIndex].Cells["dvc_author_firstbook"].Value?.ToString() ?? string.Empty;
            var author_divtype = dv1.Rows[RowIndex].Cells["dvc_author_divtype"].Value?.ToString() ?? string.Empty;
            var author_divnum = dv1.Rows[RowIndex].Cells["dvc_author_divnum"].Value?.ToString() ?? string.Empty;
            var author_four = dv1.Rows[RowIndex].Cells["dvc_author_four"].Value?.ToString() ?? string.Empty;
            var pijunja = dv1.Rows[RowIndex].Cells["dvc_pijunja"].Value?.ToString() ?? "0";
            var author_four_use = dv1.Rows[RowIndex].Cells["dvc_author_four_use"].Value?.ToString() ?? "0";
            

            if (author_typeK.isEmpty() == false) cb_authorTypeK.Text = author_typeK;
            else cb_authorTypeK.SelectedIndex = -1;
            if (author_typeE.isEmpty() == false) cb_authorTypeE.Text = author_typeE;
            else cb_authorTypeE.SelectedIndex = -1;
            if (author_first.isEmpty() == false) cb_FirstAuthor.Text = author_first;
            else cb_FirstAuthor.SelectedIndex = -1;
            if (author_firstbook.isEmpty() == false) cb_FirstBook.Text = author_firstbook;
            else cb_FirstBook.SelectedIndex = -1;
            if (author_divtype.isEmpty() == false) cb_divType.Text = author_divtype;
            else cb_divType.SelectedIndex = -1;
            if (author_divnum.isEmpty() == false) cb_divNum.Text = author_divnum;
            else cb_divNum.SelectedIndex = -1;
            if (author_four.isEmpty() == false) cb_author_four.Text = author_four;
            else cb_author_four.SelectedIndex = -1;

            chk_pijunja.Checked = pijunja == "1";
            chk_authorFour.Checked = author_four_use == "1";
            Select_Gubun(RowIndex);
        }
        private void Select_Gubun(int pRowIndex)
        {
            string gubun = dv1.Rows[pRowIndex].Cells["gubun"].Value.ToString();
            if (gubun.Contains("학교") || gubun == "도서관" || gubun == "유치원")
            {
                cb_gubun1.SelectedIndex = 1;

                switch (gubun)
                {
                    case "유치원":
                        cb_gubun2.SelectedIndex = 1;
                        break;
                    case "초등학교":
                        cb_gubun2.SelectedIndex = 2;
                        break;
                    case "중학교":
                        cb_gubun2.SelectedIndex = 3;
                        break;
                    case "고등학교":
                        cb_gubun2.SelectedIndex = 4;
                        break;
                    case "대학교":
                        cb_gubun2.SelectedIndex = 5;
                        break;
                    case "학교":
                        cb_gubun2.SelectedIndex = 6;
                        break;
                    case "도서관":
                        cb_gubun2.SelectedIndex = 7;
                        break;
                }
                ;
            }
            if (gubun == "서점" || gubun == "기타")
            {
                cb_gubun1.SelectedIndex = 2;

                switch (gubun)
                {
                    case "서점":
                        cb_gubun2.SelectedIndex = 1;
                        break;
                    case "기타":
                        cb_gubun2.SelectedIndex = 2;
                        break;
                }
                ;
            }
        }
        private void tb_sangho_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btn_search_Click(null, null);
        }
        private void btn_search_Click(object sender, EventArgs e)
        {
            /// _Sub_Search_Form sub_search = new _Sub_Search_Form(this);
            /// sub_search.Show();
            SearchList();
        }
        private void SearchList()
        {
            dv1.Rows.Clear();

            string search = "`idx`, `c_sangho`, `c_gu`, `c_boss`, `c_bubin`, " +
                            "`c_uptae`, `c_jongmok`, `c_tel`, `c_fax`, `c_email`, " +
                            "`c_man`, `c_mantel`, `c_user`, `c_zip`, `c_addr`, " +
                            "`c_dlsArea`, `c_dlsID`, `c_dlsPW`, `c_division`, `c_label`," +
                            "`c_program`, `c_etc`," +
                            "`c_author_first`, `c_author_typeK`, `c_author_typeE`,`c_author_firstbook`, " +
                            "`c_author_divtype`, `c_author_divnum`, `c_author_four`, `c_pijunja`, `c_author_four_use`";
            string cmd = db.DB_Contains("Client", compidx, "c_sangho", tbSearch.Text, search);
            db.DB_Send_CMD_Search_ApplyGrid(cmd, dv1);

            dv1.Focus();
            dv1.ClearSelection();
        }
        private void cb_gubun1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_gubun1.SelectedIndex == 1)
            {
                cb_gubun2.Items.Clear();
                string[] gubun2 = { "전체", "유치원", "초등학교", "중학교", "고등학교", "대학교", "학교", "도서관" };
                cb_gubun2.Items.AddRange(gubun2);
                cb_gubun2.SelectedIndex = 0;
            }
            if (cb_gubun1.SelectedIndex == 2)
            {
                cb_gubun2.Items.Clear();
                string[] gubun2 = { "전체", "서점", "기타" };
                cb_gubun2.Items.AddRange(gubun2);
                cb_gubun2.SelectedIndex = 0;
            }
        }

        private void btn_marc_expand_Click(object sender, EventArgs e)
        {
            if (dv1.CurrentCell == null) return;
            int RowIndex = dv1.CurrentCell.RowIndex;

            if (RowIndex < 0)
                return;

            if (!panel4.Visible)
            {
                btn_marc_expand.Text = "마크 비고 >>";
                panel4.Visible = true;
            }
            else
            {
                btn_marc_expand.Text = "마크 비고 <<";
                panel4.Visible = false;
            }

            lookup(panel4.Visible);
        }

        private void lookup(bool chk)
        {
            int RowIndex = dv1.CurrentCell.RowIndex;

            if (RowIndex < 0)
                return;

            if (!chk) return;

            marcGrid.Rows.Clear();
            gearGrid.Rows.Clear();

            marcGrid.Rows.Add(150);
            gearGrid.Rows.Add(100);

            string idx = dv1.Rows[RowIndex].Cells["idx"].Value.ToString();
            string Area = "`cm_m1`, `cm_m2`, `cm_m3`";

            string cmd = String.Format("Select {0} From {1} where cm_midx = {2} and cm_opt = {3} Order by cm_opt asc, cm_sq asc;",
                Area, "custm_tbl", idx, "1");

            string res = db.DB_Send_CMD_Search(cmd);
            string[] tmpArray = res.Split('|');

            Add_Grid(tmpArray, marcGrid);

            cmd = String.Format("Select {0} From {1} where cm_midx = {2} and cm_opt = {3} Order by cm_opt asc, cm_sq asc;",
                Area, "custm_tbl", idx, "2");

            res = db.DB_Send_CMD_Search(cmd);
            tmpArray = res.Split('|');

            Add_Grid(tmpArray, gearGrid);
        }

        private void Add_Grid(string[] ary_data, DataGridView gridView)
        {
            int rowCount = 0;
            for (int a = 0; a < ary_data.Length; a++)
            {
                if (a % 3 == 0) { gridView.Rows[rowCount].Cells[0].Value = ary_data[a]; }
                if (a % 3 == 1) { gridView.Rows[rowCount].Cells[1].Value = ary_data[a]; }
                if (a % 3 == 2) { gridView.Rows[rowCount].Cells[2].Value = ary_data[a]; rowCount++; }
            }
        }

        private void tb_marcSave_Click(object sender, EventArgs e)
        {
            string idx = lbl_idx.Text;

            if (string.IsNullOrEmpty(idx))
                return;

            string Dcmd = string.Format("DELETE FROM custm_tbl WHERE cm_midx = {0}", idx);
            Helper_DB.ExcuteNonQuery(Dcmd);

            MakeInsertCommend(marcGrid, 1, idx);
            MakeInsertCommend(gearGrid, 2, idx);
        }

        private void MakeInsertCommend(DataGridView dgv, int gridNum, string idx)
        {
            int LoopCount = 0;
            string m1, m2, m3;
            for (int a = 0; a < dgv.Rows.Count; a++)
            {
                if (dgv.Rows[a].Cells[0].Value == null) dgv.Rows[a].Cells[0].Value = "";
                if (dgv.Rows[a].Cells[1].Value == null) dgv.Rows[a].Cells[1].Value = "";
                if (dgv.Rows[a].Cells[2].Value == null) dgv.Rows[a].Cells[2].Value = "";

                if (dgv.Rows[a].Cells[0].Value.ToString() != "") LoopCount = a;
                if (dgv.Rows[a].Cells[1].Value.ToString() != "") LoopCount = a;
                if (dgv.Rows[a].Cells[2].Value.ToString() != "") LoopCount = a;
            }

            for (int a = 0; a < LoopCount + 1; a++)
            {
                m1 = dgv.Rows[a].Cells[0].Value.ToString();
                m2 = dgv.Rows[a].Cells[1].Value.ToString();
                m3 = dgv.Rows[a].Cells[2].Value.ToString();

                string Icmd = string.Format("INSERT INTO custm_tbl (cm_m1, cm_m2, cm_m3, cm_sq, cm_opt, cm_midx)" +
                    " values(\"{0}\", \"{1}\", \"{2}\", {3}, {4}, {5});", m1, m2, m3, a, gridNum, idx);

                Helper_DB.ExcuteNonQuery(Icmd);
            }
        }

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

        private void tb_Empty_Click(object sender, EventArgs e)
        {
            string name = ((Button)sender).Name;

            if (name.Contains("marc"))
            {
                marcGrid.Rows.Clear();
                marcGrid.Rows.Add(150);
            }
            else
            {
                gearGrid.Rows.Clear();
                gearGrid.Rows.Add(100);
            }
        }

        private void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Excel_to_DataGridView(sender, e);
            sg.DataGrid_to_Delete(sender, e);
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btExportList_Click(object sender, EventArgs e)
        {
            using (var sd = new SaveFileDialog())
            {
                sd.Filter = "텍스트(콤마로 분리된 파일)|*.csv";
                sd.FilterIndex = 0;
                sd.FileName = "exportdata.csv";
                if (sd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        this.dv1.ExportData(sd.FileName);
                        if (UTIL.MsgQ("생성된 파일을 확인 할까요?") == DialogResult.Yes)
                            UTIL.RunExplorer(sd.FileName);
                    }

                    catch (Exception ex) { UTIL.MsgE(ex.Message); }
                }
            }

        }

        private void cb_authorTypeK_Click(object sender, EventArgs e)
        {

        }

        private void cb_authorTypeK_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.cb_authorTypeE.SelectedIndex = cb_authorTypeK.SelectedIndex;
            if (cb_authorTypeK.Text.Contains("장일세"))
            {
                cb_FirstAuthor.Text = "초성";
                cb_FirstBook.Text = "초성";
            }
        }
    }
}
