using Microsoft.VisualBasic;
using System;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Windows.Forms;
using BokBonCheck;
using AR;

namespace UniMarc
{
    public partial class Check_copy : Form
    {
        Helper_DB db = new Helper_DB();
        public string URL;
        public string lib_Category;
        public string Code;
        public string SearcherNo;
        private bool isStop = false;
        Main main;
        public Check_copy(Main _main)
        {
            InitializeComponent();
            main = _main;
            db.DBcon();
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Print_Grid_Num(sender, e);
        }

        private void Check_copy_Load(object sender, EventArgs e)
        {
            string[] Grid = { "----- 빈칸으로 놔주세요 -----", "빈칸", "" };
            dataGridView1.Rows.Add(Grid);

            this.Show();
            Application.DoEvents();
        }


        private void tb_SearchTarget_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SearchLibrary();
            }
        }
        void SearchLibrary()
        {
            string Target = tb_SearchTarget.Text;
            // if (Target == "") { MessageBox.Show("도서관명이 비어있습니다."); return; }

            string area = "`Province`, `Area`, `LibName`, `Code`, `URL`, `SearcherNo`";
            string cmd = string.Format("SELECT {0} FROM `lib_CopyCheck` WHERE CONCAT( province , '_' , AREA , '_' , libname) LIKE '%{1}%' and ifnull(searcherno,0) = 0;", area, Target);
            string data = db.self_Made_Cmd(cmd);
            string[] ary = data.Split('|');
            Check_Copy_Sub_Search ccs = new Check_Copy_Sub_Search(this);
            ccs.Init(ary, Target);
            ccs.Show();
        }

        private void btn_SearchList_Click(object sender, EventArgs e)
        {
            Check_Copy_Sub_List cl = new Check_Copy_Sub_List(this);
            cl.Show();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Excel_to_DataGridView(sender, e);

            SearchCount.Value = dataGridView1.Rows.Count;
        }

         private void btn_Start_Click(object sender, EventArgs e)
        {
            var libraryName = tb_SearchTarget.Text.Trim();
            if (libraryName.isEmpty())
            {
                tb_SearchTarget.Focus();
                UTIL.MsgE("도서관을 선택하세요");
                return;
            }
            if (libraryName.Contains("Kolasys.net"))
            {
                if (lbl_ID.Text == " " || lbl_PW.Text == " ")
                {
                    UTIL.MsgE("해당 도서관은 로그인정보가 필요합니다.\n복본조사 창을 껏다켜주세요.");
                    return;
                }
            }



            isIksanClick = false;
            isJBEClick = false;
            isJNLClick = false;
            isGwangJuNamGuClick = false;
            isKJKClick = false;
            isMokClick = false;
            isWandoClick = false;

            SearchCount.Value = dataGridView1.Rows.Count;   //250619
            RowCount = 0;   //250619

            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];

            int SCount = Convert.ToInt32(SearchCount.Value);

            if (SearcherNo.toInt() < 1)
            {
                //legacy
                webBrowser1.Visible = true;
                webBrowser1.Navigate("");
                if (URL is null)
                {
                    webBrowser1.DocumentCompleted -= this.webBrowser1_DocumentCompleted;
                    return;
                }
                else if (URL.IndexOf("lib.jeonnam.go.kr") > -1)
                {
                    for (int a = 0; a < SCount; a++)
                    {
                        if (dataGridView1.Rows[a].Cells["book_name"].Value == null)
                            continue;

                        if (dataGridView1.Rows[a].Cells["book_name"].Value.ToString() == "")
                            continue;

                        if (isStop)
                            break;

                        string BookSearchCount = CopyCount(dataGridView1.Rows[a].Cells["book_name"].Value.ToString());

                        if (BookSearchCount == "false")
                        {
                            UTIL.MsgE("검색대상이 설정되지않았습니다!");
                            return;
                        }

                        if (BookSearchCount == "0" || BookSearchCount == "" || BookSearchCount == "미소장")
                        {
                            dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.LightGray;
                            dataGridView1.Rows[a].DefaultCellStyle.ForeColor = Color.Red;
                            BookSearchCount = "";
                        }
                        else
                        {
                            dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Yellow;
                            dataGridView1.Rows[a].DefaultCellStyle.ForeColor = Color.Blue;
                        }

                        int tmp = RowCount - 1;
                        if (tmp < 0) tmp = 0;

                        BookSearchCount = IsHave(BookSearchCount, tmp);
                        dataGridView1.Rows[a].Cells["Count"].Value = BookSearchCount;
                    }
                }
                else
                {
                    if (URL.IndexOf("218.157.123.2:9996/kcms/Main") > -1)
                        webBrowser1.Navigate(URL + "/" + Code);

                    else
                        webBrowser1.Navigate(URL);

                    webBrowser1.DocumentCompleted += this.webBrowser1_DocumentCompleted;
                    return;
                }

            }
            else
            {
                UTIL.MsgE("이 기능은 WebDriver 에서 실행하세요");
            }
        }

        int RowCount = 0;
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (RowCount < 0)
                return;

            if (RowCount == SearchCount.Value)
            {
                webBrowser1.DocumentCompleted -= this.webBrowser1_DocumentCompleted;
                UTIL.MsgI("조사가 완료되었습니다!");
                RowCount = 0;
                return;
            }

            string URL = webBrowser1.Url.AbsoluteUri;
            string BookCount = "";
            var val_bookName = dataGridView1.Rows[RowCount].Cells["book_name"].Value;
            if (val_bookName == null) return;

            string text = val_bookName.ToString();

            if (text == "----- 빈칸으로 놔주세요 -----")
                return;

            // 광주 시립 (무등, 사직, 산수)
            if (URL.IndexOf("citylib.gwangju.kr/main/bookSearch") > -1)
            {
                if (URL.IndexOf("keyword") > -1)
                    BookCount = 광주시립결과();

                광주시립입력(text);
            }

            // 광주 남구 (문화정보, 푸른길, 청소년)
            else if (URL.IndexOf("searchlib.namgu.gwangju.kr") > -1 || URL.IndexOf("lib.namgu.gwangju.kr") > -1)
            {
                //if (URL.IndexOf("word") > -1)
                //    BookCount = 광주남구결과();

                HtmlElement searchform = null;  //250619 검색결과를 통해서 내용 추측
                foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("div"))
                {
                    if (he.GetAttribute("class").ToLower().Equals("search-result"))
                    {
                        searchform = he;
                        break;
                    }
                }
                if (searchform != null)
                {
                    BookCount = 광주남구결과();
                }



                광주남구입력(text);
            }
            //광주 서구
            //else if (URL.IndexOf("library.seogu.gwangju.kr") > -1)
            //{
            //    //if (URL.IndexOf("word") > -1)
            //    //    BookCount = 광주서구결과();

            //    BookCount = 광주서구입력(text);
            //}
            // 광주 북구 (일곡, 운암, 양산)
            else if (URL.IndexOf("lib.bukgu.gwangju.kr") > -1)
            {
                BookCount = 광주북구입력(text);
            }

            // 광주 광산구 (장덕, 이야기꽃, 첨단, 신가, 운남어린이, 스마트)
            else if (URL.IndexOf("lib.gwangsan.go.kr") > -1)
            {
                if (URL.IndexOf("query") > -1)
                    BookCount = 광주광산구결과();

                광주광산구입력(text);
            }

            // 광주 교육청 (학생독립, 중앙, 학생교육, 금호평생, 광주송정, 석봉)
            else if (URL.IndexOf("lib.gen.go.kr") > -1)
            {
                if (URL.IndexOf("search_txt") > -1)
                    BookCount = 광주교육청결과();

                광주교육청입력(text);
            }

            // 전남 교육청 (목포, 나주, 남평, 광양, 담양 ... 순천만생채문화교육원 등 총 26개 도서관)
            else if (URL.IndexOf("jnelib.jne.go.kr") > -1)
            {
                BookCount = 전남교육청입력(text);
            }

            // 전남 진도 (진도철마, 새섬작은, 의신백구)
            else if (URL.IndexOf("lib.jindo.go.kr") > -1)
            {
                if (URL.IndexOf("simple") > -1)
                    BookCount = 전남진도결과();

                전남진도입력(text);
            }

            // 전남 완도 (완도군립, 노화공공, 금일공공, 보길윤선도작은, 군외동백숲작은, 도담도담작은)
            else if (URL.IndexOf("book.wando.go.kr") > -1)
            {
                BookCount = 전남완도입력(text);
            }

            // 전남 도립 TODO: 오류발생 (원인불명) [한번에 3개씩 검색결과가 표출됨]
            /*
            else if (URL.IndexOf("lib.jeonnam.go.kr") > -1)
            {
                //Delay(500);
                if (URL.IndexOf("value") > -1)
                    BookCount = 전남도립결과();
            
                전남도립입력(text);
            }
            */

            // 전남 고흥 (군립중앙, 군립남부, 군립북부 등 총 7개 도서관)
            else if (URL.IndexOf("ghlib.go.kr/BookSearch") > -1)
            {
                if (URL.IndexOf("simple") > -1)
                    BookCount = 전남고흥결과();

                전남고흥입력(text);
            }

            // 전남 여수 (쌍봉, 현암, 환경, 돌산 등 총 31개 도서관) 
            else if (URL.IndexOf("218.157.123.2:9996/kcms") > -1)
            {
                if (URL.IndexOf("KBookSearch") > -1)
                    BookCount = 전남여수결과();

                전남여수입력(text);
            }

            // 전남 무안군 공공도서관
            else if (URL.IndexOf("muan.go.kr/lib/data/search") > -1)
            {
                BookCount = 전남무안입력(text);
            }

            // 전남 목포 시립도서관
            else if (URL.IndexOf("mokpolib.or.kr/dls_lt/index.php") > -1)
            {
                if (URL.IndexOf("searchWord") > -1)
                    BookCount = 전남목포결과();

                전남목포입력(text);
            }

            // 전남 순천 시립도서관
            else if (URL.IndexOf("library.suncheon.go.kr") > -1)
            {
                BookCount = 전남순천입력(text);
            }

            // 전북대학교 도서관
            else if (URL.IndexOf("dl.jbnu") > -1)
            {
                if (URL.IndexOf("result") > -1)
                    BookCount = 전북대결과();

                전북대입력(text);
            }

            // 조선대학교 중앙도서관
            else if (URL.IndexOf("library.chosun") > -1)
            {
                if (URL.IndexOf("result") > -1)
                    BookCount = 조대도서관결과();

                조대도서관입력(text);
            }

            // 전북교육청 소재 도서관
            else if (URL.IndexOf("lib.jbe.go.kr") > -1)
            {
                BookCount = 전북교육청입력(text);
            }

            // 익산통합도서관
            else if (URL.IndexOf("lib.iksan.go.kr") > -1)
            {
                if (URL.IndexOf("search_txt_add") > -1)
                    BookCount = 익산통합도서관결과();

                익산통합도서관입력(text);
            }

            // 안산 중앙도서관
            else if (URL.IndexOf("lib.ansan.go.kr") > -1)
            {
                BookCount = 안산중앙도서관입력(text);
            }

            // 송원대학교 중앙도서관
            else if (URL.IndexOf("lib.songwon.ac.kr") > -1)
            {
                if (URL.IndexOf("searchTruncate") > -1)
                    BookCount = 송원대중앙도서관결과();

                송원대중앙도서관입력(text);
            }

            int tmp = RowCount - 1;
            if (tmp < 0) tmp = 0;

            BookCount = IsHave(BookCount, tmp);
            dataGridView1.Rows[tmp].Cells["Count"].Value = BookCount;
            RowCount++;
        }

        /// <summary>
        /// 입력된 카운트를 소장/미소장으로 바꿔서 반환
        /// </summary>
        /// <param name="Count">소장 몇권인지</param>
        /// <returns>소장 혹은 미소장으로 반환</returns>
        private string IsHave(string Count, int RowCount)
        {
            if (Count == "" || Count == "0" || Count == "미소장")
            {
                dataGridView1.Rows[RowCount].DefaultCellStyle.BackColor = Color.LightGray;
                dataGridView1.Rows[RowCount].DefaultCellStyle.ForeColor = Color.Red;

                if (rb_isHave.Checked)
                    return "";
                else
                    return Count;
            }

            dataGridView1.Rows[RowCount].DefaultCellStyle.BackColor = Color.Yellow;
            dataGridView1.Rows[RowCount].DefaultCellStyle.ForeColor = Color.Blue;

            if (rb_isHave.Checked)
                return "소장";
            else
                return Count;
        }

        #region 광주 소재 도서관

        #region 광주 시립
        void 광주시립입력(string text)
        {
            webBrowser1.Document.GetElementById("searchKeyword").SetAttribute("value", text);

            webBrowser1.Document.GetElementById("libCode").SetAttribute("value", Code);

            HtmlElementCollection button = webBrowser1.Document.GetElementsByTagName("button");
            foreach (HtmlElement SearchButton in button)
            {
                if (SearchButton.GetAttribute("className").IndexOf("bookSearchBtn") > -1)
                    SearchButton.InvokeMember("click");
            }
        }

        string 광주시립결과()
        {
            string result = "";

            HtmlElementCollection hecDiv = webBrowser1.Document.GetElementsByTagName("div");
            foreach (HtmlElement heDiv in hecDiv)
            {
                if (heDiv.GetAttribute("className").IndexOf("srch_info") > -1)
                {
                    HtmlElementCollection hecLi = heDiv.GetElementsByTagName("span");
                    foreach (HtmlElement heLi in hecLi)
                    {
                        if (heLi.GetAttribute("className").IndexOf("heighlight") > -1)
                        {
                            result = heLi.InnerText;
                            break;
                        }
                    }
                }
            }
            return result;
        }
        #endregion

        #region 광주 남구
        bool isGwangJuNamGuClick = false;
        void 광주남구입력(string text)
        {
            HtmlElement searchform = null;
            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("form"))
            {
                if (he.GetAttribute("id").ToLower().Equals("searchform"))
                {
                    searchform = he;
                    break;
                }
            }

            foreach (HtmlElement he in searchform.GetElementsByTagName("input"))
            {
                if (he.GetAttribute("id").ToLower().Equals("query"))
                {
                    if (!isGwangJuNamGuClick)
                    {
                        he.InvokeMember("click");
                        isGwangJuNamGuClick = true;
                    }
                }
            }

            foreach (HtmlElement he in searchform.GetElementsByTagName("input"))
            {
                if (he.Id != null && he.Id.ToLower().Equals("query"))//"searchWord")
                {
                    he.SetAttribute("value", text);
                }
            }
            // webBrowser1.Document.GetElementById("searchWord").SetAttribute("value", text);


            foreach (HtmlElement Btn in searchform.GetElementsByTagName("button"))
            {
                if (Btn.GetAttribute("type").IndexOf("submit") > -1)//.IndexOf("btn btn-search") > -1)
                    Btn.InvokeMember("click");
            }
        }

        string 광주남구결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("strong");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("cyan") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }

            return result;
        }
        #endregion
        #region 광주 서구
        bool isKJSeoClick = false;
        string 광주서구입력(string text)
        {
            string result = "";
            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (he.Name.IndexOf("libcodes") > -1)
                {
                    if (!he.Id.Contains("libcode129004") && !isKJSeoClick)
                    {
                        he.InvokeMember("click");
                    }
                }
            }
            isKJSeoClick = true;
            webBrowser1.Document.GetElementById("searchword").SetAttribute("value", text);

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (Btn.GetAttribute("className").IndexOf("seachBbsBt") > -1)
                    Btn.InvokeMember("click");
            }
            Delay(3000);

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("p");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("board_list") > -1)
                {
                    if (heTd.TagName == "P")
                    {
                        result = Regex.Replace(heTd.InnerText, @"\D", "");
                    }
                }
            }

            return result;
        }
        string 광주서구결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("strong");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("cyan") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }

            return result;
        }
        #endregion
        #region 광주 북구
        bool isKJKClick = false;
        string 광주북구입력(string text)
        {
            string result = "";
            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (he.Name.IndexOf("libCode") > -1)
                {
                    if (!he.Id.Contains(Code) && !isKJKClick)
                    {
                        he.InvokeMember("click");
                    }
                }
            }
            isKJKClick = true;
            webBrowser1.Document.GetElementById("searchSimple").SetAttribute("value", text);

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (Btn.GetAttribute("className").IndexOf("btn btn-lg") > -1)
                    Btn.InvokeMember("click");
            }
            Delay(3000);

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("p");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("totalCount") > -1)
                {
                    if (heTd.TagName == "P")
                    {
                        result = Regex.Replace(heTd.InnerText, @"\D", "");
                    }
                }
            }

            return result;
        }

        #endregion

        #region 광주 광산구

        void 광주광산구입력(string text)
        {
            webBrowser1.Document.GetElementById("query").SetAttribute("value", text);

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (Btn.GetAttribute("className") == "btn btn-lg")
                    Btn.InvokeMember("click");
            }
        }

        string 광주광산구결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("p");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("totalCount") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }

            return result;
        }
        #endregion

        #region 광주 교육청

        void 광주교육청입력(string text)
        {
            webBrowser1.Document.GetElementById("manage_code").SetAttribute("value", Code);

            webBrowser1.Document.GetElementById("search_txt").SetAttribute("value", text);

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (Btn.GetAttribute("id").IndexOf("search_txt") > -1)
                    Btn.SetAttribute("value", text);
                if (Btn.GetAttribute("className").IndexOf("btn-search") > -1)
                    Btn.InvokeMember("click");
            }
        }

        string 광주교육청결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("span");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.InnerText.IndexOf("전체") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }
            return result;
        }

        #endregion

        #region 조선대학교 중앙도서관

        void 조대도서관입력(string text)
        {
            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.GetAttribute("className").IndexOf("searchInput") > -1)
                    input.SetAttribute("value", text);

                if (input.GetAttribute("className").IndexOf("searchBtn") > -1)
                {
                    input.InvokeMember("click");
                    break;
                }
            }
        }

        string 조대도서관결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("span");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("catalogsCnt") > -1)
                {
                    result = heTd.InnerText;
                    break;
                }
            }
            return result;
        }
        #endregion

        #region 송원대학교 중앙도서관

        void 송원대중앙도서관입력(string text)
        {
            webBrowser1.Document.GetElementById("q").SetAttribute("value", text);
            webBrowser1.Document.GetElementById("opacsearch").InvokeMember("click");
        }

        string 송원대중앙도서관결과()
        {
            string result = "";

            foreach (HtmlElement strong in webBrowser1.Document.GetElementsByTagName("strong"))
            {
                result = strong.InnerText;
                break;
            }
            return result;
        }

        #endregion

        #endregion

        #region 전남 소재 도서관

        #region 전남 교육청
        bool isJNLClick = false;
        string 전남교육청입력(string text)
        {
            string result = "";

            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (he.Id != null && he.Id.IndexOf(Code) > -1 && !isJNLClick)
                {
                    he.InvokeMember("click");
                    isJNLClick = true;
                    Delay(500);
                }
                if (he.Name.IndexOf("searchWordText") > -1)
                {
                    he.SetAttribute("value", text);
                }
            }

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (Btn.GetAttribute("value") == "소장자료 검색")
                    Btn.InvokeMember("click");
            }
            Delay(3000);

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("span");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("txt_bold") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                    break;
                }
            }

            return result;
        }

        #endregion

        #region 전남 진도

        void 전남진도입력(string text)
        {
            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (he.GetAttribute("value").IndexOf(Code) > -1)
                {
                    he.InvokeMember("click");
                }
                if (he.Name.IndexOf("query") > -1)
                {
                    he.SetAttribute("value", text);
                }
            }

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (Btn.GetAttribute("className").IndexOf("btn btn-lg") > -1)
                    Btn.InvokeMember("click");
            }
        }

        string 전남진도결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("p");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("totalCount") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }

            return result;
        }
        #endregion

        #region 전남 완도

        bool isWandoClick = false;
        string 전남완도입력(string text)
        {

            foreach (HtmlElement DIV in webBrowser1.Document.GetElementsByTagName("div"))
            {
                if (DIV.GetAttribute("className").IndexOf("search") > -1)
                {
                    HtmlElementCollection FindSearch = DIV.GetElementsByTagName("input");
                    foreach (HtmlElement search in FindSearch)
                    {
                        if (search.Name.IndexOf("word") > -1)
                            search.SetAttribute("value", text);
                    }
                }
            }
            if (!isWandoClick)
            {
                foreach (HtmlElement DIV in webBrowser1.Document.GetElementsByTagName("div"))
                {
                    if (DIV.GetAttribute("className").IndexOf("wrapbox") > -1)
                    {
                        HtmlElementCollection FindChk = DIV.GetElementsByTagName("input");
                        foreach (HtmlElement chk in FindChk)
                        {
                            if (chk.GetAttribute("value").IndexOf(Code) > -1)
                            {
                                chk.InvokeMember("click");
                                isWandoClick = true;
                            }
                        }
                    }
                }
            }

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (Btn.GetAttribute("className").IndexOf("btn-search") > -1)
                    Btn.InvokeMember("click");
            }

            Delay(4000);

            string result = "";

            HtmlElementCollection hech3 = webBrowser1.Document.GetElementsByTagName("strong");
            foreach (HtmlElement heh3 in hech3)
            {
                if (heh3.GetAttribute("className").IndexOf("cyan") > -1)
                {
                    result = Regex.Replace(heh3.InnerText, @"\D", "");
                }
            }

            return result;
        }
        #endregion

        #region 전남 도립 (오류발생)

        void 전남도립입력(string text)
        {

            HtmlElementCollection div = webBrowser1.Document.GetElementsByTagName("div");
            foreach (HtmlElement SearchDiv in div)
            {
                if (SearchDiv.GetAttribute("className") == "booksearch")
                {
                    HtmlElementCollection hInput = SearchDiv.GetElementsByTagName("input");
                    foreach (HtmlElement Input in hInput)
                    {
                        if (Input.GetAttribute("className").IndexOf("search_main") > -1)
                            Input.SetAttribute("value", text);
                    }

                    HtmlElementCollection hBtn = SearchDiv.GetElementsByTagName("button");
                    foreach (HtmlElement Btn in hBtn)
                    {
                        if (Btn.InnerText == "검색")
                            Btn.InvokeMember("click");
                    }
                }
            }
        }

        string 전남도립결과()
        {
            string result = "";

            Delay(300);

            HtmlElementCollection hecDiv = webBrowser1.Document.GetElementsByTagName("div");
            foreach (HtmlElement heDiv in hecDiv)
            {
                if (heDiv.GetAttribute("className").IndexOf("booksearch_info") > -1)
                {
                    HtmlElementCollection hecLi = heDiv.GetElementsByTagName("font");
                    foreach (HtmlElement heLi in hecLi)
                    {
                        if (heLi.InnerText.IndexOf("전체") > -1)
                        {
                            result = Regex.Replace(heLi.InnerText, @"\D", "");
                            break;
                        }
                    }
                }
            }

            return result;
        }
        #endregion

        #region 전남 고흥

        void 전남고흥입력(string text)
        {
            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (he.GetAttribute("id").IndexOf(Code) > -1)
                {
                    he.InvokeMember("click");
                }
            }

            webBrowser1.Document.GetElementById("query").SetAttribute("value", text);

            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (Btn.GetAttribute("className").IndexOf("btn-lg") > -1)
                    Btn.InvokeMember("click");
            }
        }

        string 전남고흥결과()
        {
            string result = "";

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("p");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("className").IndexOf("totalCount") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }

            return result;
        }
        #endregion

        #region 전남 여수
        void 전남여수입력(string text)
        {
            HtmlElementCollection FindInput = webBrowser1.Document.GetElementsByTagName("input");
            foreach (HtmlElement input in FindInput)
            {
                if (input.Name.IndexOf("search_txt") > -1)
                {
                    input.SetAttribute("value", text);
                }
            }

            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("a"))
            {
                if (he.GetAttribute("className").IndexOf("btn_search") > -1)
                {
                    he.InvokeMember("click");
                }
            }
        }

        string 전남여수결과()
        {
            string result = "";

            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("span"))
            {
                if (he.InnerText != null && he.InnerText.IndexOf("검색되었습니다.") > -1)
                {
                    result = Regex.Replace(he.InnerText, @"[^0-9]", "");
                }
            }

            return result;
        }

        #endregion

        #region 전남 무안

        string 전남무안입력(string text)
        {
            string result = "소장";

            webBrowser1.Document.GetElementById("search_word").SetAttribute("value", text);

            HtmlElementCollection inputcol = webBrowser1.Document.GetElementsByTagName("input");
            foreach (HtmlElement input in inputcol)
            {
                if (input.GetAttribute("className").IndexOf("btn-sch btn-gray") > -1)
                {
                    input.InvokeMember("click");
                }
            }

            Delay(3000);
            HtmlElementCollection tdcol = webBrowser1.Document.GetElementsByTagName("td");
            foreach (HtmlElement td in tdcol)
            {
                if (td.GetAttribute("className").IndexOf("list_empty") > -1)
                {
                    result = "미소장";
                }
            }
            return result;
        }

        #endregion

        #region 전남 목포

        bool isMokClick = false;

        void 전남목포입력(string text)
        {

            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.Id != null && input.Id.IndexOf(Code) > -1 && !isMokClick)
                {
                    input.InvokeMember("click");
                    isMokClick = true;
                    Delay(500);
                }
                if (input.Id != null && input.Id.IndexOf("searchWord") > -1)
                    input.SetAttribute("value", text);
            }

            foreach (HtmlElement btn in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (btn.GetAttribute("className").IndexOf("btn-search") > -1)
                    btn.InvokeMember("click");
            }

        }

        string 전남목포결과()
        {
            string result = "";

            foreach (HtmlElement strong in webBrowser1.Document.GetElementsByTagName("strong"))
            {
                if (strong.GetAttribute("className").IndexOf("cyan") > -1)
                    result = Regex.Replace(strong.InnerText, @"\D", "");
            }

            return result;
        }

        #endregion

        #region 전남 순천

        string 전남순천입력(string text)
        {

            foreach (HtmlElement select in webBrowser1.Document.GetElementsByTagName("select"))
            {
                if (select.Id == "lib_code")
                {
                    select.SetAttribute("value", Code);
                    break;
                }
            }

            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.Id == "search_val")
                {
                    input.SetAttribute("value", text);
                    break;
                }
            }

            webBrowser1.Document.GetElementsByTagName("button")[0].InvokeMember("click");
            // foreach (HtmlElement button in webBrowser1.Document.GetElementsByTagName("button"))
            // {
            //     button.InvokeMember("click");
            //     break;
            // }

            string result = "";

            foreach (HtmlElement table in webBrowser1.Document.GetElementsByTagName("table"))
            {
                if (table.GetAttribute("className").IndexOf("search_bar") > -1)
                {
                    result = Regex.Replace(table.Document.GetElementsByTagName("font")[0].InnerText, @"\D", "");
                    // foreach (HtmlElement font in table.Document.GetElementsByTagName("font"))
                    // {
                    //     if (font.GetAttribute("className").IndexOf("cyan") > -1)
                    //     {
                    //         result = Regex.Replace(font.InnerText, @"\D", "");
                    //         break;
                    //     }
                    // }
                    break;
                }
            }

            return result;
        }

        #endregion

        #endregion

        #region 전북 소재 도서관

        #region 전북대학교 도서관

        void 전북대입력(string text)
        {
            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.GetAttribute("className").IndexOf("inputText") > -1)
                {
                    input.SetAttribute("value", text);
                }
                if (input.GetAttribute("className").IndexOf("searchBtn") > -1 && input.GetAttribute("type") != "submit")
                {
                    input.InvokeMember("click");
                    break;
                }
            }
        }

        string 전북대결과()
        {
            string result = "";

            foreach (HtmlElement div in webBrowser1.Document.GetElementsByTagName("div"))
            {
                if (div.GetAttribute("className").IndexOf("catalogs") > -1)
                {
                    foreach (HtmlElement span in div.GetElementsByTagName("span"))
                    {
                        if (span.GetAttribute("className").IndexOf("moreCount") > -1)
                        {
                            result = span.InnerText;
                            break;
                        }
                    }
                    if (result != "0")
                        break;
                }
                else if (div.GetAttribute("className").IndexOf("articles") > -1)
                {
                    foreach (HtmlElement span in div.GetElementsByTagName("span"))
                    {
                        if (span.GetAttribute("className").IndexOf("moreCount") > -1)
                        {
                            result = span.InnerText;
                            break;
                        }
                    }
                    if (result != "0")
                        break;
                }
            }

            return result;
        }

        #endregion

        #region 전북 교육청

        bool isJBEClick = false;
        string 전북교육청입력(string text)
        {
            // webBrowser1.Document.GetElementById("search_text").SetAttribute("value", text);

            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (!isJBEClick)
                {
                    if (input.GetAttribute("value").IndexOf("ALL") > -1)
                    {
                        input.InvokeMember("click");
                    }
                    if (input.GetAttribute("value").IndexOf(Code) > -1)
                    {
                        input.InvokeMember("click");
                        isJBEClick = true;
                        break;
                    }
                }
            }
            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.Name == "search_text" && input.GetAttribute("className") == "text")
                {
                    input.SetAttribute("value", text);
                    break;
                }
            }

            webBrowser1.Document.GetElementById("do-search").InvokeMember("click");

            Delay(3000);
            string result = "";
            int count = 0;
            foreach (HtmlElement B in webBrowser1.Document.GetElementsByTagName("b"))
            {
                if (count == 1)
                {
                    result = B.InnerText;
                    break;
                }
                count++;
            }

            return result;
        }
        #endregion

        #region 익산시 통합도서관

        bool isIksanClick = false;
        void 익산통합도서관입력(string text)
        {

            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (!isIksanClick)
                {
                    if (input.Id == null)
                        continue;
                    if (input.Id.IndexOf("all_lib_simple") > -1)
                    {
                        input.InvokeMember("click");
                        // input.InvokeMember("submit");
                    }
                    if (input.Id.IndexOf(Code) > -1)
                    {
                        input.InvokeMember("click");
                        // input.InvokeMember("submit");
                        isIksanClick = true;
                        break;
                    }
                    btn_Close.Text = isIksanClick.ToString();
                }
            }

            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.Id != null && input.Id == "search_txt")
                {
                    input.SetAttribute("value", text);
                    break;
                }
            }

            //webBrowser1.Document.GetElementById("search_txt").SetAttribute("value", text);

            webBrowser1.Document.GetElementById("submit_simple").InvokeMember("click");
        }



        string 익산통합도서관결과()
        {
            string result = "";

            foreach (HtmlElement strong in webBrowser1.Document.GetElementsByTagName("strong"))
            {
                if (strong.GetAttribute("className").IndexOf("word") > -1)
                {
                    string innerText = strong.InnerText;
                    if (Regex.IsMatch(innerText, @"^[0-9]+$"))
                    {
                        result = strong.InnerText;
                        break;
                    }
                }
            }

            return result;
        }

        #endregion

        #endregion

        #region 경기 소재 도서관

        string 안산중앙도서관입력(string text)
        {
            // 콤보박스 적용
            webBrowser1.Document.GetElementById("srcKind").SetAttribute("value", Code);

            // 검색어 적용
            webBrowser1.Document.GetElementById("srcWord").SetAttribute("value", text);

            foreach (HtmlElement button in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (button.InnerText.IndexOf("검색하기") > -1)
                {
                    button.InvokeMember("click");
                    break;
                }
            }

            Delay(3000);
            string result = "";
            foreach (HtmlElement span in webBrowser1.Document.GetElementsByTagName("span"))
            {
                string tmp = span.InnerText;
                if (tmp.IndexOf("검색결과:") > -1)
                {
                    result = Regex.Replace(tmp, @"[^0-9]", "");
                    break;
                }
            }

            return result;
        }
        #endregion

        public string CopyCount(string Text)
        {
            string result = "";

            if (lib_Category is null)
                return "false";

            string[] Detail = lib_Category.Split('_');

            switch (Detail[0])
            {
                case "전남":
                    result = 전남(Detail[1], Text);
                    break;
                default:
                    break;
            }
            return result;
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            webBrowser1.Stop();
            webBrowser1.DocumentCompleted -= this.webBrowser1_DocumentCompleted;
        }

        #region 전남
        string 전남(string detail, string Text)
        {
            string result = "";
            switch (detail)
            {
                case "도립":
                    result = 전남도립(Text);
                    break;

                case "여수":
                    result = 전남여수(Text);
                    break;

                case "완도":
                    result = 전남완도(Text);
                    break;

                default:
                    break;
            }
            return result;
        }

        private string 전남도립(string text)
        {
            string result = "";

            webBrowser1.Navigate(URL);

            Delay(5000);

            전남도립입력(text);

            Delay(8000);

            result = 전남도립결과();

            return result;
        }

        private string 전남여수(string text)
        {
            string result = "";

            text = HttpUtility.UrlEncode(text);

            string url = string.Format("https://yslib.yeosu.go.kr/dls_kapi/index.php?" +
                "mod=wdDataSearch" +
                "&act=searchResultList" +
                "&facetManageCode={1}" +
                "&searchWord={0}" +
                "&dataSort=rk+desc", text, Code);

            webBrowser1.Navigate(url);

            Delay(8000);
            foreach (HtmlElement he in webBrowser1.Document.GetElementsByTagName("strong"))
            {
                if (he.GetAttribute("className").IndexOf("cyan") > -1)
                {
                    result = Regex.Replace(he.InnerText, @"\D", "");
                }
            }
            return result;
        }

        private string 전남완도(string text)
        {
            string result = "";

            webBrowser1.Navigate(URL);
            Delay(3000);

            webBrowser1.Document.GetElementById("value2").SetAttribute("value", text);
            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("select"))
            {
                if (Btn.GetAttribute("name").IndexOf("local") > -1)
                    Btn.SetAttribute("value", Code);
            }


            foreach (HtmlElement Btn in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (Btn.GetAttribute("type") == "image")
                    Btn.InvokeMember("click");
            }

            Delay(3000);

            HtmlElementCollection hecTd = webBrowser1.Document.GetElementsByTagName("td");
            foreach (HtmlElement heTd in hecTd)
            {
                if (heTd.GetAttribute("alrign").IndexOf("left") > -1)
                {
                    result = Regex.Replace(heTd.InnerText, @"\D", "");
                }
            }

            return result;
        }

        #endregion

        /// <summary>
        /// 지연시키는 함수
        /// </summary>
        /// <param name="ms">1000 = 1초</param>
        void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);

            while (dateTimeAdd >= dateTimeNow)
            {
                Application.DoEvents();
                dateTimeNow = DateTime.Now;
            }
            return;
        }

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

            if (count <= 1)
                return;

            if (chk_spChar.Checked)         // 특수문자 제거
                RemoveSpecialChar(count);

            if (chk_RemoveBrit.Checked)     // 괄호안의 문자 제거
                RemoveInBrit(count);
        }

        /// <summary>
        /// 특수문자 제거
        /// </summary>
        void RemoveSpecialChar(int count)
        {
            for (int a = 0; a < count; a++)
            {
                if (dataGridView1.Rows[a].Cells["book_name"].Value == null)
                    break;

                string Target = dataGridView1.Rows[a].Cells["book_name"].Value.ToString();

                // 구두점 제거 ,.;:/
                // Target = Target.Replace(",", "").Replace(".", "").Replace(";", "").Replace(":", "");

                string res = Regex.Replace(Target, @"[^a-zA-Z0-9가-힣_\s()]", "", RegexOptions.Singleline);

                dataGridView1.Rows[a].Cells["book_name"].Value = res.Trim();
            }
        }

        /// <summary>
        /// 괄호안의 문자 제거
        /// </summary>
        void RemoveInBrit(int count)
        {
            String_Text st = new String_Text();
            for (int a = 0; a < count; a++)
            {
                if (dataGridView1.Rows[a].Cells["book_name"].Value == null)
                    break;

                string Target = dataGridView1.Rows[a].Cells["book_name"].Value.ToString();

                dataGridView1.Rows[a].Cells["book_name"].Value = st.RemoveWordInBracket(Target).Trim();
            }
        }

        private void btn_OpenMemo_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFileDialog = new OpenFileDialog();
            if (OpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                dataGridView1.Rows.Clear();
                string filePath = OpenFileDialog.FileName;
                try
                {
                    System.IO.StreamReader r = new System.IO.StreamReader(filePath, Encoding.GetEncoding("ks_c_5601-1987"));
                    OpenFileGrid(r.ReadToEnd());
                    r.Close();
                }
                catch (Exception ex)
                {
                    UTIL.MsgE(ex.ToString());
                }
            }
        }
        #region OpenMemo_Sub

        void OpenFileGrid(string text)
        {
            string[] splitText = text.Split('\n');

            foreach (string Line in splitText)
            {
                if (Line == "")
                    continue;

                string[] GridData = { "", "" };
                if (Line.IndexOf('\t') > -1)
                {
                    string[] splitLine = Line.Split('\t');
                    GridData[0] = splitLine[0];
                    GridData[1] = splitLine[1];
                }
                else
                    GridData[0] = Line;

                dataGridView1.Rows.Add(GridData);
            }
        }
        #endregion

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

        private void btn_ResultEmpty_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].DefaultCellStyle.ForeColor = Color.Black;
                dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.White;
                dataGridView1.Rows[a].Cells["Count"].Value = "";
                RowCount = 0;
            }
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void Check_copy_FormClosing(object sender, FormClosingEventArgs e)
        {
            webBrowser1.Stop();
            webBrowser1.DocumentCompleted -= this.webBrowser1_DocumentCompleted;
        }

        private void btn_SiteDenote_Click(object sender, EventArgs e)
        {
            if (URL == null) return;
            if (URL.Contains("\"") == false)
                URL = $"\"{URL}\"";
            AR.UTIL.RunExplorer(URL);
        }

        private void btSearchLibrary_Click(object sender, EventArgs e)
        {
            SearchLibrary();
        }
    }
}
