using AR;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    public partial class Check_ISBN : Form
    {
        Main main;
        List_aggregation list_agg;
        Commodity_registration cr;
        Helper_DB db = new Helper_DB();
        public string compidx;
        public string list_name = string.Empty;
        private string mListIDX = string.Empty;
        private string mSearchText = string.Empty;
        public int rowidx;
        private bool save = true;
        string[] list_combo = { "알라딘", "국립중앙도서관", "다음", "네이버" };

        public Check_ISBN(Main _main,string pSearchText = "",string pListIDX = "")
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
            mSearchText = pSearchText;
            mListIDX = pListIDX;
        }
        public Check_ISBN(List_aggregation _list_agg)
        {
            InitializeComponent();
            list_agg = _list_agg;
            compidx = list_agg.compidx;
        }
        public Check_ISBN(Commodity_registration _cr)
        {
            InitializeComponent();
            cr = _cr;
            compidx = cr.comp_idx;
        }

        private void Check_ISBN_Load(object sender, EventArgs e)
        {
            this.tbDelayMs.Text = PUB.setting.ISBNSearchDelay.ToString();
            if (mSearchText != "")
            {
                tb_list_name.Text = mSearchText;
                DataLoad(mSearchText, mListIDX);
            }
        }

        public void DataLoad()
        {
            tb_list_name.Text = list_name;
            cb_api.Items.Clear();

            cb_api.Items.AddRange(list_combo);

            db.DBcon();
            string[] search_tbl = { "compidx", "list_name" };
            string[] search_col = { compidx, list_name };
            string search_data = "`idx`, `header`, `num`, `isbn`, `book_name`, `author`, `book_comp`, " +
                                 "`count`, `pay`, `total`, `import`, `price`, " +
                                 "`etc`, `pubDate`, `persent`, `category`, `image_url`, `set_book_name`";

            string cmd = db.More_DB_Search("Obj_List_Book", search_tbl, search_col, search_data);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] data = db_res.Split('|');
            made_Grid(data);
        }

        public void DataLoad(string ListName, string l_idx)
        {
            dataGridView1.Rows.Clear();
            cb_api.Items.Clear();

            list_name = ListName;

            cb_api.Items.AddRange(list_combo);

            db.DBcon();
            string[] search_tbl = { "compidx", "l_idx" };
            string[] search_col = { compidx, l_idx };
            string search_data = "`idx`, `header`, `num`, `isbn_marc`, `book_name`, `author`, `book_comp`, " +
                                 "`count`, `pay`, `total`, `import`, `price`, " +
                                 "`etc`, `pubDate`, `persent`, `category`, `image_url`, `set_book_name`";

            string cmd = db.More_DB_Search("Obj_List_Book", search_tbl, search_col, search_data);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] data = db_res.Split('|');
            made_Grid(data);
        }
        #region Load_Sub
        void made_Grid(string[] data)
        {
            /* 번호 isbn 도서명 저자 출판사
             * 수량 단가 합계 상태 정가
             * 비고 발행일 % 도서분류 */
            string[] grid = { "", "", "", "", "",
                              "", "", "", "", "",
                              "", "", "", "", "",
                              "", "", "", "", "" };

            int sdc = 18; // search_data_count
            for (int a = 0; a < data.Length; a++)
            {
                if (a % sdc ==  0) { grid[ 0] = data[a]; }                      // idx
                if (a % sdc ==  2) { grid[ 1] = data[a - 1] + " " + data[a]; }  // 번호
                if (a % sdc ==  3) { grid[ 2] = data[a]; }                      // isbn
                if (a % sdc ==  4) { grid[ 3] = data[a]; }                      // 도서명
                if (a % sdc ==  5) { grid[ 5] = data[a]; }                      // 저자
                if (a % sdc ==  6) { grid[ 7] = data[a]; }                      // 출판사
                if (a % sdc ==  7) { grid[ 9] = data[a]; }                      // 수량
                if (a % sdc ==  8) { grid[10] = data[a]; }                      // 단가
                if (a % sdc ==  9) { grid[11] = data[a]; }                      // 합계
                if (a % sdc == 10) { grid[12] = data[a]; }                      // 상태
                if (a % sdc == 11) { grid[13] = data[a]; }                      // 정가
                if (a % sdc == 12) { grid[14] = data[a]; }                      // 비고
                if (a % sdc == 13) { grid[15] = data[a]; }                      // 발행일
                if (a % sdc == 14) { grid[16] = data[a]; }                      // %
                if (a % sdc == 15) { grid[17] = data[a]; }                      // 도서분류
                if (a % sdc == 16) { grid[19] = data[a]; }                      // 도서 URL
                if (a % sdc == 17) {
                    if (data[a] != "") {
                        grid[3] = data[a];
                    }
                    dataGridView1.Rows.Add(grid);
                }
            }
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["isbn"].Value.ToString() != "")
                {
                    if (dataGridView1.Rows[a].Cells["unit"].Value.ToString() !=
                        dataGridView1.Rows[a].Cells["price"].Value.ToString())
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Orange;

                    else
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
            Set_grid();
        }
        
        void Set_grid()
        {
            for (int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                if (dataGridView1.Columns[a].HeaderText == "ISBN13" ||
                    dataGridView1.Columns[a].Name == "book_name" ||
                    dataGridView1.Columns[a].Name == "author" ||
                    dataGridView1.Columns[a].Name == "book_comp" ||
                    dataGridView1.Columns[a].Name == "price" ||
                    dataGridView1.Columns[a].Name == "category" ||
                    dataGridView1.Columns[a].Name == "etc")
                {
                    dataGridView1.Columns[a].ReadOnly = false;
                }
                else { dataGridView1.Columns[a].ReadOnly = true; }
            }
        }
        #endregion

        private void btn_lookup_Click(object sender, EventArgs e)
        {
            if(int.TryParse(tbDelayMs.Text, out int delayMs)==false)
            {
                UTIL.MsgE("지연시간은 숫자로 입력하세요");
                tbDelayMs.Focus();
                tbDelayMs.SelectAll();
                return;
            }

            //지연시간저장
            if(PUB.setting.ISBNSearchDelay != delayMs)
            {
                PUB.setting.ISBNSearchDelay = delayMs;
                PUB.setting.Save();
            }
            

            if (cb_api.SelectedIndex == -1) { UTIL.MsgE("조건이 선택되지 않았습니다."); return; }
            if (cb_filter.SelectedIndex == -1) { UTIL.MsgE("조건이 선택되지 않았습니다."); return; }

            clear_api();

            progressBar1.Style = ProgressBarStyle.Continuous;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = dataGridView1.Rows.Count;
            progressBar1.Step = 1;
            progressBar1.Value = 0;

            switch (cb_api.SelectedIndex)
            {
                case 0:
                    Aladin_API(dataGridView1, delayMs);
                    break;
                case 1:
                    NL_API(dataGridView1, delayMs);
                    break;
                case 2:
                    Daum_API(dataGridView1, delayMs);
                    break;
                case 3:
                    Naver_API(dataGridView1, delayMs);
                    break;
            }

            // 총 검색 횟수, 일치, 중복
            UTIL.MsgI("검색이 완료되었습니다!");

            progressBar1.Value = dataGridView1.Rows.Count;
            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells["num"];
            this.ActiveControl = dataGridView1;
            rowidx = 0;
            save = false;
        }
        /// <summary>
        /// 불러와서 저장한 api값 초기화
        /// </summary>
        void clear_api()
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].Cells["api_data"].Value = "";
            }
        }
        private void Aladin_API(DataGridView gridview,int delay_ms)
        {
            string temp = string.Empty;
            string type = string.Empty;

            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn13", "priceStandard", 
                               "pubDate", "categoryName", "stockStatus", "cover" };
            API api = new API();

            switch (cb_filter.SelectedIndex)
            {
                case 0:
                    type = "Title";
                    break;
                case 1:
                    type = "Author";
                    break;
                case 2:
                    type = "Publisher";
                    break;
                case 3:
                    type = "ISBN13";
                    break;
            }
            for (int a = 0; a < gridview.Rows.Count; a++) 
            {
                progressBar1.PerformStep();

                if (gridview.Rows[a].Cells["isbn"].Value == null)
                    gridview.Rows[a].Cells["isbn"].Value = "";

                string isbn = gridview.Rows[a].Cells["isbn"].Value.ToString();
                if (cb_filter.SelectedIndex == 3) {
                    if (!CheckData(isbn))
                        continue;
                    else
                        gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                }
                else {
                    if (CheckData(isbn))
                        continue;
                    else
                        gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                }

                string query = Aladin_Set_query(type, a);
                var apiresult = api.Aladin(query, type, param);
                insert_Aladin(string.Join("|",apiresult), a);

                if (delay_ms > 0)
                    System.Threading.Thread.Sleep(delay_ms);
            }
        }
        string Aladin_Set_query(string type, int idx)
        {
            string result = string.Empty;

            if (type == "Title")
                result = dataGridView1.Rows[idx].Cells["book_name"].Value.ToString();

            if (type == "Author")
                result = dataGridView1.Rows[idx].Cells["author"].Value.ToString();

            if (type == "Publisher")
                result = dataGridView1.Rows[idx].Cells["book_comp"].Value.ToString();

            if (type == "ISBN13")
                result = dataGridView1.Rows[idx].Cells["isbn"].Value.ToString();

            return result;
        }

        private void NL_API(DataGridView gridView, int delay_ms)
        {
            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 
            string[] param = { "TITLE", "AUTHOR", "PUBLISHER", "EA_ISBN", "PRE_PRICE",
                               "PUBLISH_PREDATE", "KDC", "TITLE_URL" };

            API api = new API();

            for (int a = 0; a < gridView.Rows.Count; a++)
            {
                string[] grid = { "", "", "", "", "",
                    "", "", "", "" };

                string type = "";
                string target = "";

                progressBar1.PerformStep();

                if (gridView.Rows[a].Cells["isbn"].Value == null)
                    gridView.Rows[a].Cells["isbn"].Value = "";

                string isbn = gridView.Rows[a].Cells["isbn"].Value.ToString();

                if (CheckData(isbn))
                    continue;
                else
                    gridView.Rows[a].DefaultCellStyle.BackColor = Color.Empty;

                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "title";
                        target = gridView.Rows[a].Cells["book_name"].Value.ToString();
                        break;
                    case 1:
                        type = "author";
                        target = gridView.Rows[a].Cells["author"].Value.ToString();
                        break;
                    case 2:
                        type = "publisher";
                        target = gridView.Rows[a].Cells["book_comp"].Value.ToString();
                        break;
                }
                string result = api.NationalLibraryOfKorea(target, type, param);
                if (result.Length < 4) continue;
                string[] tmp_Array = result.Split('|');
                int ArrayLength = tmp_Array.Length;

                for (int b = 0; b < ArrayLength; b++)
                {
                    if (b % 8 == 0) grid[0] = tmp_Array[b];
                    if (b % 8 == 1) grid[1] = tmp_Array[b];
                    if (b % 8 == 2) grid[2] = tmp_Array[b];
                    if (b % 8 == 3) grid[3] = tmp_Array[b];
                    if (b % 8 == 4) grid[4] = tmp_Array[b].Replace(",", "");
                    if (b % 8 == 5) grid[5] = tmp_Array[b];
                    if (b % 8 == 6) grid[6] = tmp_Array[b];
                    if (b % 8 == 7)
                    {
                        grid[8] = tmp_Array[b];
                        gridView.Rows[a].DefaultCellStyle.BackColor = Color.LightGray;

                        if (ArrayLength < 10) {
                            input_api(grid, a, grid[5]);
                            break;
                        }
                        else
                        {
                            gridView.Rows[a].Cells["api_data"].Value += string.Join("|", grid) + "|";
                        }
                    }

                }
                if (delay_ms > 0)
                    System.Threading.Thread.Sleep(delay_ms);
            }
        }
        private void Naver_API(DataGridView gridview, int delay_ms)
        {
            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn", "discount", 
                               "pubdate", "discount", "image"};
            API api = new API();

            for (int a = 0; a < gridview.Rows.Count; a++)
            {
                progressBar1.PerformStep();

                if (gridview.Rows[a].Cells["isbn"].Value == null)
                    gridview.Rows[a].Cells["isbn"].Value = "";

                string isbn = gridview.Rows[a].Cells["isbn"].Value.ToString();
                string Target = "";

                if (CheckData(isbn))
                    continue;
                else
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;

                #region 필터적용
                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        Target = gridview.Rows[a].Cells["book_name"].Value.ToString();
                        break;

                    case 1:
                        Target = gridview.Rows[a].Cells["author"].Value.ToString();
                        break;

                    case 2:
                        Target = gridview.Rows[a].Cells["book_comp"].Value.ToString();
                        break;
                }
                #endregion
                string result = api.Naver(Target, "query", param);
                insert_Naver(result, a);
                if (delay_ms > 0)
                    System.Threading.Thread.Sleep(delay_ms);
            }
        }
        private void Daum_API(DataGridView gridview, int delay_ms)
        {
            string[] param = { "title", "authors", "publisher", "isbn", "price", 
                               "datetime", "status", "thumbnail" };
            string type = string.Empty;
            string query = string.Empty;
            API api = new API();

            for(int a = 0; a < gridview.Rows.Count; a++)
            {
                progressBar1.PerformStep();

                if (gridview.Rows[a].Cells["isbn"].Value == null)
                    gridview.Rows[a].Cells["isbn"].Value = "";

                string isbn = gridview.Rows[a].Cells["isbn"].Value.ToString();

                if (CheckData(isbn))
                    continue;
                else
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;

                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "title";
                        query = gridview.Rows[a].Cells["book_name"].Value.ToString();
                        break;
                    case 1:
                        type = "person";
                        query = gridview.Rows[a].Cells["author"].Value.ToString();
                        break;
                    case 2:
                        type = "publisher";
                        query = gridview.Rows[a].Cells["book_comp"].Value.ToString();
                        break;
                }
                string result = api.Daum(query, type, param);
                insert_Daum(result, a);
                if (delay_ms > 0)
                    System.Threading.Thread.Sleep(delay_ms);
            }
        }

        bool CheckData(string isbn)
        {
            if (string.IsNullOrEmpty(isbn))
                return false;
            return true;
        }

        void insert_Aladin(string data, int row)
        {
            if (row > 0) { dataGridView1.Rows[row - 1].Selected = false; }
            dataGridView1.Rows[row].Selected = true;

            if (data.Length > 0) {
                dataGridView1.Rows[row].Cells["api_data"].Value = data;
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }
            string[] insert = data.Split('|');

            if (data == "") { return; }

            string newstring;
            try {
                // pubDate형 보기편하게 DateTime형으로 재정리
                newstring = String.Format("{0:yyyy/MM/dd HH:mm}",
                            DateTime.Parse(insert[5].Remove(insert[5].IndexOf(" G"))));
            }
            catch {
                newstring = insert[5];
            }

            insert[6] = Aladin_CategorySort(insert[6]);

            if (insert.Length > 10) {
                return;
            }
            if (cb_filter.SelectedItem.ToString() == "별치조사")
                input_api_aladin(insert, row, newstring);
            input_api(insert, row, newstring);

            /*
            if (row > 0) { dataGridView1.Rows[row - 1].Selected = false; }
            dataGridView1.Rows[row].Selected = true;

            string[] insert = data.Split('|');

            if (data == "") { return; }

            // pubDate형 보기편하게 DateTime형으로 재정리
            string newstring = "";
            try
            {
                newstring = String.Format("{0:yyyy/MM/dd}",
                    DateTime.Parse(insert[5].Remove(insert[5].IndexOf(" G"))));
            }
            catch (Exception ex) { UTIL.MsgE(data); }

            for (int a = 0; a < insert.Length; a++)
            {
                if (a % 8 == 6) { insert[a] = Aladin_CategorySort(insert[a]); }
            }

            dataGridView1.Rows[row].Cells["Column1"].Value += string.Join("|", insert) + "|";
            dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            if (cb_filter.SelectedItem.ToString() == "별치조사")
                input_api_aladin(insert, row, newstring);
            input_api(insert, row, newstring);
            */
        }
        public string Aladin_CategorySort(string insert)
        {
            // 도서 분류 필요한 데이터로 재정리
            int top = insert.IndexOf('>');
            int mid = insert.IndexOf('>', top + 1);
            int bot = insert.IndexOf('>', mid + 1);

            if (bot < 0) { insert = insert.Substring(top + 1); }
            else { insert = insert.Substring(top + 1, bot - top - 1); }

            return insert;
        }
        void input_api_aladin(string[] value, int idx, string date)
        {
            dataGridView1.Rows[idx].Cells["search_book_name"].Value = value[0];
            dataGridView1.Rows[idx].Cells["search_author"].Value = value[1];
            dataGridView1.Rows[idx].Cells["search_book_comp"].Value = value[2];
            dataGridView1.Rows[idx].Cells["price"].Value = value[4];
            dataGridView1.Rows[idx].Cells["pubDate"].Value = date;
            dataGridView1.Rows[idx].Cells["category"].Value = value[6];
        }
        void insert_Naver(string value, int row)
        {
            if (row > 0) dataGridView1.Rows[row - 1].Selected = false;

            dataGridView1.Rows[row].Selected = true;

            if (value == "") return;

            value = value.Replace("<b>", "");
            value = value.Replace("</b>", "");

            string[] sp_data = value.Split('\t');
            string[] grid = { "", "", "", "", "", "", "", "", "" };

            #region 분류작업
            for (int a = 0; a < sp_data.Length - 1; a++)
            {
                string[] data = sp_data[a].Split('|');
                int idx = data.Length - 2;
                grid[0] = data[0];
                grid[1] = data[1];
                for (int b = 2; b < idx - 5; b++)
                {
                    grid[1] += ", " + data[b];
                }
                grid[2] = data[idx - 5];
                if (data[idx - 4].Contains(" ") == true)
                {
                    string[] isbn = data[idx - 4].Split(' ');
                    grid[3] = isbn[1];
                }
                else
                    grid[3] = data[idx - 4];

                grid[4] = data[idx - 3];
                grid[5] = data[idx - 2];

                if (data[idx - 1] == "")
                    grid[7] = "절판";
                else
                    grid[7] = "";

                grid[8] = data[idx];

                dataGridView1.Rows[row].Cells["api_data"].Value += string.Join("|", grid) + "|";
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }
            #endregion

            if (sp_data.Length > 10) return;

            if (row > 0) dataGridView1.Rows[row - 1].Selected = false;

            dataGridView1.Rows[row].Selected = true;
            string newstring = "";
            try
            {
                newstring = DateTime.ParseExact(grid[5], "yyyyMMdd", null).ToString("yyyy-MM-dd");
            }
            catch (FormatException fe)
            {
                
            }

            input_api(grid, row, newstring);
        }
        void insert_Daum(string value, int row)
        {
            if (row > 0) { dataGridView1.Rows[row - 1].Selected = false; }
            dataGridView1.Rows[row].Selected = true;

            if (value == "") return;

            string[] sp_data = value.Split('\n');
            string[] grid = { "", "", "", "", "", "", "", "", "" };

            for (int a = 0; a < sp_data.Length - 1; a++)
            {
                string[] data = sp_data[a].Split('|');
                grid[0] = data[0];
                grid[1] = data[1];
                grid[2] = data[2];
                string[] tmp_isbn = data[3].Split(' ');

                if (tmp_isbn.Length < 2)
                    grid[3] = data[3].Replace(" ", "");

                else
                    grid[3] = tmp_isbn[1];

                grid[4] = data[4];

                if (data[5].Length < 10)
                    grid[5] = data[5];

                else
                    grid[5] = data[5].Substring(0, 10);

                grid[7] = data[6];
                grid[8] = data[7];

                dataGridView1.Rows[row].Cells["api_data"].Value += string.Join("|", grid) + "|";
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }

            if (sp_data.Length > 10) return;

            if (row > 0) dataGridView1.Rows[row - 1].Selected = false;
            dataGridView1.Rows[row].Selected = true;

            string newstring = grid[5];

            input_api(grid, row, newstring);
        }

        /// <summary>
        /// API에서 가져온 데이터가 요구한 데이터와 일치하는지 알아보는 함수
        /// </summary>
        /// <param name="value">데이터</param>
        /// <param name="idx">Grid의 row인덱스 번호</param>
        /// <param name="date">날짜</param>
        void input_api(string[] value, int idx, string date)
        {
            bool[] chk = { false, false, false };

            string book_name = dataGridView1.Rows[idx].Cells["book_name"].Value.ToString();
            string author = dataGridView1.Rows[idx].Cells["author"].Value.ToString();
            string book_comp = dataGridView1.Rows[idx].Cells["book_comp"].Value.ToString();

            if (value[0] == book_name) chk[0] = true;
            else if (book_name.Contains(value[0])) chk[0] = true;
            else if (value[0].Contains(book_name)) chk[0] = true;

            if (value[1] == author) chk[1] = true;
            else if (author.Contains(value[1])) chk[1] = true;
            else if (value[1].Contains(author)) chk[1] = true;

            if (value[2] == book_comp) chk[2] = true;
            else if (book_comp.Contains(value[2])) chk[2] = true;
            else if (value[2].Contains(book_comp)) chk[2] = true;

            if (chk[0] && chk[1] && chk[2]) {

                dataGridView1.Rows[idx].Cells["search_book_name"].Value = value[0];
                dataGridView1.Rows[idx].Cells["search_author"].Value = value[1];
                dataGridView1.Rows[idx].Cells["search_book_comp"].Value = value[2];
                dataGridView1.Rows[idx].Cells["isbn"].Value = value[3];
                dataGridView1.Rows[idx].Cells["price"].Value = value[4];
                dataGridView1.Rows[idx].Cells["pubDate"].Value = date;
                dataGridView1.Rows[idx].Cells["category"].Value = value[6];
                dataGridView1.Rows[idx].Cells["sold_out"].Value = value[7];
                dataGridView1.Rows[idx].Cells["image"].Value = value[8];

                dataGridView1.Rows[idx].DefaultCellStyle.BackColor = Color.Yellow;
            }
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            string[] Edit_tbl = { "isbn", "price", "pubDate", "category", "image_url", "etc" };


            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["isbn"].Value == null &&
                    dataGridView1.Rows[a].Cells["isbn"].Value.ToString() == "") continue;

                if (main != null)
                    Edit_tbl[0] = "isbn_marc";
                else
                    Edit_tbl[0] = "isbn";

                string[] Edit_Col =  {
                    dataGridView1.Rows[a].Cells["isbn"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["price"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["pubDate"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["category"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["image"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["etc"].Value.ToString()
                };

                string[] Search_tbl = { "idx", "list_name", "compidx" };
                string[] Search_col = { dataGridView1.Rows[a].Cells["idx"].Value.ToString(),
                                        list_name, compidx };

                if (dataGridView1.Rows[a].Cells["etc"].Value.ToString().Contains("세트분할"))
                    Search_tbl[0] = "set_book_name";

                string U_cmd = db.More_Update("Obj_List_Book", Edit_tbl, Edit_Col, Search_tbl, Search_col, 1);
                Helper_DB.ExcuteNonQuery(U_cmd);

                if (Check_Marc.Checked) {
                    string CMcmd = string.Format("UPDATE `Obj_List_Book` SET `isbn_marc` = \"{0}\" WHERE `idx` = \"{1}\"",
                        Edit_Col[0], Search_col[0]);
                    Helper_DB.ExcuteNonQuery(CMcmd);
                }                   
            }
            UTIL.MsgI("저장되었습니다!");
            save = true;
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (rowidx >= dataGridView1.Rows.Count) return;
            //if (dataGridView1.Rows[rowidx].Cells["api_data"].Value == null || 
            //    dataGridView1.Rows[rowidx].Cells["api_data"].Value.ToString() == "") { 
            //    return;
            //}
            //Check_ISBN_Sub sub = new Check_ISBN_Sub(this);
            //sub.row = rowidx;
            //sub.Call_API = cb_api.Text;
            //sub.Show();
        }
        private void SHOW_ISBN()
        {
            if (rowidx >= dataGridView1.Rows.Count) return;
            if (dataGridView1.Rows[rowidx].Cells["api_data"].Value == null ||
                dataGridView1.Rows[rowidx].Cells["api_data"].Value.ToString() == "")
            {
                return;
            }
            Check_ISBN_Sub sub = new Check_ISBN_Sub(this);
            sub.row = rowidx;
            sub.Call_API = cb_api.Text;
            sub.Show();
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Excel_to_DataGridView(sender, e);
            //if (e.KeyCode == Keys.Enter) { dataGridView1_CellDoubleClick(null, null); rowidx++; }
            if (e.KeyCode == Keys.Enter) { SHOW_ISBN(); rowidx++; }
            if (e.KeyCode == Keys.Insert)
            {
                // Check_ISBN_Split split = new Check_ISBN_Split(this);
                // split.book_data[0] = dataGridView1.Rows[rowidx].Cells["num"].Value.ToString();
                // split.book_data[1] = dataGridView1.Rows[rowidx].Cells["book_name"].Value.ToString();
                // split.book_data[2] = dataGridView1.Rows[rowidx].Cells["author"].Value.ToString();
                // split.book_data[3] = dataGridView1.Rows[rowidx].Cells["book_comp"].Value.ToString();
                // split.book_data[4] = dataGridView1.Rows[rowidx].Cells["unit"].Value.ToString();
                // split.book_data[5] = dataGridView1.Rows[rowidx].Cells["count"].Value.ToString();
                // split.row_idx = rowidx;
                // split.compidx = compidx;
                // split.Show();
            }
            if (e.KeyCode == Keys.F12)
            {
                Book_Lookup bl = new Book_Lookup(this);
                bl.TopMost = true;
                string book_name = dataGridView1.Rows[rowidx].Cells["book_name"].Value.ToString();
                string author = dataGridView1.Rows[rowidx].Cells["author"].Value.ToString();
                string book_comp = dataGridView1.Rows[rowidx].Cells["book_comp"].Value.ToString();
                bl.Lookup_Load(book_name, author, book_comp, list_name);
                bl.Show();
            }
            if (e.KeyCode == Keys.Up)
            {
                rowidx--;
                if (rowidx < 0)
                    rowidx = 0;
            }
            if (e.KeyCode == Keys.Down)
            {
                rowidx++;
                if (rowidx > dataGridView1.Rows.Count - 1)
                    rowidx = dataGridView1.Rows.Count - 1;
            }
        }
        private void cb_api_SelectedIndexChanged(object sender, EventArgs e)
        {
            cb_filter.Items.Clear();
            if (cb_api.SelectedIndex == 0) {
                string[] aladin = { "도서명", "저자", "출판사", "별치조사" };
                cb_filter.Items.AddRange(aladin);
            }
            else { 
                string[] sub = { "도서명", "저자", "출판사" };
                cb_filter.Items.AddRange(sub);
            }
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            rowidx = e.RowIndex;
            if (rowidx < 0) {
                return;
            }
            richTextBox1.Text += dataGridView1.Rows[rowidx].Cells["etc"].Value.ToString().Contains("세트분할").ToString();
            if (dataGridView1.Rows[rowidx].Cells["api_data"].Value == null) {
                return;
            }
            richTextBox1.Text = dataGridView1.Rows[rowidx].Cells["api_data"].Value.ToString();
        }
        private void Check_ISBN_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!save) {
                if (UTIL.MsgQ("데이터가 저장되지않았습니다!\n종료하시겠습니까?") == DialogResult.No) {
                    e.Cancel = true;
                }
            }
        }
        private void btn_yes24_Click(object sender, EventArgs e)
        {
            Check_ISBN_Yes24 yes = new Check_ISBN_Yes24(this);
            yes.Show();
        }

        private void tb_list_name_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Order_input_Search search = new Order_input_Search(this);
                search.Where_Open = "book_list";
                search.searchText = tb_list_name.Text;
                search.OnlyMarc = true;
                search.TopMost = true;
                search.Show();
            }
        }

        private void btn_ComparePrice_Click(object sender, EventArgs e)
        {
            int GridCount = dataGridView1.Rows.Count;

            for (int a = 0; a < GridCount; a++)
            {
                string isbn = dataGridView1.Rows[a].Cells["isbn"].Value.ToString();
                if (isbn == null || isbn == "") continue;

                string unit = dataGridView1.Rows[a].Cells["unit"].Value.ToString();
                string price = dataGridView1.Rows[a].Cells["price"].Value.ToString();

                if (unit != price)
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Orange;
            }
        }
    }
}