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

namespace UniMarc
{
    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;
        public Purchase(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }
        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;
        }
        /// <summary>
        /// 텍스트박스 키다운
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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)
                    {
                        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 cmd, db_res;
            string Area = "`idx`, `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 };
                cmd = db.More_DB_Search("Obj_List", Where, data, tabel);
                db_res = db.DB_Send_CMD_Search(cmd);
                string[] db_ori = db_res.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], "미입고" };
                            cmd = db.More_DB_Search("Obj_List_Book", table, sear_data, Area);
                            db_res = db.DB_Send_CMD_Search(cmd);
                            Insert_Grid(db_res);
                        }
                        else if (Name == "tb_dly" && tmp_data[2].Contains(Text) == true) {
                            string[] table = { "compidx", "list_name", "import" };
                            string[] sear_data = { compidx, tmp_data[0], "미입고" };
                            cmd = db.More_DB_Search("Obj_List_Book", table, sear_data, Area);
                            db_res = db.DB_Send_CMD_Search(cmd);
                            Insert_Grid(db_res);
                        }
                    }
                }
            }
            else if (Name == "tb_order") {
                cmd = db.DB_Contains("Obj_List_Book", compidx, "`order`", Text, Area, "import", "미입고");
                db_res = db.DB_Send_CMD_Search(cmd);
                Insert_Grid(db_res);
            }
            else if (Name == "tb_isbn") {
                cmd = db.DB_Contains("Obj_List_Book", compidx, "isbn", Text, Area, "import", "미입고");
                db_res = db.DB_Send_CMD_Search(cmd);
                Insert_Grid(db_res);
                if (dataGridView1.Rows.Count == 1) {
                    dataGridView1_CellDoubleClick(null, null);
                }
                else {
                    dataGridView1.Focus();
                }
            }
            else if (Name == "tb_book_name") {
                cmd = db.DB_Contains("Obj_List_Book", compidx, "book_name", Text, Area, "import", "미입고");
                db_res = db.DB_Send_CMD_Search(cmd);
                Insert_Grid(db_res);
            }
            else if (Name == "tb_book_comp") {
                cmd = db.DB_Contains("Obj_List_Book", compidx, "book_comp", Text, Area, "import", "미입고");
                db_res = db.DB_Send_CMD_Search(cmd);
                Insert_Grid(db_res);
            }
        }
        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 13  */
            for (int a = 0; a < data.Length; a++)
            {
                if (a % 14 == 00) { add_data[00] = data[a]; }
                if (a % 14 == 02) { add_data[01] = data[a - 1] + " " + data[a]; }
                if (a % 14 == 03) { add_data[02] = data[a]; }
                if (a % 14 == 04) { add_data[03] = data[a]; }
                if (a % 14 == 05) { add_data[04] = data[a]; }
                if (a % 14 == 06) { add_data[05] = data[a]; }
                if (a % 14 == 07) { add_data[06] = data[a]; }
                if (a % 14 == 08) { add_data[07] = data[a]; }
                if (a % 14 == 09) { add_data[08] = data[a]; }
                if (a % 14 == 10) { add_data[09] = data[a]; }
                if (a % 14 == 11) { add_data[10] = data[a].Replace("\r", string.Empty); }
                if (a % 14 == 12) { add_data[12] = data[a]; }
                if (a % 14 == 13) {
                    add_data[13] = 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;
            if (dataGridView1.Rows.Count < 0) { return "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() == "") {
                    return;
                }
                else {
                    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)
        {
            dataGridView1_CellClick(sender, 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 == 11) {
                if(tb_persent.Text == "") {
                    UTIL.MsgE("매입율을 작성해주세요.");
                    tb_persent.Focus();
                }
                else {
                    press_Grid1_Btn(row, col);
                }
            }
            else if (name == "dataGridView2" && col == 11) {
                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();
            }
        }
        private void create_TempTxt()
        {
            DirectoryInfo di = new DirectoryInfo(Application.StartupPath+"\\temp");
            if (!di.Exists)
            {
                di.Create();
            }
            FileInfo file = new FileInfo(Application.StartupPath + "\\temp\\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 = Application.StartupPath + "\\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 { UTIL.MsgE("임시 저장된 데이터가 없습니다."); }
        }
        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 cmd = db.Search_Date("Obj_List", search_Table, "date", start, end, compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] tp = db_res.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 };
                        cmd = db.More_DB_Search("Obj_List_Book", Where, Search, _Table);
                        db_res = db.DB_Send_CMD_Search(cmd);
                        mk_grid(db_res);
                    }
                }
                else if (cb_charge.SelectedIndex == 0) {
                    if (a % 2 == 1) {
                        string[] Where = { "list_name", "import", "compidx" };
                        string[] Search = { tp[a - 1], "입고", compidx };
                        cmd = db.More_DB_Search("Obj_List_Book", Where, Search, _Table);
                        db_res = db.DB_Send_CMD_Search(cmd);
                        mk_grid(db_res);
                    }
                }
            }
        }
        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)
        {
            /* idx 번호 수량 도서명 출판사 
             * 저자 단가 합계 구분 비고 
             * 주문처명 btn취소 isbn 입고시간 */
            string[] grid2 = {"", "", "", "", "",
                              "", "", "", "", "",
                              "", "취소", "", DateTime.Now.ToString("g")};

            /* 번호 수량 도서명 출판사 저자
             * 정가 매입율 합계 비고 구분
             * 주문처 날짜 isbn */
            string[] grid3 = {"", "", "", "", "",
                              "0", "", "", "", "", 
                              "", DateTime.Now.ToString("g"), ""};

            if(row < 0 || col < 0) {
                return;
            }
            for(int a = 0; a < 11; a++)
            {
                if(dataGridView1.Rows.Count <= 0) {
                    return;
                }
                grid2[a] = dataGridView1.Rows[row].Cells[a].Value.ToString();
                if (a == 2) {
                    grid2[a] = "1";
                }
            }
            grid2[12] = dataGridView1.Rows[row].Cells[12].Value.ToString();
            Grid2Count(grid2, row, col);   // 책 중복시
            Grid3_Pay_Count(grid2[9]);

            grid3[0] = dataGridView1.Rows[row].Cells["isbn"].Value.ToString();
            grid3[1] = "1";
            grid3[2] = dataGridView1.Rows[row].Cells["book_name"].Value.ToString();
            grid3[3] = dataGridView1.Rows[row].Cells["book_comp"].Value.ToString();
            grid3[4] = dataGridView1.Rows[row].Cells["author"].Value.ToString();

            string isbn_chk = dataGridView1.Rows[row].Cells["isbn"].Value.ToString().Replace("\r", string.Empty);
            grid3[5] = dataGridView1.Rows[row].Cells["pay"].Value.ToString();
            grid3[8] = dataGridView1.Rows[row].Cells["etc"].Value.ToString();

            if (chk_stock.Checked == true) {
                if (stock_chk(isbn_chk) == true) {
                    int inven_count = stock_count_chk(isbn_chk);
                    UTIL.MsgI(inven_count.ToString());
                    if (lbl_inven_count.Text == "0") {
                        lbl_inven_count.Text = "0";
                        inven_count = 0;
                        grid3[5] = dataGridView1.Rows[row].Cells["pay"].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["list_name"].Value.ToString();
            grid3[10] = dataGridView1.Rows[row].Cells["order"].Value.ToString();
            grid3[12] = dataGridView1.Rows[row].Cells["num"].Value.ToString();

            Grid3Count(grid3, row, col);

            dataGridView1.Rows.RemoveAt(row);
        }
        private bool stock_chk(string isbn)
        {
            string Area = "`isbn`";
            string[] table = { "compidx" };
            string[] colum = { compidx };
            string cmd = db.More_DB_Search("Inven", table, colum, Area);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] inven_isbn = db_res.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;
        }
        private int stock_count_chk(string isbn)
        {
            string Area = "`count`";
            string[] table = { "compidx", "isbn" };
            string[] colum = { compidx, isbn.Replace("\r", string.Empty) };
            string cmd = db.More_DB_Search("Inven", table, colum, Area);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] inven_count = db_res.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;
        }
        /// <summary>
        /// 매입처의 미수금 금액이 표출됨.
        /// </summary>
        /// <param name="order"></param>
        private void Grid3_Pay_Count(string order)
        {
            string Search_table = "`buy_money`, `payment`";
            string[] Where_table = { "compidx", "purchase" };
            string[] Where_col = { compidx, order };

            string cmd = db.More_DB_Search("Buy_ledger", Where_table, Where_col, Search_table);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] db_data = db_res.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++)
            {
                // 3: 도서명 / 4: 출판사 / 5: 저자 / 8: 구분
                if (mkgrid[3] == dataGridView2.Rows[a].Cells["Book_name2"].Value.ToString() &&
                    mkgrid[4] == dataGridView2.Rows[a].Cells["Book_comp2"].Value.ToString() &&
                    mkgrid[5] == dataGridView2.Rows[a].Cells["author2"].Value.ToString() &&
                    mkgrid[8] == dataGridView2.Rows[a].Cells["list_name2"].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[6]);
                    int totaltmp = invenCount * money;
                    mkgrid[7] = totaltmp.ToString();
                    dataGridView2.Rows[a].Cells["count2"].Value = invenCount.ToString();
                    dataGridView2.Rows[a].Cells["total2"].Value = mkgrid[7];
                    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["book_name3"].Value.ToString() &&
                    grid[3] == dataGridView3.Rows[a].Cells["book_comp3"].Value.ToString() &&
                    grid[4] == dataGridView3.Rows[a].Cells["author3"].Value.ToString() &&
                    grid[5] == dataGridView3.Rows[a].Cells["pay3"].Value.ToString() &&
                    grid[6] == dataGridView3.Rows[a].Cells["persent"].Value.ToString()) {
                    
                    string invenCount_tmp = dataGridView3.Rows[a].Cells["count3"].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["count3"].Value = invenCount.ToString();
                    dataGridView3.Rows[a].Cells["total3"].Value = grid[7];

                    break;
                }
            }
            if (chk == false) {
                dataGridView3.Rows.Add(grid);
            }
            Grid3_Book_Count();
        }
        private void press_Grid2_Btn(DataGridViewCellEventArgs e)
        {
            string number = dataGridView2.Rows[e.RowIndex].Cells["num2"].Value.ToString();
            string Area = "`idx`, `header`, `num`, `count`, `book_name`, `book_comp`, " +
                          "`author`, `pay`, `total`, `list_name`, `etc`, " +
                          "`order`, `isbn`, `order_date`";
            string[] Table = { "idx", "book_name", "book_comp", "author", "list_name" };
            string[] Data = { dataGridView2.Rows[e.RowIndex].Cells["idx2"].Value.ToString(),
                              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 cmd = db.More_DB_Search("Obj_List_Book", Table, Data, Area);
            string db_res = db.DB_Send_CMD_Search(cmd);
            Insert_Grid(db_res);

            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 = { "idx", "book_name", "book_comp", "author", "list_name" };
                string[] search_Data = { 
                    dataGridView2.Rows[a].Cells["idx2"].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["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() };
                string U_cmd = db.More_Update("Obj_List_Book", edit_Col, edit_Data, search_Col, search_Data);
                Helper_DB.ExcuteNonQuery(U_cmd);
            }
            /* 입고작업을 하려는 책이 재고에 있을 경우, 재고 -1이 되어야함.
             * 만약 재고수보다 입고수가 더 많을경우는?
             * 1. 재고수량이 0이 되며, 나머지값을 매입원장에 기입. 
             * (재고1, 입고필요수량3 일 경우 재고는 사라지고, 매입원장에 2권분량의 값이 들어가야함.) */
            
            save_grid2();
            input_ledger();
        }
        #region Save_Sub
        /// <summary>
        /// 목록도서DB 안의 입고수량 수정하는 함수
        /// </summary>
        private void save_grid2()
        {
            for (int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                string[] grid2 = { 
                    dataGridView2.Rows[a].Cells["idx2"].Value.ToString(),        // 인덱스
                    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", "idx", "book_name", "book_comp", "author", "list_name" };
                string[] Search_data = { compidx, grid2[0], grid2[2], grid2[3], grid2[4], grid2[7] };
                
                string cmd = db.More_DB_Search("Obj_List_Book", Search_col, Search_data, "`count`");
                string db_res = db.DB_Send_CMD_Search(cmd);
                string[] db_data = db_res.Split('|');

                string[] Edit_col = { "input_count" };
                string[] Edit_data = { Inven_count(db_data[0], dataGridView2.Rows[a].Cells["count2"].Value.ToString(), a) };
                string U_cmd = db.More_Update("Obj_List_Book", Edit_col, Edit_data, Search_col, Search_data);
                Helper_DB.ExcuteNonQuery(U_cmd);
            }
        }
        /// <summary>
        /// 재고에 들어갈 카운트를 재는거
        /// </summary>
        /// <param name="ori">목록DB내 수량</param>
        /// <param name="change">입고된 수량</param>
        /// <returns></returns>
        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;
            }
            else if (i_ori > i_change)
            {
                // 비고로 부족한 수량이 들어가야함
                int i_result = i_change - i_ori;
                Etc_Count(i_result, count);
            }
            return result;
        }
        private void Etc_Count(int res, int row)
        {

            string[] Edit_Col = { "etc", "import" };
            string[] Edit_Data = { res.ToString(), "미입고" };
            string[] Search_Name = { "compidx", "idx", "book_name", "author", "book_comp", "list_name" };
            string[] Search_Data = { compidx, 
                dataGridView2.Rows[row].Cells["idx2"].Value.ToString(),
                dataGridView2.Rows[row].Cells["Book_name2"].Value.ToString(),
                dataGridView2.Rows[row].Cells["author2"].Value.ToString(),
                dataGridView2.Rows[row].Cells["Book_comp2"].Value.ToString(),
                dataGridView2.Rows[row].Cells["list_name2"].Value.ToString()
            };
            string U_cmd = db.More_Update("Obj_List_Book", Edit_Col, Edit_Data, Search_Name, Search_Data);
            Helper_DB.ExcuteNonQuery(U_cmd);

            dataGridView2.Rows[row].Cells["edasd"].Value = res.ToString();
        }
        /// <summary>
        /// 입고 추가수량이 재고로 들어가는 함수
        /// </summary>
        /// <param name="data"></param>
        /// <param name="row_count"></param>
        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 cmd = db.More_DB_Search("Obj_List_Book", Where_Table, Search_Data, Search_Table);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] db_data = db_res.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 == 7) input_data[a] = data.ToString();
            }

            // Inven테이블내 데이터중복체크
            string[] chk_Table = { "compidx", "isbn" };
            string[] chk_Data = { compidx, db_data[12] };
            cmd = db.More_DB_Search("Inven", chk_Table, chk_Data);
            db_res = db.DB_Send_CMD_Search(cmd);

            // 중복데이터가 검색되지않음.
            if (db_res.Length < 3)
            {
                string Incmd = db.DB_INSERT("Inven", input_col, input_data);
                Helper_DB.ExcuteNonQuery(Incmd);
                UTIL.MsgI("DB 새로 추가");
                return;
            }
            else
            {
                cmd = db.More_DB_Search("Inven", chk_Table, chk_Data, "`count`, `idx`");
                db_res = db.DB_Send_CMD_Search(cmd);
                string[] cout = db_res.Split('|');
                int count = Convert.ToInt32(cout[0]);
                count += data;
                UTIL.MsgI("DB 수정");
                string U_cmd = db.DB_Update("Inven", "count", count.ToString(), "idx", cout[0]);
                Helper_DB.ExcuteNonQuery(U_cmd);
            }
            
        }
        /// <summary>
        /// 매입원장에 추가하는 함수
        /// </summary>
        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] = "재고가감";
                }
                string Incmd = db.DB_INSERT("Buy_ledger", Area, tata);
                Helper_DB.ExcuteNonQuery(Incmd);
            }
        }
        /// <summary>
        /// input_ledger를 도와주는 함수
        /// </summary>
        /// <param name="count">입력할 표의 행번호</param>
        /// <param name="book_name">행번호에 위치한 도서명</param>
        /// <param name="book_comp">행번호에 위치한 출판사</param>
        /// <param name="author">행번호에 위치한 저자</param>
        /// <returns>input_ledger에 Area배열에 맞춰 DB에 INSERT할 데이터의 배열값 반환</returns>
        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;
        }
        #endregion
        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView3.CurrentCell != null)
            {
                string current = ((DataGridView)sender).Columns[e.ColumnIndex].Name;
                if (current == "count3" || current == "pay3" || current == "persent")
                {
                    int count = 0;
                    int pay = 0;
                    int persent = 0;
                    if (((DataGridView)sender).Rows[e.RowIndex].Cells["count3"].Value != null) {
                        count = Convert.ToInt32(((DataGridView)sender).Rows[e.RowIndex].Cells["count3"].Value.ToString());
                    }
                    if (((DataGridView)sender).Rows[e.RowIndex].Cells["pay3"].Value != null) {
                        pay = Convert.ToInt32(((DataGridView)sender).Rows[e.RowIndex].Cells["pay3"].Value.ToString());
                    }
                    if (((DataGridView)sender).Rows[e.RowIndex].Cells["persent"].Value != null) {
                        persent = Convert.ToInt32(((DataGridView)sender).Rows[e.RowIndex].Cells["persent"].Value.ToString());
                    }
                    double result = pay * persent * 0.01 * count;
                    ((DataGridView)sender).Rows[e.RowIndex].Cells["total3"].Value = Math.Round(result);
                }
                if (current == "isbn3") {
                    // ISBN 찍으면 도서명 출판사 저자 정가가 출력되어야 함. (수량은 1고정)
                    string isbn_str = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    if (isbn_str.Length == 13 || isbn_str.Length == 10) 
                        ISBN_LookUp_By_Aladin(isbn_str, e.RowIndex, (DataGridView)sender);
                    else { return; }
                }
                Grid3_Book_Count();
            }
        }
        #region Sub
        private void ISBN_LookUp_By_Aladin(string isbn, int row, DataGridView datagrid)
        {
            string[] param = { "title", "publisher", "author", "priceStandard" };
            API api = new API();
            var aladinResult = api.Aladin(isbn, "ISBN13", param);

            string[] insert = aladinResult.ToArray();// aladin.Split('|');
            if (insert.Length < 2) { return; };

            datagrid.Rows[row].Cells["book_name3"].Value = insert[0];
            datagrid.Rows[row].Cells["book_comp3"].Value = insert[1];
            datagrid.Rows[row].Cells["author3"].Value = insert[2];
            datagrid.Rows[row].Cells["pay3"].Value = insert[3];
            datagrid.Rows[row].Cells["count3"].Value = "1";
            datagrid.Rows[row].Cells["persent"].Value = tb_persent.Text;
        }
        #endregion
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            dataGridView1.CurrentCell.Style.SelectionBackColor = Color.Orange;
        }
        private void Purchase_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (UTIL.MsgQ("이대로 닫으시겠습니까?") != DialogResult.Yes)
            {
                // 로컬파일 생성. (C:\)
                create_TempTxt();
                e.Cancel = true;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            string isbn = dataGridView1.Rows[row].Cells["isbn"].Value.ToString();

            if (isbn.Length < 9) {
                pictureBox1.Image = null;
                return;
            }
            string isbn3 = isbn.Substring(isbn.Length - 3, 3);
            string tFilePath = string.Format("https://contents.kyobobook.co.kr/sih/fit-in/458x0/pdt/{0}.jpg", isbn);
            pictureBox1.ImageLocation = tFilePath;
            //pictureBox1.ImageLocation = "http://image.kyobobook.co.kr/images/book/xlarge/" + isbn3 + "/x" + isbn + ".jpg";
        }
    }
}
