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_ISBN2 : Form
    {
        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 = { "알라딘", "국립중앙도서관", "다음", "네이버" };

        BindingList<IsbnGridItem> bookList = new BindingList<IsbnGridItem>();

        public Check_ISBN2(string pSearchText = "", string pListIDX = "")
        {
            InitializeComponent();
            compidx = PUB.user.CompanyIdx;
            mSearchText = pSearchText;
            mListIDX = pListIDX;
        }


        private void Check_ISBN_Load(object sender, EventArgs e)
        {
            bs1.DataSource = bookList;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = bs1;
            dataGridView1.DataBindingComplete += DataGridView1_DataBindingComplete;

            tbDelayMs.Text = PUB.setting.ISBNSearchDelay.ToString();
            if (mSearchText != "")
            {
                tb_list_name.Text = mSearchText;
                DataLoad(mSearchText, mListIDX);
            }

        }

        public void DataLoad(string ListName, string l_idx)
        {
            bookList.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`, sold_out," +
                                 "`count`, `pay`, `total`, `import`, `price`, " +
                                 "`etc`, `pubDate`, `persent`, `category`, `image_url`, `set_book_name`,`search_book_name`,`search_author`,`search_book_comp`,`search_description`,`search_url`";

            string cmd = db.More_DB_Search("Obj_List_Book", search_tbl, search_col, search_data);
            var dt = Helper_DB.ExecuteDataTable(cmd);
            made_Grid(dt);
        }
        #region Load_Sub
        void made_Grid(DataTable datas)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            if (datas == null)
            {
                UTIL.MsgE("자료가 없습니다");
                return;
            }

            foreach (DataRow row in datas.Rows)
            {
                var item = new IsbnGridItem();
                item.idx = row["idx"]?.ToString() ?? string.Empty;
                item.num = (row["header"]?.ToString() ?? string.Empty) + " " + (row["num"]?.ToString() ?? string.Empty); // header + num
                item.isbn = row["isbn_marc"]?.ToString() ?? string.Empty;
                item.book_name = row["book_name"]?.ToString() ?? string.Empty;
                item.author = row["author"]?.ToString() ?? string.Empty;
                item.book_comp = row["book_comp"]?.ToString() ?? string.Empty;
                item.count = row["count"]?.ToString() ?? string.Empty;
                item.unit = row["pay"]?.ToString() ?? string.Empty;
                item.total = row["total"]?.ToString() ?? string.Empty;
                item.condition = row["import"]?.ToString() ?? string.Empty;
                item.price = row["price"]?.ToString() ?? string.Empty;
                item.etc = row["etc"]?.ToString() ?? string.Empty;
                item.pubDate = row["pubDate"]?.ToString() ?? string.Empty;
                item.persent = row["persent"]?.ToString() ?? string.Empty;
                item.category = row["category"]?.ToString() ?? string.Empty;
                item.image = row["image_url"]?.ToString() ?? string.Empty;
                item.sold_out = row["sold_out"]?.ToString() ?? string.Empty;
                item.search_book_name = row["search_book_name"]?.ToString() ?? string.Empty;
                item.search_author = row["search_author"]?.ToString() ?? string.Empty;
                item.search_book_comp = row["search_book_comp"]?.ToString() ?? string.Empty;
                item.search_description = row["search_description"]?.ToString() ?? string.Empty;
                item.search_url = row["search_url"]?.ToString() ?? string.Empty;

                string setBookName = row["set_book_name"]?.ToString() ?? string.Empty;
                if (!string.IsNullOrEmpty(setBookName))
                {
                    item.book_name = setBookName;
                }

                bookList.Add(item);
            }

            Set_grid();
        }

        private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            ApplyRowColors();
        }

        private void ApplyRowColors()
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                var row = dataGridView1.Rows[a];
                var item = row.DataBoundItem as IsbnGridItem;
                if (item != null && !string.IsNullOrEmpty(item.isbn))
                {
                    if (item.unit != item.price)
                        row.DefaultCellStyle.BackColor = Color.Orange;
                    else
                        row.DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }

        void Set_grid()
        {
            for (int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                if (dataGridView1.Columns[a].Name == "isbn" ||
                    dataGridView1.Columns[a].Name == "book_name" ||
                    dataGridView1.Columns[a].Name == "search_book_name" ||
                    dataGridView1.Columns[a].Name == "author" ||
                    dataGridView1.Columns[a].Name == "search_author" ||
                    dataGridView1.Columns[a].Name == "book_comp" ||
                    dataGridView1.Columns[a].Name == "search_book_comp" ||
                    dataGridView1.Columns[a].Name == "unit" ||
                    dataGridView1.Columns[a].Name == "price" ||
                    dataGridView1.Columns[a].Name == "pubDate" ||
                    dataGridView1.Columns[a].Name == "category" ||
                    dataGridView1.Columns[a].Name == "sold_out" ||
                    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(delayMs);
                    break;
                case 1:
                    NL_API(delayMs);
                    break;
                case 2:
                    Daum_API(delayMs);
                    break;
                case 3:
                    Naver_API(delayMs);
                    break;
            }

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

            progressBar1.Value = bookList.Count;
            bs1.Position = 0;
            this.ActiveControl = dataGridView1;
            rowidx = 0;
            save = false;
        }
        /// <summary>
        /// 불러와서 저장한 api값 초기화
        /// </summary>
        void clear_api()
        {
            foreach (var item in bookList)
            {
                item.api_data = "";
            }
        }
        private void Aladin_API(int delay_ms)
        {
            string temp = string.Empty;
            string type = string.Empty;

            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn13", "priceStandard",
                               "pubDate", "categoryName", "stockStatus", "cover" ,"description","link"};
            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 < bookList.Count; a++)
            {
                progressBar1.PerformStep();

                var item = bookList[a];
                if (item.isbn == null)
                    item.isbn = "";

                string isbn = item.isbn;
                if (cb_filter.SelectedIndex == 3)
                {
                    if (!CheckData(isbn))
                        continue;
                    else
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                }
                else
                {
                    if (CheckData(isbn))
                        continue;
                    else
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                }

                string query = Aladin_Set_query(type, a);
                var apireseult = api.Aladin(query, type, param);
                insert_Aladin(apireseult, 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 = bookList[idx].book_name;

            if (type == "Author")
                result = bookList[idx].author;

            if (type == "Publisher")
                result = bookList[idx].book_comp;

            if (type == "ISBN13")
                result = bookList[idx].isbn;

            return result;
        }

        private void NL_API(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 < bookList.Count; a++)
            {
                string[] grid = { "", "", "", "", "",
                    "", "", "", "" };

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

                progressBar1.PerformStep();

                var item = bookList[a];
                if (item.isbn == null)
                    item.isbn = "";

                string isbn = item.isbn;

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

                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "title";
                        target = item.book_name;
                        break;
                    case 1:
                        type = "author";
                        target = item.author;
                        break;
                    case 2:
                        type = "publisher";
                        target = item.book_comp;
                        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];
                        dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.LightGray;

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

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

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

                var item = bookList[a];
                if (item.isbn == null)
                    item.isbn = "";

                string isbn = item.isbn;
                string Target = "";

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

                #region 필터적용
                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        Target = item.book_name;
                        break;

                    case 1:
                        Target = item.author;
                        break;

                    case 2:
                        Target = item.book_comp;
                        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(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 < bookList.Count; a++)
            {
                progressBar1.PerformStep();

                var item = bookList[a];
                if (item.isbn == null)
                    item.isbn = "";

                string isbn = item.isbn;

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

                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "title";
                        query = item.book_name;
                        break;
                    case 1:
                        type = "person";
                        query = item.author;
                        break;
                    case 2:
                        type = "publisher";
                        query = item.book_comp;
                        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(List<string> data, int row)
        {
            if (row > 0) { dataGridView1.Rows[row - 1].Selected = false; }
            dataGridView1.Rows[row].Selected = true;

            if (data.Count > 0)
            {
                bookList[row].api_data = string.Join("|", data);
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            }
            //string[] insert = data.Split('|');

            if (data.Any() == false) { return; }

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

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

            if (data.Count > 11)
            {
                return;
            }
            if (cb_filter.SelectedItem.ToString() == "별치조사")
                input_api_aladin(data.ToArray(), row, newstring);
            input_api(data.ToArray(), 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)
        {
            var item = bookList[idx];
            item.search_book_name = value[0];
            item.search_author = value[1];
            item.search_book_comp = value[2];
            item.price = value[4];
            item.pubDate = date;
            item.category = 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];

                bookList[row].api_data += 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];

                bookList[row].api_data += 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 };

            var item = bookList[idx];
            string book_name = item.book_name;
            string author = item.author;
            string book_comp = item.book_comp;

            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])
            {

                item.search_book_name = value[0];
                item.search_author = value[1];
                item.search_book_comp = value[2];
                item.isbn = value[3];
                item.price = value[4];
                item.pubDate = date;
                item.category = value[6];
                item.sold_out = value[7];
                item.image = value[8];

                if (value.Length > 9)
                    item.search_description = value[9];
                else
                    item.search_description = string.Empty;

                if (value.Length > 10)
                    item.search_url = value[10];
                else
                    item.search_url = string.Empty;


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

        private void btn_Save_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < bookList.Count; a++)
            {
                var item = bookList[a];
                if (string.IsNullOrEmpty(item.isbn)) continue;

                var updateData = new Dictionary<string, object>
                {
                    { "isbn", item.isbn },
                    { "book_name", item.book_name },
                    { "author", item.author },
                    { "book_comp", item.book_comp },
                    { "pay", item.unit },
                    { "price", item.price },
                    { "pubDate", item.pubDate },
                    { "category", item.category },
                    { "image_url", item.image },
                    { "sold_out", item.sold_out },
                    { "etc", item.etc },
                    { "search_book_name", item.search_book_name },
                    { "search_author", item.search_author },
                    { "search_book_comp", item.search_book_comp },
                    { "search_description", item.search_description },
                    { "search_url", item.search_url }
                };

                var whereClause = new Dictionary<string, object>
                {
                    { item.etc.Contains("세트분할") ? "set_book_name" : "idx", item.idx },
                    { "list_name", list_name },
                    { "compidx", compidx }
                };

                string U_cmd = Helper_DB.Make_UpdateQuery("Obj_List_Book", updateData, whereClause);
                var ret = Helper_DB.ExcuteNonQuery(U_cmd);
                if(ret.applyCount != 1)
                {
                    UTIL.MsgE($"{ret.applyCount} 건의 자료가 업데이트 되었습니다\n개발자 문의 하세요\n\n{ret.errorMessage}");
                    return;
                }

                if (Check_Marc.Checked)
                {
                    string CMcmd = string.Format("UPDATE `Obj_List_Book` SET `isbn_marc` = \"{0}\" WHERE `idx` = \"{1}\"",
                        item.isbn, item.idx);
                    ret = Helper_DB.ExcuteNonQuery(CMcmd);
                    if (ret.applyCount != 1)
                    {
                        UTIL.MsgE($"{ret.applyCount} 건의 자료가 업데이트 되었습니다\n개발자 문의 하세요\n\n{ret.errorMessage}");
                        return;
                    }
                }
            }
            UTIL.MsgI("저장되었습니다!");
            save = true;
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var row = dataGridView1.Rows[e.RowIndex];
            var item = row.DataBoundItem as IsbnGridItem;

            if (item == null) return;

            using (var editForm = new Check_ISBN_ItemEdit(item))
            {
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    bs1.ResetBindings(false);
                    row.DefaultCellStyle.BackColor = Color.Yellow;
                    save = false;
                }
            }
        }
        private void SHOW_ISBN()
        {
            int idx = bs1.Position;
            if (idx < 0 || idx >= bookList.Count) return;
            if (string.IsNullOrEmpty(bookList[idx].api_data))
            {
                return;
            }
            var sub = new Check_ISBN_Sub2(this);
            sub.row = idx;
            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)
            {
                var bl = new Book_Lookup2(this);
                bl.TopMost = true;
                int idx = bs1.Position;
                if (idx < 0) return;
                var item = bookList[idx];
                bl.Lookup_Load(item.book_name, item.author, item.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)
        {
            var yes = new Check_ISBN_Yes242(this);
            yes.Show();
        }

        private void tb_list_name_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var search = new Order_input_Search2(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;
            }
        }

        private void bs1_CurrentChanged(object sender, EventArgs e)
        {
            //
            var item = bs1.Current as IsbnGridItem;
            if (item == null)
            {
                link_url.Text = "";
            }
            else
            {
                link_url.Text = item.search_url;
            }

        }

        private void link_url_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var url = link_url.Text;
            if (url.isEmpty()) return;
            System.Diagnostics.Process.Start(url);

        }
    }
}