using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using WindowsFormsApp1;
using System.Text.RegularExpressions;
using System.Diagnostics.Eventing.Reader;
using Org.BouncyCastle.Pkcs;

namespace ISBN_Check_test
{
    public partial class Form1 : Form
    {
        private int rowidx;
        public Form1()
        {
            InitializeComponent();
            this.dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
            this.Text = $"{Application.ProductName} ver {Application.ProductVersion}";
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Show();
            Application.DoEvents();
            string[] api_list = { "다음", "네이버", "알라딘" };
            cb_api.Items.AddRange(api_list);
            cb_api.SelectedIndex = 2;
            Application.DoEvents();
            cb_filter_SelectedIndexChanged(null, null);
            Application.DoEvents();

        }
        private void button2_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].DefaultCellStyle.BackColor != Color.Yellow)
                {
                    dataGridView1.Rows[a].Cells["Column1"].Value = "";
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            button2_Click(null, null);
            if (cb_api.SelectedIndex == -1) { MessageBox.Show("조건이 선택되지 않았습니다."); return; }
            if (cb_filter.SelectedIndex == -1) { MessageBox.Show("조건이 선택되지 않았습니다."); return; }

            this.dataGridView1.AutoResizeColumn(3);
            this.Refresh();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            if (int.TryParse(tbDelay.Text, out int delayms) == false)
            {
                MessageBox.Show("지연시간 입력 오류");
                return;
            }

            var sistr = start_idx.Text.Trim();
            var eistr = end_idx.Text.Trim();

            if (string.IsNullOrEmpty(sistr)) sistr = "1";
            if (string.IsNullOrEmpty(eistr)) eistr = "1";

            if (int.TryParse(sistr, out int si) == false)
            {
                MessageBox.Show("시작번호가 올바르지 않습니다");
                start_idx.Focus();
                return;
            }
            if (int.TryParse(eistr, out int ei) == false)
            {
                MessageBox.Show("종료번호가 올바르지 않습니다");
                start_idx.Focus();
                return;
            }

            ei = ei - 1;
            si = si - 1;
            if (si < 0 || ei < 0)
            {
                MessageBox.Show("시작,종료번호를 확인하세요");
                return;
            }

            if (ei < si)
            {
                MessageBox.Show("종료번호는 시작번호보다 같거나 커야 합니다");
                return;
            }


            progressBar1.Style = ProgressBarStyle.Continuous;
            progressBar1.Minimum = si;
            progressBar1.Maximum = ei;
            progressBar1.Step = 1;
            progressBar1.Value = progressBar1.Minimum;

            switch (cb_api.SelectedIndex)
            {
                case 0:
                    Daum_API(dataGridView1, si, ei);
                    break;
                case 1:
                    Naver_API(dataGridView1, si, ei);
                    break;
                case 2:
                    Aladin_API(dataGridView1, si, ei, delayms);
                    break;
            }

            stopwatch.Stop();

            TimeSpan ts = stopwatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            label1.Text = elapsedTime;
            rowidx = 0;

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

            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
            this.ActiveControl = dataGridView1;
        }
        /// <summary>
        /// 알라딘 API
        /// </summary>
        /// <param name="gridview"></param>
        private void Aladin_API(DataGridView gridview, int start, int end, int delayms)
        {
            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn13", "priceStandard",
                               "pubDate", "categoryName", "stockStatus", };
            API api = new API();
            for (int a = start; a <= end; a++)
            {
                process_Sub();
                string type;
                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "Keyword";
                        break;
                    case 1:
                        type = "Title";
                        break;
                    case 2:
                        type = "Author";
                        break;
                    case 3:
                        type = "Publisher";
                        break;
                    case 4:
                        type = "ISBN13";
                        break;
                    default:
                        type = "";
                        break;
                }
                // string query = dataGridView1.Rows[a].Cells["isbn"].Value?.ToString() ?? string.Empty;
                string query = Set_query(type, a); //a=는줄번호이고 idx는 -1 해야함
                if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.Yellow)
                    continue;
                else if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.LightGray)
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;

                // string aladin = api.Aladin(query, "ISBN13", param);
                //var aladin = api.Aladin(query, type, param);
                var aladin_struct = api.Aladin_struct(query, type, out string xmlString);
                insert_By_Aladin(aladin_struct, a, xmlString);
                if (aladin_struct.Any())
                    richTextBox1.Text = aladin_struct.First().ToString();
                else
                    richTextBox1.Text = "No Data";

                System.Threading.Thread.Sleep(delayms);
                //try
                //{
                //    var sb = new StringBuilder();
                //    foreach (var item in aladin)
                //    {
                //        sb.AppendLine(string.Join("|", item));
                //    }
                //    richTextBox1.Text = aladin_struct.ToString();// sb.ToString();
                //}
                //catch { }
            }
        }
        string Set_query(string type, int idx)
        {
            string result = string.Empty;

            if (type == "Keyword")
                result = (dataGridView1.Rows[idx].Cells["book_name"].Value?.ToString() ?? string.Empty) +
                         dataGridView1.Rows[idx].Cells["author"].Value?.ToString() ?? string.Empty;

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

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

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

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

            return result;
        }
        private void Naver_API(DataGridView gridview, int start, int end)
        {
            // 도서명 / 저자 / 출판사 / isbn / 정가
            // 발행일 / 도서분류 / 재고
            string[] param = { "title", "author", "publisher", "isbn", "price",
                               "pubdate", "discount" };
            API api = new API();
            List<string> L_type = new List<string>();
            List<string> L_Array = new List<string>();

            for (int a = start; a <= end; a++)
            {
                L_type.Clear();
                L_Array.Clear();
                process_Sub();
                if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.Yellow)
                    continue;
                else if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.LightGray)
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;

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

                    case 1:
                        L_type.Add("d_auth");
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        break;

                    case 2:
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;

                    case 3:
                        L_type.Add("d_titl");
                        L_type.Add("d_auth");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        break;

                    case 4:
                        L_type.Add("d_titl");
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;

                    case 5:
                        L_type.Add("d_auth");
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;

                    case 6:
                        L_type.Add("d_titl");
                        L_type.Add("d_auth");
                        L_type.Add("d_publ");
                        L_Array.Add(gridview.Rows[a].Cells["book_name"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["author"].Value.ToString());
                        L_Array.Add(gridview.Rows[a].Cells["book_comp"].Value.ToString());
                        break;
                }
                #endregion

                string[] arrayType = L_type.ToArray();
                string[] arrayValue = L_Array.ToArray();
                string result = api.Naver(arrayValue, arrayType, param);
                insert_By_Naver(result, a);
                Thread.Sleep(700);
            }
        }
        private void Daum_API(DataGridView gridview, int start, int end)
        {
            string[] param = { "title", "authors", "publisher", "isbn", "price",
                               "datetime", "status" };
            string type = string.Empty;
            string query = string.Empty;
            API api = new API();

            for (int a = start; a <= end; a++)
            {
                process_Sub();
                if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.Yellow)
                    continue;
                else if (gridview.Rows[a].DefaultCellStyle.BackColor == Color.LightGray)
                    gridview.Rows[a].DefaultCellStyle.BackColor = Color.Empty;

                switch (cb_filter.SelectedIndex)
                {
                    case 0:
                        type = "title";
                        query = gridview.Rows[a].Cells["book_name"].Value?.ToString() ?? string.Empty;
                        break;
                    case 1:
                        type = "person";
                        query = gridview.Rows[a].Cells["author"].Value?.ToString() ?? string.Empty;
                        break;
                    case 2:
                        type = "publisher";
                        query = gridview.Rows[a].Cells["book_comp"].Value?.ToString() ?? string.Empty;
                        break;
                }
                if (query == "") { continue; }

                string result = api.Daum(query, type, param);
                richTextBox1.Text = result;
                insert_By_Daum(result, a);
            }
        }
        private void process_Sub()
        {
            progressBar1.PerformStep();
        }

        void insert_By_Aladin(List<AladinBookData> insert, int row, string xmlString)
        {
            if (row > 0)
            {
                dataGridView1.Rows[row - 1].Selected = false;
            }
            dataGridView1.Rows[row].Selected = true;

            //데이터가 없다면 처리하지 않는다.
            if (insert.Any() == false)
            {
                dataGridView1.Rows[row].Cells["count"].Value = "0";
                dataGridView1.Rows[row].Cells["dvc_remark"].Value = $"No Data\n{xmlString}";
                return;
            }

            var item = insert.First();

            // pubDate형 보기편하게 DateTime형으로 재정리
            string pubdate = item.PubDate;
            try
            {
                //pubdate = item.PubDate;
                pubdate = String.Format("{0:yyyy/MM/dd}",
                    DateTime.Parse(pubdate.Remove(pubdate.IndexOf(" G"))));
            }
            catch (Exception ex) { MessageBox.Show(item.ToString()); }

            //카테고리명 정리
            item.CategoryName = Aladin_CategorySort(item.CategoryName);
            //for (int a = 0; a < insert.Length; a++)
            //{
            //    if (a % 8 == 6) { insert[a] = Aladin_CategorySort(insert[a]); }
            //}

            dataGridView1.Rows[row].Cells["Column1"].Value += item.ToString();// string.Join("|", insert) + "|";
            if (item.Description.StartsWith("<")) item.Description = item.Description.Substring(item.Description.IndexOf(">")+1);
            dataGridView1.Rows[row].Cells["dvc_remark"].Value = item.Description;// $"{insert.Count}건";
            dataGridView1.Rows[row].Cells["dvc_link"].Value = $"{item.Link}";
            dataGridView1.Rows[row].Cells["count"].Value = $"{insert.Count}";
            dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.LightGray;
            if (cb_filter.SelectedItem.ToString() == "별치조사")
                input_api_aladin(item, row, pubdate);

            input_api(item, row, pubdate);
        }
        void insert_By_Aladin(string[] insert, int row)
        {
            if (row > 0)
            {
                dataGridView1.Rows[row - 1].Selected = false;
            }
            dataGridView1.Rows[row].Selected = true;


            if (insert.Any() == false) { 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) { MessageBox.Show(string.Join("|", insert)); }

            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);
        }
        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(AladinBookData data, int row, string date)
        {
            dataGridView1.Rows[row].Cells["book_name"].Value = data.Title;
            dataGridView1.Rows[row].Cells["author"].Value = data.Author;
            dataGridView1.Rows[row].Cells["book_comp"].Value = data.Publisher;
            dataGridView1.Rows[row].Cells["price2"].Value = data.PriceStandard;
            dataGridView1.Rows[row].Cells["pubDate"].Value = date;
            dataGridView1.Rows[row].Cells["category"].Value = data.CategoryName;
        }

        void input_api_aladin(string[] data, int row, string date)
        {
            dataGridView1.Rows[row].Cells["book_name"].Value = data[0];
            dataGridView1.Rows[row].Cells["author"].Value = data[1];
            dataGridView1.Rows[row].Cells["book_comp"].Value = data[2];
            dataGridView1.Rows[row].Cells["price2"].Value = data[4];
            dataGridView1.Rows[row].Cells["pubDate"].Value = date;
            dataGridView1.Rows[row].Cells["category"].Value = data[6];
        }
        void insert_By_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 분류작업
            /* 0 : 도서명
             * 1 : 저자
             * 2 : 출판사
             * 3 : ISBN
             * 4 : 판매가
             * 5 : 출간일
             * 6 : 카테고리
             * 7 : 품절/절판 */
            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 - 4; b++)
                {
                    grid[1] += ", " + data[b];
                }
                grid[2] = data[idx - 4];
                if (data[idx - 3].Contains(" ") == true)
                {
                    string[] isbn = data[idx - 3].Split(' ');
                    grid[3] = isbn[1];
                }
                else
                    grid[3] = data[idx - 3];

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

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

                dataGridView1.Rows[row].Cells["Column1"].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 { }

            input_api(grid, row, newstring);
        }
        void insert_By_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];
                try
                {
                    grid[5] = data[5].Substring(0, 10);
                }
                catch { }
                grid[7] = data[6];

                dataGridView1.Rows[row].Cells["Column1"].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;

            bool[] chk = { false, false, false };
            // string newstring = DateTime.ParseExact(grid[5], "yyyyMMdd", null).ToString("yyyy-MM-dd");
            string newstring = grid[5];

            input_api(grid, row, newstring);
        }

        void input_api(AladinBookData value, int idx, string date)
        {

            //string[] param = { "title", "authors", "publisher", "isbn", "price",
            //                   "datetime", "status" };
            //string[] param = { "title", "author", "publisher", "isbn13", "priceStandard",
            //                   "pubDate", "categoryName", "stockStatus", };

            bool[] chk = { false, false, false };

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

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

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

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

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

                dataGridView1.Rows[idx].Cells["isbn"].Value = value.Isbn13;
                dataGridView1.Rows[idx].Cells["price2"].Value = value.PriceStandard;
                dataGridView1.Rows[idx].Cells["pubDate"].Value = date;
                //if (cb_api.SelectedIndex == 2)
                dataGridView1.Rows[idx].Cells["category"].Value = value.CategoryName;
                dataGridView1.Rows[idx].Cells["sold_out"].Value = value.StockStatus;
                dataGridView1.Rows[idx].DefaultCellStyle.BackColor = Color.Yellow;
            }
            count_res();
        }


        /// <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.Empty;
            string author = dataGridView1.Rows[idx].Cells["author"].Value?.ToString() ?? string.Empty;
            string book_comp = dataGridView1.Rows[idx].Cells["book_comp"].Value?.ToString() ?? string.Empty;

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

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

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

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

                dataGridView1.Rows[idx].Cells["isbn"].Value = value[3];
                dataGridView1.Rows[idx].Cells["price2"].Value = value[4];
                dataGridView1.Rows[idx].Cells["pubDate"].Value = date;
                //if (cb_api.SelectedIndex == 2)
                dataGridView1.Rows[idx].Cells["category"].Value = value[6];
                dataGridView1.Rows[idx].Cells["sold_out"].Value = value[7];
                dataGridView1.Rows[idx].DefaultCellStyle.BackColor = Color.Yellow;
            }
            count_res();
        }
        #region 검색갯수 계산
        private void count_res()
        {
            //String_Text st = new String_Text();
            //int count = dataGridView1.Rows.Count;
            //for (int a = 0; a < count; a++)
            //{
            //    string search_data = dataGridView1.Rows[a].Cells["Column1"].Value?.ToString() ?? string.Empty;
            //    int tmp_count = st.Char_count(search_data, '|');
            //    int lcount = tmp_count / 8;
            //    dataGridView1.Rows[a].Cells["count"].Value = lcount.ToString();
            //}
        }
        #endregion
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();

            if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V))
            {
                sg.Excel_to_DataGridView(sender, e);
            }
            else if (e.KeyCode == Keys.Delete)
            {
                sg.DataGrid_to_Delete(sender, e);
            }
            if (e.KeyCode == Keys.Enter) { dataGridView1_CellDoubleClick(null, null); rowidx++; }
            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;
            }
            end_idx.Text = dataGridView1.Rows.Count.ToString();
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();

            sg.Print_Grid_Num(sender, e);
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            rowidx = e.RowIndex;
            if (rowidx < 0) return;
            if (dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value == null)
                dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value = "";

            richTextBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value?.ToString() ?? string.Empty;
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var column = this.dataGridView1.Columns[e.ColumnIndex];

            if (column.Name.Equals("dvc_remark"))
            {
                var value = this.dataGridView1.Rows[e.RowIndex].Cells[column.Name].Value?.ToString() ?? string.Empty;
                if(value.StartsWith("<"))
                {
                    value = value.Substring(value.IndexOf(">") + 1);
                }
                else this.richTextBox1.Text = value;
            }
            else if (column.Name.Equals("Column"))
            {
                var value = this.dataGridView1.Rows[e.RowIndex].Cells[column.Name].Value?.ToString() ?? string.Empty;
                if (value == string.Empty) return;

                Form2 f2 = new Form2(this);
                f2.row = rowidx;
                f2.Call_API = cb_api.Text;
                f2.Show();
            }
            else if (column.Name.Equals("dvc_link"))
            {
                var value = this.dataGridView1.Rows[e.RowIndex].Cells[column.Name].Value?.ToString() ?? string.Empty;
                if (value == string.Empty) return;
                try
                {
                    var prc = new System.Diagnostics.Process();
                    prc.StartInfo = new System.Diagnostics.ProcessStartInfo()
                    {
                        FileName = value,
                        UseShellExecute = true
                    };
                    prc.Start();
                }
                catch (Exception ex)
                {

                }
            }


        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back)))
                e.Handled = true;
        }
        private void cb_api_SelectedIndexChanged(object sender, EventArgs e)
        {
            cb_filter.Items.Clear();
            if (cb_api.SelectedIndex == 0)
            {
                string[] daum = { "도서명", "저자", "출판사" };
                cb_filter.Items.AddRange(daum);
            }
            else if (cb_api.SelectedIndex == 1)
            {
                string[] naver = { "도서명", "저자", "출판사",
                                   "도서명 + 저자", "도서명 + 출판사", "저자 + 출판사",
                                   "도서명 + 저자 + 출판사" };
                cb_filter.Items.AddRange(naver);
            }
            else if (cb_api.SelectedIndex == 2)
            {
                string[] aladin = { "도서명 + 저자", "도서명", "저자", "출판사", "별치조사" };
                cb_filter.Items.AddRange(aladin);
                cb_filter.SelectedIndex = cb_filter.Items.Count - 1;
            }
            Must_Col(cb_api.SelectedIndex);
        }
        private void Must_Col(int cb_idx)
        {
            if (cb_idx == 0 || cb_idx == 1 || cb_idx == 2)
            {
                dataGridView1.Columns["isbn"].DefaultCellStyle.BackColor = Color.Empty;
                dataGridView1.Columns["book_name"].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
                dataGridView1.Columns["author"].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
                dataGridView1.Columns["book_comp"].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
            }
            else
            {
                return;
            }
        }
        private void btn_Yes24_Click(object sender, EventArgs e)
        {
            Yes24 yes24 = new Yes24(this);
            yes24.Show();
        }

        private void cb_filter_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cb_filter.SelectedItem.ToString() == "별치조사")
            {
                dataGridView1.Columns["isbn"].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
                dataGridView1.Columns["book_name"].DefaultCellStyle.BackColor = Color.Empty;
                dataGridView1.Columns["author"].DefaultCellStyle.BackColor = Color.Empty;
                dataGridView1.Columns["book_comp"].DefaultCellStyle.BackColor = Color.Empty;
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                string[] lst = {  "9788965427520",
                    "9791193110584",
                "9791168672260",
                "9788993858396",
                "9791171200351",
                "9791199239043",
                "9791194828112",
                "9791196026523",
                "9791194368359",
                "9791191744439",
                "9791198843067",
                "9788999712883",
                "9788999729188"};
                foreach (var item in lst)
                    this.dataGridView1.Rows.Add(new string[] { "", "", "", item });
                end_idx.Text = (this.dataGridView1.Rows.Count - 1).ToString();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                //if (dataGridView1.Rows[a].DefaultCellStyle.BackColor != Color.Yellow)
                {
                    dataGridView1.Rows[a].Cells["Column1"].Value = "";
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
        }
    }
}
