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.Windows.Forms.VisualStyles;
using WindowsFormsApp1.Home;
namespace WindowsFormsApp1.Delivery
{
    public partial class Purchase : Form
    {
        Helper_DB db = new Helper_DB();
        String_Text st = new String_Text();
        Main main;
        public string compidx;
        public int grididx;
        bool chk_inven = false;
        int grid3Row = 0;
        public Purchase(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = main.com_idx;
        }
        private void Purchase_Load(object sender, EventArgs e)
        {
            db.DBcon();
            cb_charge.Items.Add("전체");
            string[] user_tmp = main.DB_User_Data.Split('|');
            string cmd = db.self_Made_Cmd("SELECT `name` FROM `User_Data` WHERE `affil` = '" + user_tmp[5] + "';");
            string[] user_name = cmd.Split('|');
            for (int a = 0; a < user_name.Length; a++) {
                if (a == user_name.Length - 1) { break; }
                cb_charge.Items.Add(user_name[a]);
            }
            cb_charge.SelectedIndex = 0;
        }
        /// 
        /// 텍스트박스 키다운
        /// 
        /// 
        /// 
        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                if (((TextBox)sender).Name == "tb_clt") {
                    Commodity_Search sea = new Commodity_Search(this);
                    sea.Clinet_name = tb_clt.Text;
                    sea.Show();
                }
                else {
                    Made_Grid(((TextBox)sender).Text, ((TextBox)sender).Name);
                }
            }
        }
        public void Made_Grid(string Text, string Name)
        {
            dataGridView1.Rows.Clear();
            string Area = "`header`, `num`, `count`, `book_name`, `book_comp`, " +
                          "`author`, `pay`, `total`, `list_name`, `etc`, " +
                          "`order`, `isbn`, `order_date`";
            if (Name == "tb_clt" || Name == "tb_dly") {
                string tabel = "`list_name`, `clt`, `dly`";
                string[] Where = { "comp_num" };
                string[] data = { compidx };
                string tmp = db.More_DB_Search("Obj_List", Where, data, tabel);
                string[] db_ori = tmp.Split('|');
                // TODO : 거래처명 중복으로 된 경우 중복된 목록 다 검색이 되도록 할것. (납품처도 동일)
                string[] tmp_data = { "", "", "" };
                for (int a = 0; a < db_ori.Length; a++)
                {
                    if (a % 3 == 0) { tmp_data[0] = db_ori[a]; }
                    if (a % 3 == 1) { tmp_data[1] = db_ori[a]; }
                    if (a % 3 == 2) { tmp_data[2] = db_ori[a];
                        if (Name == "tb_clt" && tmp_data[1].Contains(Text) == true) {
                            string[] table = { "compidx", "list_name", "import" };
                            string[] sear_data = { compidx, tmp_data[0], "미입고" };
                            string tmp_db = db.More_DB_Search("Obj_List_Book", table, sear_data, Area);
                            Insert_Grid(tmp_db);
                        }
                        else if (Name == "tb_dly" && tmp_data[2].Contains(Text) == true) {
                            string[] table = { "compidx", "list_name", "import" };
                            string[] sear_data = { compidx, tmp_data[0], "미입고" };
                            string tmp_db = db.More_DB_Search("Obj_List_Book", table, sear_data, Area);
                            Insert_Grid(tmp_db);
                        }
                    }
                }
            }
            else if (Name == "tb_order") {
                string tmp_db = db.DB_Contains("Obj_List_Book", compidx, "`order`", Text, Area, "import", "미입고");
                Insert_Grid(tmp_db);
            }
            else if (Name == "tb_isbn") {
                string tmp_db = db.DB_Contains("Obj_List_Book", compidx, "isbn", Text, Area, "import", "미입고");
                Insert_Grid(tmp_db);
                if (dataGridView1.Rows.Count == 1) {
                    dataGridView1_CellDoubleClick(null, null);
                }
            }
            else if (Name == "tb_book_name") {
                string tmp_db = db.DB_Contains("Obj_List_Book", compidx, "book_name", Text, Area, "import", "미입고");
                Insert_Grid(tmp_db);
            }
            else if (Name == "tb_book_comp") {
                string tmp_db = db.DB_Contains("Obj_List_Book", compidx, "book_comp", Text, Area, "import", "미입고");
                Insert_Grid(tmp_db);
            }
        }
        private void Insert_Grid(string db_data)
        {
            string[] data = db_data.Split('|');
            string[] add_data = {"", "", "", "", "",
                                 "", "", "", "", "",
                                 "입고", "", "" };
            /* 0 1 2 3 4 
             * 5 6 7 8 9
             * 10 11 12 */
            for (int a = 0; a < data.Length; a++)
            {
                if (a % 13 == 01) { add_data[00] = data[a - 1] + " " + data[a]; }
                if (a % 13 == 02) { add_data[01] = data[a]; }
                if (a % 13 == 03) { add_data[02] = data[a]; }
                if (a % 13 == 04) { add_data[03] = data[a]; }
                if (a % 13 == 05) { add_data[04] = data[a]; }
                if (a % 13 == 06) { add_data[05] = data[a]; }
                if (a % 13 == 07) { add_data[06] = data[a]; }
                if (a % 13 == 08) { add_data[07] = data[a]; }
                if (a % 13 == 09) { add_data[08] = data[a]; }
                if (a % 13 == 10) { add_data[09] = data[a]; }
                if (a % 13 == 11) { add_data[11] = data[a].Replace("\r", string.Empty); }
                if (a % 13 == 12) {
                    add_data[12] = data[a];
                    if (chk_order_book.Checked == true && data[a] != "") {
                        dataGridView1.Rows.Add(add_data);
                    }
                    else if (chk_order_book.Checked == false) {
                        dataGridView1.Rows.Add(add_data);
                    }
                }
            }
            lbl_grid.Text = "목록 수 : " + dataGridView1.Rows.Count.ToString();
            lbl_count.Text = "권 수 : " + Book_Count();
        }
        private string Book_Count()
        {
            int result = 0;
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                result += Convert.ToInt32(dataGridView1.Rows[a].Cells["count"].Value.ToString());
            }
            return result.ToString();
        }
        private void Grid2_Book_Count()
        {
            int result = 0;
            for(int a= 0; a < dataGridView2.Rows.Count; a++)
            {
                result += Convert.ToInt32(dataGridView2.Rows[a].Cells["count2"].Value.ToString());
            }
            lbl_grid2.Text = "입고 수 : " + dataGridView2.Rows.Count.ToString();
            lbl_count2.Text = "권 수 : " + result.ToString();
        }
        private void Grid3_Book_Count()
        {
            double result = 0;
            for(int a= 0; a < dataGridView3.Rows.Count-1; a++)
            {
                if (dataGridView3.Rows[a].IsNewRow == true) { return; }
                if (dataGridView3.Rows[a].Cells["total3"].Value != null || 
                    dataGridView3.Rows[a].Cells["total3"].Value.ToString() != "") {
                    result += Convert.ToDouble(dataGridView3.Rows[a].Cells["total3"].Value.ToString());
                }
            }
            int count = dataGridView3.Rows.Count - 1;
            
            lbl_grid3.Text = "입고 수 : " + count.ToString();
            lbl_total3.Text = "입고 금액 : " + Math.Round(result).ToString();
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int col, row;
            string name = "";
            if (sender == null || e == null) { 
                grididx = 0;
                row = grididx;
                col = 10;
                name = "dataGridView1";
            }
            else { 
                grididx = e.RowIndex;
                row = e.RowIndex;
                col = e.ColumnIndex;
                name = ((DataGridView)sender).Name;
            }
            if (name == "dataGridView1" && col == 10) {
                if(tb_persent.Text == "") {
                    MessageBox.Show("매입율을 작성해주세요.");
                    tb_persent.Focus();
                }
                else {
                    press_Grid1_Btn(row, col);
                }
            }
            else if (name == "dataGridView2" && col == 10) {
                press_Grid2_Btn(e);
            }
            else {
                int select = 0;
                if (name == "dataGridView1") { select = 0; }
                else if (name == "dataGridView2") { select = 1; }
                Book_Lookup bl = new Book_Lookup(this);
                string[] cells_name1 = { "Book_name", "Book_name2" };
                string[] cells_name2 = { "author", "author2" };
                string[] cells_name3 = { "Book_comp", "Book_comp2" };
                string[] cells_name4 = { "list_name", "list_name2" };
                bl.TopMost = true;
                string book_name = ((DataGridView)sender).Rows[row].Cells[cells_name1[select]].Value.ToString();
                string author = ((DataGridView)sender).Rows[row].Cells[cells_name2[select]].Value.ToString();
                string book_comp = ((DataGridView)sender).Rows[row].Cells[cells_name3[select]].Value.ToString();
                string list_name = ((DataGridView)sender).Rows[row].Cells[cells_name4[select]].Value.ToString();
                bl.Lookup_Load(book_name, author, book_comp, list_name);
                bl.Show();
            }
            // 로컬파일 생성. (C:\)
            create_TempTxt();
        }
        private void create_TempTxt()
        {
            //FileInfo file = new FileInfo(Application.StartupPath + "\\temp\\temp.txt");
            DirectoryInfo di = new DirectoryInfo("C:\\unimarc");
            if (di.Exists == false)
            {
                di.Create();
            }
            FileInfo file = new FileInfo("C:\\unimarc\\temp.txt");
            FileStream fs;
            if (!file.Exists) { // 해당 파일이 없을 경우 생성하고 파일 닫기
                fs = file.Create();
                fs.Close();
            }
            // 해당 파일의 내용을 저장하고자 할 때(기존 내용 초기화)
            fs = file.OpenWrite();
            TextWriter tw = new StreamWriter(fs);
            tw.Write(made_txt_string());
            tw.Close();
            fs.Close();
        }
        private string made_txt_string()
        {
            string result = "";
            for(int a = 0; a < dataGridView3.Rows.Count - 1; a++)
            {
                for(int b = 0; b < dataGridView3.Columns.Count; b++)
                {
                    if (dataGridView3.Rows[a].Cells[b].Value == null) {
                        dataGridView3.Rows[a].Cells[b].Value = "";
                    }
                    result += dataGridView3.Rows[a].Cells[b].Value.ToString() + "\t";
                }
                // 맨 마지막의 경우 이상한 숫자가 찍히므로 아래 if문으로 예외처리
                if (dataGridView3.Rows[a].Cells["total3"].Value.ToString() == "") {
                    return result;
                }
                result += "\n";
            }
            return result;
        }
        private void load_tmplist_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일(*.*)|*.*";
            string file_con = null;
            string file_path = "C:\\unimarc\\temp.txt";
            if (File.Exists(file_path))
            {
                using (StreamReader sr = new StreamReader(file_path, Encoding.UTF8))
                {
                    // 불러온 파일의 내용을 표에 적용
                    string[] Cell_result = null;
                    string[] collumn_result;
                    file_con = sr.ReadToEnd();
                    Cell_result = file_con.Split('\n');
                    for (int a = 0; a < Cell_result.Length-1; a++)
                    {
                        collumn_result = Cell_result[a].Split('\t');
                        dataGridView3.Rows.Add();
                        for (int b = 0; b < collumn_result.Length-1; b++)
                        {
                            dataGridView3.Rows[a].Cells[b].Value = collumn_result[b];
                        }
                    }
                }
            }
            else { MessageBox.Show("임시 저장된 데이터가 없습니다.", "에러", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        }
        private void btn_lookup_Click(object sender, EventArgs e)
        {
            dataGridView2.Rows.Clear();
            string start = startTime.Value.ToString().Substring(0, 10);
            string end = endTime.Value.ToString().Substring(0, 10);
            string _Table = "`header`, `num`, `count`, `book_name`, `book_comp`, " +
                            "`author`, `pay`, `total`, `list_name`, `etc`, " +
                            "`order`, `import_date`";
            // 날짜 구분
            string search_Table = "`list_name`, `charge`";
            string tmp = db.Search_Date("Obj_List", search_Table, "date", start, end, compidx);
            string[] tp = tmp.Split('|');
            for (int a = 0; a < tp.Length; a++) {
                if (cb_charge.SelectedIndex != 0 && tp[a] == cb_charge.Text) {
                    if (a % 2 == 1) {
                        string[] Where = { "list_name", "import", "compidx" };
                        string[] Search = { tp[a - 1], "입고", compidx };
                        string db_tmp = db.More_DB_Search("Obj_List_Book", Where, Search, _Table);
                        mk_grid(db_tmp);
                    }
                }
                else if (cb_charge.SelectedIndex == 0) {
                    if (a % 2 == 1) {
                        string[] Where = { "list_name", "import", "compidx" };
                        string[] Search = { tp[a - 1], "입고", compidx };
                        string db_tmp = db.More_DB_Search("Obj_List_Book", Where, Search, _Table);
                        mk_grid(db_tmp);
                    }
                }
            }
        }
        private void mk_grid(string value)
        {
            string[] db_data = value.Split('|');
            string[] result = { "", "", "", "", "",
                                "", "", "", "", "", "취소", "", "O" };
           /* 번호 수량 도서명 출판사 저자
            * 단가 합계 구분 비고 주문처명
            */
            for (int b = 0; b < db_data.Length; b++) {
                if (b % 12 == 01) { result[0] = db_data[b - 1] + " " + db_data[b]; }
                if (b % 12 == 02) { result[1] = db_data[b]; }
                if (b % 12 == 03) { result[2] = db_data[b]; }
                if (b % 12 == 04) { result[3] = db_data[b]; }
                if (b % 12 == 05) { result[4] = db_data[b]; }
                if (b % 12 == 06) { result[5] = db_data[b]; }
                if (b % 12 == 07) { result[6] = db_data[b]; }
                if (b % 12 == 08) { result[7] = db_data[b]; }
                if (b % 12 == 09) { result[8] = db_data[b]; }
                if (b % 12 == 10) { result[9] = db_data[b]; }
                if (b % 12 == 11) { result[11] = db_data[b];
                    if (tb_book_name.Text != "") {
                        if (result[2].Contains(tb_book_name.Text) != true) { continue; }
                    }
                    if (tb_book_comp.Text != "") {
                        if (result[3].Contains(tb_book_comp.Text) != true) { continue; }
                    }
                    dataGridView2.Rows.Add(result);
                }
            }
        }
        private void press_Grid1_Btn(int row, int col)
        {
            /* 번호 수량 도서명 출판사 저자
             * 단가 합계 구분 비고 주문처명 
             * btn취소 isbn 입고시간 */
            string[] grid2 = {"", "", "", "", "",
                              "", "", "", "", "", 
                              "취소", "", System.DateTime.Now.ToString("g")};
            /* 번호 수량 도서명 출판사 저자
             * 정가 매입율 합계 비고 구분
             * 주문처 날짜 isbn */
            string[] grid3 = {"", "", "", "", "",
                              "0", "", "", "", "", 
                              "", System.DateTime.Now.ToString("g"), ""};
            if(row < 0 || col < 0) {
                return;
            }
            for(int a = 0; a < 10; a++)
            {
                if(dataGridView1.Rows.Count <= 0) {
                    return;
                }
                grid2[a] = dataGridView1.Rows[row].Cells[a].Value.ToString();
                if (a == 1) {
                    grid2[a] = "1";
                }
            }
            grid2[11] = dataGridView1.Rows[row].Cells[11].Value.ToString();
            Grid2Count(grid2, row, col);   // 책 중복시
            Grid3_Pay_Count(grid2[9]);
            grid3[0] = dataGridView1.Rows[row].Cells[0].Value.ToString();
            grid3[1] = "1";
            grid3[2] = dataGridView1.Rows[row].Cells[2].Value.ToString();
            grid3[3] = dataGridView1.Rows[row].Cells[3].Value.ToString();
            grid3[4] = dataGridView1.Rows[row].Cells[4].Value.ToString();
            string isbn_chk = dataGridView1.Rows[row].Cells[11].Value.ToString().Replace("\r", string.Empty);
            grid3[5] = dataGridView1.Rows[row].Cells[5].Value.ToString();
            grid3[8] = dataGridView1.Rows[row].Cells[8].Value.ToString();
            if (chk_stock.Checked == true) {
                if (stock_chk(isbn_chk) == true) {
                    int inven_count = stock_count_chk(isbn_chk);
                    MessageBox.Show(inven_count.ToString());
                    if (lbl_inven_count.Text == "0") {
                        lbl_inven_count.Text = "0";
                        inven_count = 0;
                        grid3[5] = dataGridView1.Rows[row].Cells[5].Value.ToString();
                    }
                    if (inven_count > 0) {
                        if (lbl_inven_count.Text != "-1") { inven_count = Convert.ToInt32(lbl_inven_count.Text); }
                        grid3[5] = "0";
                        grid3[8] = "재고";
                        inven_count--;
                        lbl_inven_count.Text = inven_count.ToString();
                    }
                }
            }
            grid3[6] = tb_persent.Text;
            int count = Convert.ToInt32(grid3[1]);
            int pay = Convert.ToInt32(grid3[5]);
            int persent = Convert.ToInt32(grid3[6]);
            double total = pay * persent * 0.01 * count;
            grid3[7] = total.ToString();
            grid3[9] = dataGridView1.Rows[row].Cells[7].Value.ToString();
            grid3[10] = dataGridView1.Rows[row].Cells[9].Value.ToString();
            grid3[12] = dataGridView1.Rows[row].Cells[11].Value.ToString();
            Grid3Count(grid3, row, col);
            dataGridView1.Rows.RemoveAt(row);
        }
        private int stock_count_chk(string isbn)
        {
            string Area = "`count`";
            string[] table = { "compidx", "isbn" };
            string[] colum = { compidx, isbn.Replace("\r", string.Empty) };
            string tmp = db.More_DB_Search("Inven", table, colum, Area);
            string[] inven_count = tmp.Split('|');
            string msg = "";
            for(int a = 0; a < inven_count.Length; a++)
            {
                msg += inven_count[a] + " ";
            }
            int count = -1;
            if (inven_count[0] != "")
            {
                count = Convert.ToInt32(inven_count[0]);
            }
            return count;
        }
        /// 
        /// 매입처의 미수금 금액이 표출됨.
        /// 
        /// 
        private void Grid3_Pay_Count(string order)
        {
            string Search_table = "`buy_money`, `payment`";
            string[] Where_table = { "compidx", "purchase" };
            string[] Where_col = { compidx, order };
            string db_tmp = db.More_DB_Search("Buy_ledger", Where_table, Where_col, Search_table);
            string[] db_data = db_tmp.Split('|');
            int buy = 0, pay = 0;
            int result = 0;
            for(int a = 0; a < db_data.Length - 1; a++)
            {
                if (a % 2 == 0) { buy = Convert.ToInt32(db_data[a]); }
                if (a % 2 == 1) { pay = Convert.ToInt32(db_data[a]);
                    result += buy - pay;
                }
            }
            lbl_pay.Text = order + " : " + result.ToString();
        }
        private void Grid2Count(string[] mkgrid, int row, int col)
        {
            int rowCount = dataGridView2.Rows.Count;
            bool chk = false;
            if (rowCount <= 0) {
                dataGridView2.Rows.Add(mkgrid);
                Grid2_Book_Count();
                return;
            }
            for(int a = 0; a < rowCount; a++)
            {
                // 2: 도서명 / 3: 출판사 / 4: 저자 / 7: 구분
                if (mkgrid[2] == dataGridView2.Rows[a].Cells[2].Value.ToString() && 
                    mkgrid[3] == dataGridView2.Rows[a].Cells[3].Value.ToString() &&
                    mkgrid[4] == dataGridView2.Rows[a].Cells[4].Value.ToString() &&
                    mkgrid[7] == dataGridView2.Rows[a].Cells[7].Value.ToString()) {
                    string invenCount_tmp = dataGridView2.Rows[a].Cells[1].Value.ToString();
                    int invenCount = Convert.ToInt32(invenCount_tmp);
                    invenCount++;
                    chk = true;
                    int money = Convert.ToInt32(mkgrid[5]);
                    int totaltmp = invenCount * money;
                    mkgrid[6] = totaltmp.ToString();
                    dataGridView2.Rows[a].Cells[1].Value = invenCount.ToString();
                    dataGridView2.Rows[a].Cells[6].Value = mkgrid[6];
                    break;
                }
            }
            if (chk == false) {
                dataGridView2.Rows.Add(mkgrid);
            }
            Grid2_Book_Count();
        }
        private void Grid3Count(string[] grid, int row, int col)
        {
            int rowCount = dataGridView3.Rows.Count-1;
            bool chk = false;
            if (rowCount <= 0) {
                dataGridView3.Rows.Add(grid);
                Grid3_Book_Count();
                return;
            }
            for(int a = 0; a < rowCount; a++)
            {
                // 0:번호 / 2:도서명 / 3:출판사 / 4:저자 / 5:정가 / 6:매입율
                if (grid[2] == dataGridView3.Rows[a].Cells[2].Value.ToString() &&
                    grid[3] == dataGridView3.Rows[a].Cells[3].Value.ToString() &&
                    grid[4] == dataGridView3.Rows[a].Cells[4].Value.ToString() &&
                    grid[5] == dataGridView3.Rows[a].Cells[5].Value.ToString() &&
                    grid[6] == dataGridView3.Rows[a].Cells[6].Value.ToString()) {
                    
                    string invenCount_tmp = dataGridView3.Rows[a].Cells[1].Value.ToString();
                    int invenCount = Convert.ToInt32(invenCount_tmp);
                    invenCount++;
                    chk = true;
                    int pay = Convert.ToInt32(grid[5]);
                    int persent = Convert.ToInt32(grid[6]);
                    double total = pay * persent * 0.01 * invenCount;
                    grid[7] = total.ToString();
                    dataGridView3.Rows[a].Cells[1].Value = invenCount.ToString();
                    dataGridView3.Rows[a].Cells[7].Value = grid[7];
                    break;
                }
            }
            if (chk == false) {
                dataGridView3.Rows.Add(grid);
            }
            Grid3_Book_Count();
        }
        private void input_Inven(int data, int row_count)
        {
            string Search_Table = "`compidx`, `list_name`, `header`, `num`, `book_name`, " +
                                  "`author`, `book_comp`, `count`, `pay`, " + //`persent`, " +
                                  "`total`, `etc`, `isbn`, `order`, `order_stat`, " +
                                  "`order_date`, `send_date`, `stat`, `chk_date`, `import`, " +
                                  "`import_date`, `export`, `export_date`";
            string[] Where_Table = { "compidx", "book_name", "author", "book_comp", "list_name" };
            string[] Search_Data = { compidx, 
                                     dataGridView2.Rows[row_count].Cells["Book_name2"].Value.ToString(),
                                     dataGridView2.Rows[row_count].Cells["author2"].Value.ToString(),
                                     dataGridView2.Rows[row_count].Cells["Book_comp2"].Value.ToString(),
                                     dataGridView2.Rows[row_count].Cells["list_name2"].Value.ToString() };
            string db_tmp_data = db.More_DB_Search("Obj_List_Book", Where_Table, Search_Data, Search_Table);
            string[] db_data = db_tmp_data.Split('|');
            string[] input_data = { "", "", "", "", "",
                                    "", "", "", "", //"",
                                    "", "", "", "", "",
                                    "", "", "", "", "",
                                    "", "", "" };
            string[] input_col = { "compidx", "list_name", "header", "num", "book_name",
                                   "author", "book_comp", "count", "pay", //"persent",
                                   "total", "etc", "isbn", "order", "order_stat",
                                   "order_date", "send_date", "stat", "chk_date", "import",
                                   "import_date", "export", "export_date" };
            // 마지막 공란 제거 for문
            for(int a= 0; a < db_data.Length-1; a++)
            {
                input_data[a] = db_data[a];
                if (a == 3) input_data[a] = data.ToString();
            }
            // Inven테이블내 데이터중복체크
            string[] chk_Table = { "book_name", "author", "book_comp", "isbn" };
            string[] chk_Data = { db_data[4], db_data[5], db_data[6], db_data[12] };
            string chk = db.More_DB_Search("Inven", chk_Table, chk_Data);
            // 중복데이터가 검색되지않음.
            if (chk.Length < 3) {
                db.DB_INSERT("Inven", input_col, input_data);
                MessageBox.Show("DB 새로 추가");
                return;
            }
            else {
                string count_tmp = db.More_DB_Search("Inven", Where_Table, Search_Data, "`count`, `idx`");
                string[] cout = count_tmp.Split('|');
                int count = Convert.ToInt32(cout[1]);
                count += data;
                MessageBox.Show("DB 수정");
                db.DB_Update("Inven", "count", count.ToString(), "idx", cout[0]);
            }
        }
        private void press_Grid2_Btn(DataGridViewCellEventArgs e)
        {
            string number = dataGridView2.Rows[e.RowIndex].Cells["num2"].Value.ToString();
            string Area = "`header`, `num`, `count`, `book_name`, `book_comp`, " +
                          "`author`, `pay`, `total`, `list_name`, `etc`, " +
                          "`order`, `order_date`";
            string[] Table = { "book_name", "book_comp", "author", "list_name" };
            string[] Data = { dataGridView2.Rows[e.RowIndex].Cells["book_name2"].Value.ToString(),
                              dataGridView2.Rows[e.RowIndex].Cells["book_comp2"].Value.ToString(),
                              dataGridView2.Rows[e.RowIndex].Cells["author2"].Value.ToString(),
                              dataGridView2.Rows[e.RowIndex].Cells["list_name2"].Value.ToString() };
            string db_data = db.More_DB_Search("Obj_List_Book", Table, Data, Area);
            Insert_Grid(db_data);
            for(int a = 0; a < dataGridView3.Rows.Count-1; a++)
            {
                if (dataGridView3.Rows[a].Cells["book_name3"].Value.ToString() == Data[0] && 
                    dataGridView3.Rows[a].Cells["book_comp3"].Value.ToString() == Data[1] &&
                    dataGridView3.Rows[a].Cells["author3"].Value.ToString() == Data[2]) {
                    int count = Convert.ToInt32(dataGridView3.Rows[a].Cells["count3"].Value.ToString());
                    count--;
                    if(count == 0) {
                        dataGridView3.Rows.RemoveAt(a);
                    }
                    else if(count > 0) {
                        dataGridView3.Rows[a].Cells["count3"].Value = count.ToString();
                    }
                }
            }
            dataGridView2.Rows.RemoveAt(e.RowIndex);
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void tb_persent_KeyPress(object sender, KeyPressEventArgs e)
        {
            st.Only_Int(sender, e);
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            for(int a = 0; a < dataGridView2.Rows.Count; a++) {
                string[] search_Col = { "book_name", "book_comp", "author", "list_name" };
                string[] search_Data = { dataGridView2.Rows[a].Cells["Book_name2"].Value.ToString(), 
                                         dataGridView2.Rows[a].Cells["Book_comp2"].Value.ToString(), 
                                         dataGridView2.Rows[a].Cells["author2"].Value.ToString(), 
                                         dataGridView2.Rows[a].Cells["list_name2"].Value.ToString() };
                string[] edit_Col = { "import", "import_date", "isbn_import" };
                string[] edit_Data = { "입고", dataGridView2.Rows[a].Cells["Date"].Value.ToString(), 
                                       dataGridView2.Rows[a].Cells["isbn2"].Value.ToString() };
                db.More_Update("Obj_List_Book", edit_Col, edit_Data, search_Col, search_Data);
            }
            // 입고작업을 하려는 책이 재고에 있을 경우, 재고 -1이 되어야함.
            /* 만약 재고수보다 입고수가 더 많을경우는?
             * 1. 재고수량이 0이 되며, 나머지값을 매입원장에 기입. 
             * (재고1, 입고필요수량3 일 경우 재고는 사라지고, 매입원장에 2권분량의 값이 들어가야함.) */
            
            save_grid2();
            save_grid3();
            input_ledger();
        }
        /// 
        /// 매입원장에 추가하는 함수
        /// 
        private void input_ledger() // 무조건 INSERT문이 들어가게 됨.
        {
            //              회사인덱스번호   거래처명     매입일자    내용(도서명)    수량
            string[] Area = {"compidx", "purchase", "buy_date", "book_name", "count",
            //                 입고율      매입금액      결제금액     현잔액    비고
                             "persent", "buy_money", "payment", "remain", "etc" };
            for (int a = 0; a < dataGridView3.Rows.Count - 1; a++)
            {
                string[] insert_sub = { dataGridView3.Rows[a].Cells["book_name3"].Value.ToString(),
                                        dataGridView3.Rows[a].Cells["book_comp3"].Value.ToString(),
                                        dataGridView3.Rows[a].Cells["author3"].Value.ToString() };
                string[] tata = ledger_sub(a, insert_sub[0], insert_sub[1], insert_sub[2]);
                if (chk_stock.Checked == true) {
                    // 매입금액 0으로 초기화, 비고칸에 재고로 들어간거 확인을 위해 추가함.
                    tata[6] = "0";
                    tata[9] = "재고가감";
                }
                db.DB_INSERT("Buy_ledger", Area, tata);
            }
        }
        private bool stock_chk(string isbn)
        {
            string Area = "`isbn`";
            string[] table = { "compidx" };
            string[] colum = { compidx };
            string tmp = db.More_DB_Search("Inven", table, colum, Area);
            string[] inven_isbn = tmp.Split('|');
            for (int a= 0; a < inven_isbn.Length - 1; a++)
            {
                inven_isbn[a] = inven_isbn[a].Replace("\r", string.Empty);
            }
            for(int a = 0; a < inven_isbn.Length - 1; a++)
            {
                if (isbn == inven_isbn[a]) { return true; }
            }
            return false;
        }
        /// 
        /// input_ledger를 도와주는 함수
        /// 
        /// 입력할 표의 행번호
        /// 행번호에 위치한 도서명
        /// 행번호에 위치한 출판사
        /// 행번호에 위치한 저자
        /// input_ledger에 Area배열에 맞춰 DB에 INSERT할 데이터의 배열값 반환
        private string[] ledger_sub(int count, string book_name, string book_comp, string author)
        {
            string[] result = { "", "", "", "", "0",
                                "0", "0", "0", "0", "" };
            if (book_name == "" || book_comp == "" || author == "") {
                for (int a = count; a > 0; a--)
                {
                    if (dataGridView2.Rows[a].Cells["order2"].Value.ToString() != "") {
                        result[0] = compidx;
                        result[1] = dataGridView3.Rows[count].Cells["Order3"].Value.ToString();
                        result[7] = dataGridView3.Rows[count].Cells["total3"].Value.ToString();
                        if (Convert.ToInt32(result[7]) < 0) {
                            int tmp7 = Convert.ToInt32(result[7]) * -1;
                            result[7] = tmp7.ToString();
                        }
                        return result;
                    }
                }
            }
            for (int a = 0; a < dataGridView3.Rows.Count - 1; a++)
            {
                if (dataGridView3.Rows[a].Cells["book_name3"].Value.ToString() == book_name &&
                    dataGridView3.Rows[a].Cells["book_comp3"].Value.ToString() == book_comp &&
                    dataGridView3.Rows[a].Cells["author3"].Value.ToString() == author)
                {
                    result[0] = compidx;
                    result[1] = dataGridView3.Rows[a].Cells["Order3"].Value.ToString();
                    result[2] = dataGridView3.Rows[a].Cells["Date3"].Value.ToString();
                    result[3] = dataGridView3.Rows[a].Cells["book_name3"].Value.ToString();
                    result[4] = dataGridView3.Rows[a].Cells["count3"].Value.ToString();
                    result[5] = dataGridView3.Rows[a].Cells["persent"].Value.ToString();
                    result[6] = dataGridView3.Rows[a].Cells["total3"].Value.ToString();
                    result[9] = dataGridView3.Rows[a].Cells["etc3"].Value.ToString();
                    break;
                }
            }
            return result;
        }
        /// 
        /// 목록도서DB 안의 입고수량 수정하는 함수
        /// 
        private void save_grid2()
        {
            for(int a= 0; a < dataGridView2.Rows.Count; a++)
            {
                string[] grid2 = { dataGridView2.Rows[a].Cells["num2"].Value.ToString(),        // 번호
                                   dataGridView2.Rows[a].Cells["count2"].Value.ToString(),      // 수량
                                   dataGridView2.Rows[a].Cells["Book_name2"].Value.ToString(),  // 도서명
                                   dataGridView2.Rows[a].Cells["Book_comp2"].Value.ToString(),  // 출판사
                                   dataGridView2.Rows[a].Cells["author2"].Value.ToString(),     // 저자
                                   dataGridView2.Rows[a].Cells["pay2"].Value.ToString(),        // 단가
                                   dataGridView2.Rows[a].Cells["total2"].Value.ToString(),      // 합계
                                   dataGridView2.Rows[a].Cells["list_name2"].Value.ToString(),  // 구분
                                   dataGridView2.Rows[a].Cells["edasd"].Value.ToString(),       // 비고
                                   dataGridView2.Rows[a].Cells["order2"].Value.ToString(),      // 주문처명
                                   dataGridView2.Rows[a].Cells["Date"].Value.ToString() };      // 입고시간
                string[] Search_col = { "compidx", "book_name", "book_comp", "author", "list_name" };
                string[] Search_data = { compidx, grid2[2], grid2[3], grid2[4], grid2[7] };
                string tmp_db = db.More_DB_Search("Obj_List_Book", Search_col, Search_data, "`count`");
                string[] db_data = tmp_db.Split('|');
                
                string[] Edit_col = { "input_count" };
                string[] Edit_data = { Inven_count(db_data[0],dataGridView2.Rows[a].Cells["count2"].Value.ToString(), a) };
                db.More_Update("Obj_List_Book", Edit_col, Edit_data, Search_col, Search_data);
            }
        }
        /// 
        /// 재고에 들어갈 카운트를 재는거
        /// 
        /// 목록DB내 수량
        /// 입고된 수량
        /// 
        private string Inven_count(string ori, string change, int count)
        {
            string result = change;
            int i_ori = Convert.ToInt32(ori);
            int i_change = Convert.ToInt32(change);
            if(i_ori < i_change) {
                int i_result = i_change - i_ori;
                input_Inven(i_result, count);
                return ori;
            }
            return result;
        }
        /// 
        /// 재고 입력함수
        /// 
        private void save_grid3()
        {
            for(int a = 0; a < dataGridView3.Rows.Count - 1; a++)
            {
                string[] Search_Col = { "list_name", "book_name", "author", "book_comp" };
                string[] Search_Data = { dataGridView3.Rows[a].Cells["list_name3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["book_name3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["author3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["book_comp3"].Value.ToString() };
                string copy_chk = db.More_DB_Search("Inven", Search_Col, Search_Data);
                // insert용 배열
                string[] insert_Col = { "list_name", "book_name", "author", "book_comp", "count", 
                                        "pay", "total", "etc" };
                string[] insert_Data = { dataGridView3.Rows[a].Cells["list_name3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["book_name3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["author3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["book_comp3"].Value.ToString(),
                                         // dataGridView3.Rows[a].Cells["count3"].Value.ToString(),
                                         1.ToString(),
                                         dataGridView3.Rows[a].Cells["pay3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["total3"].Value.ToString(),
                                         dataGridView3.Rows[a].Cells["etc3"].Value.ToString() };
                if(copy_chk.Length < 3) {       // 중복없음 INSERT
                    db.DB_INSERT("Inven", insert_Col, insert_Data);
                }
                else {                          // 중복     UPDATE
                    db.More_Update("Inven", insert_Col, insert_Data, Search_Col, Search_Data);
                }
            }
        }
        private void dataGridView3_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            grid3Row = e.RowIndex;
        }
        private void dataGridView3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up) { grid3Row--; }
            if (e.KeyCode == Keys.Down) { grid3Row++; }
        }
        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if(dataGridView3.CurrentCell != null)
            {
                if (((DataGridView)sender).CurrentCell.ColumnIndex == 6)
                {
                    int count = 0;
                    int pay = 0;
                    int persent = 0;
                    if(((DataGridView)sender).Rows[grid3Row].Cells[1].Value != null) {
                        count = Convert.ToInt32(((DataGridView)sender).Rows[e.RowIndex].Cells[1].Value.ToString());
                    }
                    if(((DataGridView)sender).Rows[grid3Row].Cells[5].Value != null) {
                        pay = Convert.ToInt32(((DataGridView)sender).Rows[e.RowIndex].Cells[5].Value.ToString());
                    }
                    if(((DataGridView)sender).Rows[grid3Row].Cells[6].Value != null) {
                        persent = Convert.ToInt32(((DataGridView)sender).Rows[e.RowIndex].Cells[6].Value.ToString());
                    }
                    double result = pay * persent * 0.01 * count;
                    ((DataGridView)sender).Rows[grid3Row].Cells[7].Value = Math.Round(result);
                }
                //Grid3_Book_Count();
            }
        }
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            dataGridView1.CurrentCell.Style.SelectionBackColor = Color.Orange;
        }
        private void Purchase_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(MessageBox.Show("이대로 닫으시겠습니까?", "경고", MessageBoxButtons.YesNo) == DialogResult.No) {
                e.Cancel = true;
            }
        }
    }
}