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 Order_manage : Form
    {
        Helper_DB db = new Helper_DB();
        Main main;
        public Order_manage(Main _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Order_manage_Load(object sender, EventArgs e)
        {
            db.DBcon();
            string[] filter = { "상호", "대표자명", "전화번호", "팩스번호", "사업자번호" };
            cb_search_filter.Items.AddRange(filter);
            cb_search_filter.SelectedIndex = 0;
            string[] gubun = { "출판", "도매", "기타", "경비" };
            cb_gubun.Items.AddRange(gubun);
            cb_gubun.SelectedIndex = 0;
        }
        private void btn_Lookup_Click(object sender, EventArgs e)   // 조회
        {
            string Search_Table = "`idx`, `send_chk`, `sangho`, `boss`, `bubin`, " +
                                  "`uptae`, `jongmok`, `zip`, `addr`, `tel`, " +
                                  "`fax`, `bank_no`, `bank_comp`, `bank_name`, `gu`, " +
                                  "`barea`, `etc_1`, `etc_2`, `email`, `id`, " +
                                  "`pw`, `site`, `emchk`";
            if (tb_search.Text == "")
            {
                string[] Where_Table = { "comparyidx" };
                string[] Search_Data = { PUB.user.CompanyIdx };
                string cmd = db.More_DB_Search("Purchase", Where_Table, Search_Data, Search_Table);
                string db_res = db.DB_Send_CMD_Search(cmd);
                Made_Grid(db_res);
            }
            else if (tb_search.Text != "") 
            {
                string[] Search_col = { "" };
                if (cb_search_filter.SelectedIndex == 0) Search_col[0] = "sangho";
                if (cb_search_filter.SelectedIndex == 1) Search_col[0] = "boss";
                if (cb_search_filter.SelectedIndex == 2) Search_col[0] = "tel";
                if (cb_search_filter.SelectedIndex == 4) Search_col[0] = "fax";
                if (cb_search_filter.SelectedIndex == 3) Search_col[0] = "bubin";
                string cmd = db.DB_Contains("Purchase", PUB.user.CompanyIdx, Search_col[0], tb_search.Text, Search_Table);
                string db_res = db.DB_Send_CMD_Search(cmd);
                Made_Grid(db_res);
            }
            
            Fill_textBox(0);
        }
        private void Made_Grid(string strValue)
        {
            dataGridView1.Rows.Clear();
            string[] dbdata = strValue.Split('|');
            string[] grid = { "", "", "", "", "",
                              "", "", "", "", "",
                              "", "", "", "", "",
                              "", "", "", "", "",
                              "", "", "" };
            int count = dbdata.Length;
            int ea = 0;
            for(int a = 0; a < count; a++)
            {
                if (a % 23 == ea) {
                    if (ea == 1) {
                        if (dbdata[a] == "0") { grid[ea] = ""; }
                        if (dbdata[a] == "1") { grid[ea] = "V"; }
                        ea++;
                    }
                    else if(ea == 14) {
                        if (dbdata[a] == "0") { grid[14] = "출판"; }
                        if (dbdata[a] == "1") { grid[14] = "도매"; }
                        if (dbdata[a] == "2") { grid[14] = "기타"; }
                        if (dbdata[a] == "3") { grid[14] = "경비"; }
                        ea++;
                    }
                    else if (ea == 22) { 
                        grid[ea] = dbdata[a];
                        dataGridView1.Rows.Add(grid);
                        ea = 0; 
                    }
                    else {
                        grid[ea] = dbdata[a];
                        ea++;
                    }
                }
            }
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            Fill_textBox(row);
        }
        void Fill_textBox(int row)
        {
            if (dataGridView1.RowCount <= 0) { return; }
            if (row < 0) { return; }
            btn_Add_Click(null, null);
            lbl_idx.Text = dataGridView1.Rows[row].Cells["idx"].Value.ToString();
            tb_sangho.Text = dataGridView1.Rows[row].Cells["sangho"].Value.ToString();
            tb_boss.Text = dataGridView1.Rows[row].Cells["boss"].Value.ToString();
            tb_bubin.Text = dataGridView1.Rows[row].Cells["bubin"].Value.ToString();
            tb_uptae.Text = dataGridView1.Rows[row].Cells["uptae"].Value.ToString();
            tb_jongmok.Text = dataGridView1.Rows[row].Cells["jongmok"].Value.ToString();
            tb_zip.Text = dataGridView1.Rows[row].Cells["zip"].Value.ToString();
            tb_addr.Text = dataGridView1.Rows[row].Cells["addr"].Value.ToString();
            tb_tel.Text = dataGridView1.Rows[row].Cells["tel"].Value.ToString();
            tb_fax.Text = dataGridView1.Rows[row].Cells["fax"].Value.ToString();
            tb_bank_no.Text = dataGridView1.Rows[row].Cells["bank_no"].Value.ToString();
            tb_bank_comp.Text = dataGridView1.Rows[row].Cells["bank_comp"].Value.ToString();
            tb_bank_name.Text = dataGridView1.Rows[row].Cells["bank_name"].Value.ToString();
            tb_barea.Text = dataGridView1.Rows[row].Cells["barea"].Value.ToString();

            string[] Search_data = { tb_sangho.Text, tb_boss.Text, tb_bubin.Text, tb_jongmok.Text, tb_zip.Text };
            string[] Where_col = { "sangho", "boss", "bubin", "jongmok", "zip" };
            string cmd = db.More_DB_Search("Purchase", Where_col, Search_data, "emchk");
            string db_res = db.DB_Send_CMD_Search(cmd);
            db_res = db_res.Replace("|", "");
            if (db_res == "0") {
                rtb_etc.Text = dataGridView1.Rows[row].Cells["etc_1"].Value.ToString();
                rtb_etc.Text += "\n" + dataGridView1.Rows[row].Cells["etc_2"].Value.ToString();
            }
            else
                rtb_etc.Text = dataGridView1.Rows[row].Cells["etc_1"].Value.ToString();

            tb_email.Text = dataGridView1.Rows[row].Cells["email"].Value.ToString();
            tb_id.Text = dataGridView1.Rows[row].Cells["id"].Value.ToString();
            tb_pw.Text = dataGridView1.Rows[row].Cells["pw"].Value.ToString();
            tb_site.Text = dataGridView1.Rows[row].Cells["site"].Value.ToString();

            if (dataGridView1.Rows[row].Cells["send_chk"].Value.ToString() == "") chk_send.Checked = false;
            if (dataGridView1.Rows[row].Cells["send_chk"].Value.ToString() == "V") chk_send.Checked = true;

            if (dataGridView1.Rows[row].Cells["emchk"].Value.ToString() == "0") chk_email.Checked = false;
            if (dataGridView1.Rows[row].Cells["emchk"].Value.ToString() == "1") chk_email.Checked = true;

            if (dataGridView1.Rows[row].Cells["gu"].Value.ToString() == "출판") cb_gubun.SelectedIndex = 0;
            if (dataGridView1.Rows[row].Cells["gu"].Value.ToString() == "도매") cb_gubun.SelectedIndex = 1;
            if (dataGridView1.Rows[row].Cells["gu"].Value.ToString() == "기타") cb_gubun.SelectedIndex = 2;
            if (dataGridView1.Rows[row].Cells["gu"].Value.ToString() == "경비") cb_gubun.SelectedIndex = 3;

            InputIndexWord();
        }
        /// <summary>
        /// 색인어 그리드 채우기
        /// </summary>
        private void InputIndexWord()
        {
            dgv_IndexWord.Rows.Clear();

            string Area = "`word`, `persent`";
            string[] Search_Col = {
                "compidx", "puridx"
            };
            string[] Search_Data = {
                PUB.user.CompanyIdx,
                lbl_idx.Text
            };
            
            string cmd = db.More_DB_Search("IndexWord", Search_Col, Search_Data, Area);
            string res = db.DB_Send_CMD_Search(cmd);

            string[] ary = res.Split('|');
            string[] grid = { "", "" };
            for (int a = 0; a < ary.Length; a++)
            {
                if (a % 2 == 0) { grid[0] = ary[a]; }
                if (a % 2 == 1) { grid[1] = ary[a];
                    dgv_IndexWord.Rows.Add(grid);
                }
            }
        }
        private void btn_Add_Click(object sender, EventArgs e)      // 추가
        {
            TextBox[] textBox = {
                tb_sangho, tb_boss, tb_bubin, tb_uptae, tb_jongmok,
                tb_zip, tb_addr, tb_tel, tb_fax, tb_bank_no, tb_bank_comp,
                tb_bank_name, tb_barea, tb_email, tb_id, tb_pw,
                tb_site
            };

            for (int a = 0; a < textBox.Length; a++)
                textBox[a].Text = "";

            rtb_etc.Text = "";
            cb_gubun.SelectedIndex = 0;
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
            {
                int row = dataGridView1.CurrentCell.RowIndex;
                if (e.KeyCode == Keys.Up && row > 0)
                {
                    row--;
                }
                if (e.KeyCode == Keys.Down && row < dataGridView1.RowCount - 1)
                {
                    row++;
                }
                Fill_textBox(row);
            }
        }
        private void btn_Save_Click(object sender, EventArgs e)     // 저장
        {
            string Table = "Purchase";
            string[] Search_Table = { "comparyidx", "idx" };
            string[] Search_Data = { PUB.user.CompanyIdx, lbl_idx.Text };

            bool Isinsert = false;
            string cmd = db.More_DB_Search(Table, Search_Table, Search_Data); 
            if (db.DB_Send_CMD_Search(cmd).Length < 30) { Isinsert = true; }

            string send_chk = "0";
            string emchk = "0";
            string gu = "";
            if (chk_send.Checked == true) { send_chk = "1"; }
            if (chk_email.Checked == true) { emchk = "1"; }
            if(cb_gubun.SelectedIndex == 0) { gu = "0"; }    // 출판
            if(cb_gubun.SelectedIndex == 1) { gu = "1"; }    // 도매
            if(cb_gubun.SelectedIndex == 2) { gu = "2"; }    // 기타
            if(cb_gubun.SelectedIndex == 3) { gu = "3"; }    // 경비
            string[] Insert_Table = {"send_chk", "sangho", "boss", "bubin", "uptae",  
                                     "jongmok", "zip", "addr", "tel", "fax", 
                                     "bank_no", "bank_comp", "bank_name", "gu", "barea", 
                                     "etc_1", "email", "id", "pw", "site", "emchk"};
            string[] Insert_Data = { send_chk, tb_sangho.Text, tb_boss.Text, tb_bubin.Text, tb_uptae.Text,
                                     tb_jongmok.Text, tb_zip.Text, tb_addr.Text, tb_tel.Text, tb_fax.Text,
                                     tb_bank_no.Text, tb_bank_comp.Text, tb_bank_name.Text, gu, tb_barea.Text,
                                     rtb_etc.Text, tb_email.Text, tb_id.Text, tb_pw.Text, tb_site.Text, emchk };
            if (Isinsert)
            {
                string Incmd = db.DB_INSERT("Purchase", Insert_Table, Insert_Data);
                Helper_DB.ExcuteNonQuery(Incmd);
                UTIL.MsgI(tb_sangho.Text + " 저장 완료");
            }
            else
            {
                string U_cmd = db.More_Update(Table, Insert_Table, Insert_Data, Search_Table, Search_Data);
                Helper_DB.ExcuteNonQuery(U_cmd);
                UTIL.MsgI(tb_sangho.Text + " 수정 완료");
            }
        }
        private void btn_Delete_Click(object sender, EventArgs e)   // 삭제
        {
            int row = dataGridView1.CurrentCell.RowIndex;

            string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();
            string sangho = dataGridView1.Rows[row].Cells["sangho"].Value.ToString();
            string D_cmd = db.DB_Delete("Purchase", "idx", idx, "sangho", sangho);
            Helper_DB.ExcuteNonQuery(D_cmd);
            UTIL.MsgI(sangho + " 삭제 완료");
        }
        private void tb_memo_Click(object sender, EventArgs e)
        {
            memo memo = new memo();
            memo.Show();
        }
        private void btn_SitePage_Click(object sender, EventArgs e)
        {
            string text = tb_site.Text;
            string[] before = { "네이버", "다음", "네이트" };
            string[] after = { "www.naver.com", "www.daum.net", "www.nate.com" };
            for(int a= 0; a < before.Length; a++)
            {
                if (text == before[a])
                    text = after[a];
            }
            try
            {
                System.Diagnostics.Process.Start(text);
            }
            catch (Exception ex)
            {
                UTIL.MsgE(ex.Message);
            }
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void tb_search_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                btn_Lookup_Click(null, null);
            }
        }
        private void chk_stopUse_CheckedChanged(object sender, EventArgs e)
        {
            if(chk_stopUse.Checked == true)
            {
                tb_sangho.Text += "-사용중지";
            }
            else if (chk_stopUse.Checked == false)
            {
                tb_sangho.Text = tb_sangho.Text.Replace("-사용중지", "");
            }
        }

        #region 색인어 관련

        private void btn_AddIW_Click(object sender, EventArgs e)
        {
            tb_IndexWord.Text = "";
            tb_persent.Value = 0;
        }

        private void btn_SaveIW_Click(object sender, EventArgs e)
        {
            // 사전준비
            string compidx = PUB.user.CompanyIdx;
            string puridx = lbl_idx.Text;
            string word = tb_IndexWord.Text;
            string persent = tb_persent.Value.ToString();

            IndexWordSavetoDB(compidx, puridx, word, persent);

            InputIndexWord();
        }

        private void IndexWordSavetoDB(string compidx, string puridx, string word, string persent)
        {
            // DB중복체크
            string Table = "IndexWord";
            string[] Search_Table = { "compidx", "puridx", "word" };
            string[] Search_Data = { compidx, puridx, word };

            bool IsInsert = false;
            string cmd = db.More_DB_Search(Table, Search_Table, Search_Data);
            if (db.DB_Send_CMD_Search(cmd).Length < 5) IsInsert = true;

            string[] Insert_Col = { "compidx", "puridx", "word", "persent" };
            string[] Insert_Data = { compidx, puridx, word, persent };

            string InCmd = "";
            if (IsInsert)
                InCmd = db.DB_INSERT("IndexWord", Insert_Col, Insert_Data);
            else
                InCmd = db.More_Update(Table, Insert_Col, Insert_Data, Search_Table, Search_Data);

            Helper_DB.ExcuteNonQuery(InCmd);
        }

        private void btn_ExcelIW_Click(object sender, EventArgs e)
        {
            // ????
        }

        private void btn_DeleteIW_Click(object sender, EventArgs e)
        {
            int row = dgv_IndexWord.CurrentRow.Index;

            string puridx = lbl_idx.Text;
            string word = dgv_IndexWord.Rows[row].Cells["IndexWord"].Value.ToString();
            string persent = dgv_IndexWord.Rows[row].Cells["IndexPersent"].Value.ToString();

            string cmd = string.Format(
                "DELETE FROM `{0}` " +
                "WHERE `{1}` = \"{2}\" " +
                  "AND `{3}` = \"{4}\" " +
                  "AND `{5}` = \"{6}\" " +
                  "AND `{7}` = \"{8}\" " +
                "LIMIT 1;", 
                "IndexWord", 
                "compidx", PUB.user.CompanyIdx, 
                "puridx", puridx,
                "word", word,
                "persent", persent);

            // MessageBox.Show(cmd); // Debugging code, commenting out or replacing
            // UTIL.MsgI(cmd); 


            Helper_DB.ExcuteNonQuery(cmd);
            dgv_IndexWord.Rows.RemoveAt(row);
        }

        #endregion

        private void tb_IndexWord_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                tb_persent.Focus();
            }
        }

        private void tb_persent_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                btn_SaveIW.Focus();
            }
        }

        private void dgv_IndexWord_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (row < 0) return;

            tb_IndexWord.Text = dgv_IndexWord.Rows[row].Cells["IndexWord"].Value.ToString();
            tb_persent.Value = Convert.ToInt32(dgv_IndexWord.Rows[row].Cells["IndexPersent"].Value.ToString());
        }

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

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

        #region 색인어 일괄입력

        private void btn_batchProcess_Click(object sender, EventArgs e)
        {
            if (panel_batchProcess.Visible)
                panel_batchProcess.Visible = false;
            else
                panel_batchProcess.Visible = true;
        }

        private void btn_batchProcessing_Click(object sender, EventArgs e)
        {
            int count = dgv_WordSUB.RowCount;

            string compidx = PUB.user.CompanyIdx;
            string puridx = lbl_idx.Text;
            for (int a = 0; a < count; a++)
            {
                if (dgv_WordSUB.Rows[a].Cells["IndexWordSub"].Value.ToString() == "" ||
                    dgv_WordSUB.Rows[a].Cells["IndexWordSub"].Value == null) break;

                string word = dgv_WordSUB.Rows[a].Cells["IndexWordSub"].Value.ToString();
                string persent = dgv_WordSUB.Rows[a].Cells["IndexPersentSub"].Value.ToString();

                IndexWordSavetoDB(compidx, puridx, word, persent);
            }
            InputIndexWord();
        }

        private void btn_ProcessExit_Click(object sender, EventArgs e)
        {
            panel_batchProcess.Visible = false;
        }
        #endregion
    }
}
