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;
using UniMarc.SearchModel;
using System.Linq;
using System.Globalization;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace UniMarc
{
    public partial class Check_copyWD : 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;

        bool GetDemoRunAuth
        {
            get
            {
                return (DateTime.Now <= new DateTime(2026, 12, 30));

            }
        }
        public Check_copyWD(Main _main)
        {
            InitializeComponent();
            main = _main;
            db.DBcon();

            // 도서관별 지연시간 설정 초기화
            _delaySettings = new Helper_LibraryDelaySettings();

            var idx = 1;
            //도서검색(크롤링)
            _searchService = new BookSearchService();

            _searchService.AddSearcher(new NamguLibrarySearcher(idx++, "#libMA", "문화정보도서관"));
            _searchService.AddSearcher(new NamguLibrarySearcher(idx++, "#libMC", "청소년도서관"));
            _searchService.AddSearcher(new NamguLibrarySearcher(idx++, "#libSQ", "스마트도서관"));
            _searchService.AddSearcher(new NamguLibrarySearcher(idx++, "#libMB", "푸른길도서관"));
            _searchService.AddSearcher(new NamguLibrarySearcher(idx++, "#libSW", "효천어울림도서관"));



            {
                //광주시교육청통합도서관
                _searchService.AddSearcher(new KwangjuCityEduLibrarySearcher(idx++, "MD", "중앙도서관"));
                _searchService.AddSearcher(new KwangjuCityEduLibrarySearcher(idx++, "MF", "분관최상준도서관"));
                _searchService.AddSearcher(new KwangjuCityEduLibrarySearcher(idx++, "ME", "송정다가치문화도서관"));
                _searchService.AddSearcher(new KwangjuCityEduLibrarySearcher(idx++, "MA", "학생독립운동기념회관"));
                _searchService.AddSearcher(new KwangjuCityEduLibrarySearcher(idx++, "MC", "학생교육문화회관"));
                _searchService.AddSearcher(new KwangjuCityEduLibrarySearcher(idx++, "MB", "금호평생교육관"));

                //전남교육청통합도서관
                //_searchService.AddSearcher(new JunnamEduSearcher(idx++, "ALL", "전체"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146010", "목포"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146007", "나주"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146006", "남평"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146025", "광양"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146008", "담양"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146005", "구례"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146012", "보성"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146013", "벌교"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146023", "화순"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146019", "장흥"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146022", "해남"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146017", "영암"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146011", "무안"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146021", "함평"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146016", "영광"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146018", "장성"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146020", "진도"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146003", "곡성"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146059", "학생교육문화회관"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146042", "광양평생"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146002", "고흥평생"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00346002", "교육연수원"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00324008", "교육연구정보원"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00346030", "전라남도국제교육원"));
                _searchService.AddSearcher(new JunnamEduSearcher(idx++, "00146180", "순천만생태문화교육원"));

                //전남교육청행정자료실
                _searchService.AddSearcher(new JunnamEduJiheaNuriSearcher(idx++, "00324010", "지혜누리"));

                //여수시립
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "MG", "여수이순신도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "MA", "여수시립쌍봉도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "MB", "여수시립현암도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "MC", "여수시립환경도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "MD", "여수시립돌산도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "ME", "여수시립소라도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "MF", "여수시립율촌도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PA", "거문도은빛바다도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PB", "치매안심센터작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PC", "청솔글누리작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PD", "동부도시보건작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PE", "화양열린작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PF", "여문늘벗작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "PH", "국동작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SA", "아주타운아파트작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SB", "책이랑나랑작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SC", "현천작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SE", "꿈꾸는영어전문작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SF", "학마을작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SG", "웅천지웰작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SH", "한려작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SJ", "주은금고작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SK", "광림작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SM", "민들레작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SO", "원앙작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SP", "푸른정원작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SR", "로얄골드빌작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SS", "꿈을키우는작은도서관"));
                //_searchService.AddSearcher(new YeosuLibSearcher(idx++, "ST", "KLAS MANAGEMENT"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SY", "신기부영작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "SZ", "국동365열린도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "TA", "지웰2차 작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "TB", "이편한 작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "TC", "채움늘 작은도서관"));
                _searchService.AddSearcher(new YeosuLibSearcher(idx++, "TD", "웅천글꽃 작은도서관"));

                //고흥군립
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "MA", "고흥군립중앙도서관"));
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "MB", "고흥군립남부도서관"));
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "MC", "고흥군립북부도서관"));
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "MD", "과역작은도서관"));
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "ME", "나로한빛 작은도서관"));
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "MF", "도화푸른꿈 작은도서관"));
                _searchService.AddSearcher(new GoheungLibSearcher(idx++, "MG", "포두작은도서관"));

                //광주북구 통합도서관
                _searchService.AddSearcher(new BukguLibSearcher(idx++, "101", "스마트도서관1호점"));
                _searchService.AddSearcher(new BukguLibSearcher(idx++, "102", "스마트도서관2호점"));
                _searchService.AddSearcher(new BukguLibSearcher(idx++, "105", "스마트도서관3호점"));

                //광주북구 작은도서관
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729038", "꿈나무작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129094", "동림동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729046", "두암1동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129069", "두암2동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129068", "두암3동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129056", "매곡동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129074", "문흥2동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129054", "삼각동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729068", "시화문화마을작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129057", "신안동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129220", "양산동주민작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129085", "오치1동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129070", "오치2동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129055", "용봉작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129064", "운암1동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129071", "운암2동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129058", "운암3동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729175", "임동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729085", "중앙동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129075", "중흥1동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729155", "징검다리작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "129065", "풍향동작은도서관"));
                _searchService.AddSearcher(new BukguSlibSearcher(idx++, "729154", "햇살마루작은도서관"));

                //광주북구 공공도서관
                _searchService.AddSearcher(new BukguPublicLibSearcher(idx++, "124010", "일곡도서관"));
                _searchService.AddSearcher(new BukguPublicLibSearcher(idx++, "129131", "운암도서관"));
                _searchService.AddSearcher(new BukguPublicLibSearcher(idx++, "129225", "양산도서관"));
                _searchService.AddSearcher(new BukguPublicLibSearcher(idx++, "129226", "중흥도서관"));
                _searchService.AddSearcher(new BukguPublicLibSearcher(idx++, "129227", "신용도서관"));

                //전북교육청도서관
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MV", "고창도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MB", "군산학생교육문화관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MC", "군산학생교육문화관 대야분관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MH", "김제학생교육문화관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MJ", "김제학생교육문화관 금산분관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MF", "남원학생교육문화관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MG", "남원학생교육문화관운봉분관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MR", "무주도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MK", "부안학생교육문화관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MU", "순창도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MP", "완주도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MD", "익산학생교육문화관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_ME", "익산학생교육문화관 함열분관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MT", "임실도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MS", "장수도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MA", "전주학생교육문화관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MQ", "진안도서관"));
                _searchService.AddSearcher(new JeonbukEduLibSearcher(idx++, "lib_MN", "정읍학생복지회관"));

                //광주광산구 통합도서관
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "JM", "장덕도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "MB", "이야기꽃도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "MA", "첨단도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "BR", "신가도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "WN", "운남어린이도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "MC", "스마트도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CA", "첨단빛누리작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CB", "사랑나눔작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CC", "혜윰마루작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CD", "책놀터작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CE", "우산동작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CF", "더불어락작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CG", "임곡꿈쟁이작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CH", "유노윤호HUG작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CI", "늘품작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CJ", "왁자지껄수다놀이터작은도서관"));
                _searchService.AddSearcher(new GwangsanLibSearcher(idx++, "CK", "송정다누리작은도서관"));

                //목포시립도서관
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MA", "목포시립도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MX", "목포어울림도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MJ", "목포어린이도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MQ", "목포영어도서관"));

                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "ME", "꿈나무작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MB", "꿈돌이작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MS", "노을작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MW", "늘푸른작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MH", "무지개작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MF", "반딧불작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MP", "삼학작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MV", "샛별작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MO", "소나무작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MN", "숲속작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MK", "연꽃작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MD", "옹달샘작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MC", "은하수작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MM", "청개구리작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MI", "초롱초롱작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "ML", "푸른솔작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MU", "푸른숲작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MR", "행복마을작은도서관"));
                _searchService.AddSearcher(new MokpoLibSearcher(idx++, "MT", "호돌이작은도서관"));

                //순천시립도서관
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MA", "삼산도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MB", "그림책도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "BR", "연향도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MH", "기적의도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MC", "조례호수도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MJ", "신대도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MK", "어울림도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MD", "해룡농어촌도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "MG", "풍덕글마루도서관"));
                _searchService.AddSearcher(new SuncheonLibSearcher(idx++, "mini", "작은도서관"));

                //광주시립도서관
                _searchService.AddSearcher(new GwangjuCityLibSearcher(idx++, "124003", "무등도서관"));
                _searchService.AddSearcher(new GwangjuCityLibSearcher(idx++, "124004", "사직도서관"));
                _searchService.AddSearcher(new GwangjuCityLibSearcher(idx++, "124008", "산수도서관"));
                _searchService.AddSearcher(new GwangjuCityLibSearcher(idx++, "129228", "디지털정보도서관"));

                // 완도군립도서관
                _searchService.AddSearcher(new WandoLibSearcher(idx++, "MA", "완도군립도서관"));
                _searchService.AddSearcher(new WandoLibSearcher(idx++, "MB", "노화공공도서관"));
                _searchService.AddSearcher(new WandoLibSearcher(idx++, "MC", "금일공공도서관"));
                _searchService.AddSearcher(new WandoLibSearcher(idx++, "MD", "보길윤선도작은도서관"));
                _searchService.AddSearcher(new WandoLibSearcher(idx++, "ME", "군외동백숲작은도서관"));
                _searchService.AddSearcher(new WandoLibSearcher(idx++, "MF", "도담도담작은도서관"));

                // 익산시통합도서관
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "MO", "모현도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "BR", "영등도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "MA", "마동도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "BU", "부송도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "MC", "유천도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "HW", "황등도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "MB", "금마도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SX", "모인여행숲도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SW", "수도산그림책숲도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "UQ", "스마트도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SI", "글마루작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SD", "깊은샘작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SE", "꿈꾸는뜰작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SO", "꿈드림작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SK", "낭산작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SB", "동산작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SJ", "모현뜰작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SH", "배산작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SC", "봄나루작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SF", "부송작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SA", "삼성동어린이도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SQ", "어양작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SP", "어울림작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SG", "예솔작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SL", "왕궁작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SN", "울림작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SM", "행복세상작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SR", "그루터기작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SS", "늘봄작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SU", "망성아담작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SV", "함라등대작은도서관"));
                _searchService.AddSearcher(new IksanLibSearcher(idx++, "SY", "무학정원작은도서관"));

                // 안산시중앙도서관
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MA", "중앙도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MD", "감골도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MB", "관산도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "ME", "단원어린이도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "ND", "대부도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NF", "미디어도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MH", "반월도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MX", "본오도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "ML", "부곡도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NK", "상록수도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MF", "상록어린이도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NC", "선부도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MC", "성포도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MS", "수암도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MR", "원고잔도서관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NJ", "월피예술도서관"));

                // 안산시 작은도서관
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MK", "사이동꿈키"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MU", "해양동"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MO", "안산평생학습관"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MG", "안산다문화"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MJ", "신길샛별"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MM", "석수골"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "MW", "선녀마을"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NA", "당곡"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NB", "와동별빛누리"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NG", "달미"));
                _searchService.AddSearcher(new AnsanLibSearcher(idx++, "NI", "신길"));

                // 광주서구구립도서관
                _searchService.AddSearcher(new GwangjuSeoguLibSearcher(idx++, "129222", "상록도서관"));
                _searchService.AddSearcher(new GwangjuSeoguLibSearcher(idx++, "129004", "어린이생태학습도서관"));
                _searchService.AddSearcher(new GwangjuSeoguLibSearcher(idx++, "129230", "서빛마루도서관"));
                _searchService.AddSearcher(new GwangjuSeoguLibSearcher(idx++, "124009", "문화의숲도서관"));

                // 광주서구스마트도서관
                _searchService.AddSearcher(new GwangjuSeoguSmartLibSearcher(idx++, "129222", "상록도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmartLibSearcher(idx++, "129004", "어린이생태학습도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmartLibSearcher(idx++, "129230", "서빛마루도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmartLibSearcher(idx++, "124009", "서구공공도서관"));

                // 광주서구작은도서관
                _searchService.AddSearcher(new GwangjuSeoguSmallLibSearcher(idx++, "MD", "화정4동작은도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmallLibSearcher(idx++, "ME", "동천작은도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmallLibSearcher(idx++, "MF", "금호2동작은도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmallLibSearcher(idx++, "MI", "서창한옥작은도서관"));
                _searchService.AddSearcher(new GwangjuSeoguSmallLibSearcher(idx++, "MZ", "새몰마루작은도서관"));

                // 광주동구도서관
                _searchService.AddSearcher(new GwangjuDongguLibSearcher(idx++, "129231", "책정원도서관"));
                _searchService.AddSearcher(new GwangjuDongguLibSearcher(idx++, "129003", "계림꿈나무도서관"));
                _searchService.AddSearcher(new GwangjuDongguLibSearcher(idx++, "729079", "다복마을도서관"));
                _searchService.AddSearcher(new GwangjuDongguLibSearcher(idx++, "729072", "학운동작은도서관"));
                _searchService.AddSearcher(new GwangjuDongguLibSearcher(idx++, "729073", "지원2동작은도서관"));

                // 경남대표도서관
                _searchService.AddSearcher(new GyeongnamLibSearcher(idx++, "", "경남대표도서관"));

                // 무안군립도서관
                _searchService.AddSearcher(new MuanLibSearcher(idx++, "", "무안군립도서관"));

                // 조선대학교중앙도서관
                _searchService.AddSearcher(new ChosunUnivLibSearcher(idx++, "", "조선대학교중앙도서관"));

                // 조선이공대학교도서관
                _searchService.AddSearcher(new ChosunTechLibSearcher(idx++, "", "조선이공대학교도서관"));

                // KCM통합도서관 (여수시)
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "MA", "쌍봉도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "MG", "여수이순신도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "MB", "여수시립현암도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "MC", "여수시립환경도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "MD", "여수시립돌산도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "ME", "여수시립소라도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "MF", "여수시립율촌도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PA", "거문도은빛바다도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PB", "치매안심작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PC", "청솔글누리작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PD", "동부도시보건작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PE", "화양열린작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PF", "여문늘벗작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "PH", "국동협동관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SA", "아주타운아파트작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SB", "책이랑나랑작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SC", "현천작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SE", "꿈꾸는영어전문작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SF", "학마을작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SG", "웅천지웰작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SH", "한려작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SJ", "주은금호작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SK", "광림작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SM", "민들레작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SO", "원앙작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SP", "푸른정원작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SR", "로얄골드빌작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SS", "꿈을키우는작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SY", "신기부영작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "SZ", "국동365열린도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "TA", "지웰2차작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "TB", "이편한작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "TC", "채움늘작은도서관"));
                _searchService.AddSearcher(new KcmLibSearcher(idx++, "TD", "웅천글꽃작은도서관"));

            }

            //고창도서관 추가 250903

            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MA", "고창군립도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MB", "선운산작은도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MC", "고수해마루작은도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MD", "고창군립성호도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "ME", "대산큰별작은도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MF", "무장글샘작은도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MG", "글마루작은도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MH", "흥덕가온누리작은도서관"));
            _searchService.AddSearcher(new GochangLibSearcher(idx++, "MI", "공음참나무골작은도서관"));

            //전라남도립도서관 추가 250917
            _searchService.AddSearcher(new JeonnamProvLibSearcher(idx++, "all", "전라남도립도서관"));

            this.tb_SearchTarget.Items.Clear();
            // this.tb_SearchTarget.Items.Add("-- 검색대상을 선택하세요 --");
            foreach (var item in _searchService.GetAvailableSites().OrderBy(t => t))
                tb_SearchTarget.Items.Add(item);
            if (PUB.setting.LastSearchTarget.isEmpty() == false)
                tb_SearchTarget.Text = PUB.setting.LastSearchTarget;

            this.Text = $"복본조사(New:{_searchService.GetAvailableSites().Count})";
        }

        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)
        {
            this.Show();
            Application.DoEvents();

            //크롤링 
            InitializeChromeDriver();
            tb_SearchTarget.Enabled = true;
        }


        #region 크롤링

        private readonly BookSearchService _searchService;
        private bool _isSearching = false;
        private readonly Helper_LibraryDelaySettings _delaySettings;

        private async void InitializeChromeDriver()
        {
            var lblStatus = this.lblStatus;// (Label)this.Controls["lblStatus"];
            lblStatus.Text = "WebDriver:Chrome 드라이버 확인 중...";
            lblStatus.ForeColor = Color.Blue;

            try
            {
                // Chrome 설치 확인
                if (!SeleniumHelper.IsBrowserInstalled())
                {
                    UTIL.MsgE("Google Chrome / Microsoft Edge 이(가) 설치되어 있지 않습니다. 브라우저를 설치한 후 프로그램을 다시 실행해주세요.");
                    lblStatus.Text = "WebDriver: 브라우저가 설치되지 않음";
                    lblStatus.ForeColor = Color.Red;
                    return;
                }

                //기존프로세스 삭제
                await SeleniumHelper.KillExistingDriversAsync();

                //준비된 경우에는 다운로드 하지 않는다.
                if (SeleniumHelper.IsReady)
                {
                    lblStatus.Text = $"WebDriver:Ready({SeleniumHelper.Browser})";
                    lblStatus.ForeColor = Color.Green;
                }
                else
                {
                    // 드라이버가 없거나 작동하지 않으면 다운로드 진행 창 표시
                    using (var progressForm = new DownloadProgressForm())
                    {
                        progressForm.Show();

                        try
                        {
                            // ChromeDriver 설정
                            await SeleniumHelper.Download(progressForm: progressForm);

                            // 드라이버 테스트
                            var isWorking = await SeleniumHelper.TestDriver(progressForm);
                            if (isWorking)
                            {
                                lblStatus.Text = $"WebDriver:Ready({SeleniumHelper.Browser})";
                                lblStatus.ForeColor = Color.Green;
                            }
                            else
                            {
                                lblStatus.Text = "WebDriver:드라이버 테스트 실패";
                                lblStatus.ForeColor = Color.Red;
                                UTIL.MsgE("Chrome 드라이버 테스트에 실패했습니다. 인터넷 연결을 확인하고 프로그램을 다시 실행해주세요.");
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            lblStatus.Text = "WebDriver:드라이버 테스트가 취소되었습니다.";
                            lblStatus.ForeColor = Color.Orange;
                            return;
                        }
                        catch (Exception ex)
                        {
                            lblStatus.Text = "WebDriver:Chrome 드라이버 테스트 실패";
                            lblStatus.ForeColor = Color.Red;
                            UTIL.MsgE($"Chrome 드라이버 테스트 중 오류가 발생했습니다: {ex.Message}");
                            return;
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                lblStatus.Text = "WebDriver:Chrome 드라이버 테스트 실패";
                lblStatus.ForeColor = Color.Red;
                UTIL.MsgE($"Chrome 드라이버 테스트 중 오류가 발생했습니다: {ex.Message}");
            }
        }
        #endregion   


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

            List<string> items = new List<string>();
            foreach (string item in tb_SearchTarget.Items)
            {
                if (items.Contains(item) == false) items.Add(item);
            }


            //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 = items.ToArray();// data.Split('|');
            using (var ccs = new Check_Copy_Sub_Selector(items.ToArray(), Target))
            {
                ccs.ShowDialog();
                if (ccs.SelectedValue.isEmpty() == false)
                    tb_SearchTarget.Text = ccs.SelectedValue;
            }
        }

        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);
        }


        async private void btn_Start_Click(object sender, EventArgs e)
        {
            var searcher = this.GetSearcher();
            if (searcher == null)
            {
                UTIL.MsgE("검색 대상을 선택하세요");
                return;
            }

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

            if (GetDemoRunAuth == false)
            {
                UTIL.MsgE("테스트 기간이 종료되었습니다\n개발자 문의 하세요");
                return;
            }

            if (SeleniumHelper.IsReady == false)
            {
                UTIL.MsgE("웹드라이버가 초기화되지 않았습니다\n1.크롬브라우즈가 설치되어있는지 확인하세요\n\n2.개발자 문의하세요");
                return;
            }

            try
            {
                PUB.setting.LastSearchTarget = this.tb_SearchTarget.Text.Trim();
                PUB.setting.Save();

                this._isSearching = true;
                btn_Start.Enabled = false;
                btn_Stop.Enabled = true;
                await searcher.StartDriver(this.chkShowBrowser.Checked);
                byte searchopt = 0; //전체검색
                if (radTargetEmpty.Checked) searchopt = 1;
                else if (radTargetErr.Checked) searchopt = 2;
                else if (radTargetErrEmpty.Checked) searchopt = 3;

                bool retry = false;
                var cnt_totalcnt = 0;
                int cnt_skip = 0;
                int cnt_ok = 0;
                int cnt_ng = 0;
                int cnt_er = 0;
                int addDelay = (int)nudAddDelay.Value * 1000;      //추가 지연시간 : 1개의 레코드 처리 후 추가 지연한다.

                // 현재 지연시간을 도서관별로 저장
                SaveLibraryDelaySettings(searcher.SiteName, (int)nudAddDelay.Value);

            RetrySearch:
                foreach (DataGridViewRow drow in this.dv1.Rows)
                {
                    if (this._isSearching == false)
                    {
                        drow.Cells["dvc_remark"].Value = "Cancel";
                        if (dv1.Columns.Contains("dvc_resulthtml"))
                        {
                            drow.Cells["dvc_resulthtml"].Value = "";
                        }
                        break;
                    }

                    dv1.CurrentCell = drow.Cells[0];
                    //var vBookName = drow.Cells["book_name"].Value;
                    var bookName = drow.Cells["book_name"].Value?.ToString() ?? string.Empty;
                    if (bookName.isEmpty())
                    {
                        cnt_skip += 1;
                        drow.Cells["dvc_remark"].Value = "No Title";
                        if (dv1.Columns.Contains("dvc_resulthtml"))
                        {
                            drow.Cells["dvc_resulthtml"].Value = "";
                        }
                        drow.DefaultCellStyle.BackColor = Color.HotPink;
                        drow.DefaultCellStyle.ForeColor = Color.Blue;
                        continue;
                    }

                    var cntValue = drow.Cells["Count"].Value?.ToString() ?? string.Empty;
                    cntValue = cntValue.ToLower().Trim();

                    if (radTargetErr.Checked)    //오류데이터만 처리
                    {
                        if (cntValue.Equals("-1") == false)
                            continue;
                    }
                    else if (radTargetEmpty.Checked) //빈데이터만 처리 (검사된 수량이 0이라면 동작한다)
                    {
                        if (int.TryParse(cntValue, out int cntvalue) && cntvalue > 0)
                            continue;
                    }
                    else if (radTargetErrEmpty.Checked) //오류+빈데이터처리
                    {
                        if (cntValue.Equals("-1") == false) continue;
                        if (int.TryParse(cntValue, out int cntvalue) && cntvalue > 0) continue;
                    }

                    cnt_totalcnt += 1;
                    var rlt = await searcher.SearchAsync(bookName);
                    if (rlt.IsSuccess)
                    {
                        drow.Cells["dvc_remark"].Value = rlt.ErrorMessage;
                        drow.Cells["Count"].Value = $"{rlt.BookCount}";

                        // ResultHtml을 dvc_resulthtml 컬럼에 저장
                        if (dv1.Columns.Contains("dvc_resulthtml"))
                        {
                            drow.Cells["dvc_resulthtml"].Value = rlt.Resulthtml ?? "";
                        }

                        if (rlt.BookCount == 0)
                        {
                            cnt_ng += 1;
                            drow.DefaultCellStyle.BackColor = Color.LightGray;
                            drow.DefaultCellStyle.ForeColor = Color.Red;
                        }
                        else
                        {
                            cnt_ok += 1;
                            drow.DefaultCellStyle.BackColor = Color.Yellow;
                            drow.DefaultCellStyle.ForeColor = Color.Blue;
                        }
                    }
                    else
                    {
                        cnt_er += 1;                        
                        drow.Cells["dvc_remark"].Value = $"Error|{rlt.ErrorMessage}";
                        drow.Cells["Count"].Value = "-1";   //오류발생시에는 -1이 입력되도록한다

                        // 오류시에도 ResultHtml이 있으면 저장 (디버깅용)
                        if (dv1.Columns.Contains("dvc_resulthtml"))
                        {
                            drow.Cells["dvc_resulthtml"].Value = rlt.Resulthtml ?? "";
                        }

                        drow.DefaultCellStyle.BackColor = Color.HotPink;
                        drow.DefaultCellStyle.ForeColor = Color.Blue;
                    }
                    if (addDelay > 0)
                        await Task.Delay(addDelay);
                }

                if (_isSearching == true && retry == false && chkRetryErrData.Checked)
                {
                    retry = true;
                    radTargetErr.Checked = true;
                    goto RetrySearch;
                }
                else
                {
                    searcher.StopDriver();
                    UTIL.MsgI($"검색 완료\n전체:{cnt_totalcnt}건/오류:{cnt_er}/성공:{cnt_ok}/없음:{cnt_ng}");

                    //재시도한경우라면 원복해준다
                    if (retry)
                    {
                        if (searchopt == 1) radTargetEmpty.Checked = true;
                        else if (searchopt == 2) radTargetErr.Checked = true;
                        else if (searchopt == 3) radTargetErrEmpty.Checked = true;
                        else radTargetAll.Checked = true;
                    }
                }
            }
            catch (Exception ex)
            {
                UTIL.MsgE("Web Driver Error\n" + ex.Message);
            }
            finally
            {
                btn_Stop.Enabled = true;
                btn_Start.Enabled = true;
                this._isSearching = false;
            }
        }



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

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

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

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


        private void btn_Stop_Click(object sender, EventArgs e)
        {
            _isSearching = false;
        }


        private void btn_ApplyFilter_Click(object sender, EventArgs e)
        {
            int count = dv1.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 (dv1.Rows[a].Cells["book_name"].Value == null)
                    break;

                string Target = dv1.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);

                dv1.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 (dv1.Rows[a].Cells["book_name"].Value == null)
                    break;

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

                dv1.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)
            {
                dv1.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;

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

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

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

                // dvc_resulthtml 컬럼도 초기화
                if (dv1.Columns.Contains("dvc_resulthtml"))
                {
                    dv1.Rows[a].Cells["dvc_resulthtml"].Value = "";
                }
            }
        }

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


        private void Check_copy_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        ILibrarySearcher GetSearcher()
        {
            if (this.tb_SearchTarget.SelectedIndex < 0) return null;
            return this._searchService.Get(tb_SearchTarget.Text);

        }

        private void btn_SiteDenote_Click(object sender, EventArgs e)
        {
            var searcher = this.GetSearcher();
            if (searcher == null)
            {
                UTIL.MsgE("검색 대상을 선택하세요");
                return;
            }

            var url = searcher.SiteUrl;
            if (url.Contains("\"") == false) url = $"\"{url}\"";
            AR.UTIL.RunExplorer(url);
        }

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

        private void tb_SearchTarget_SelectedIndexChanged(object sender, EventArgs e)
        {
            var searcher = this._searchService.Get(this.tb_SearchTarget.Text);
            if (searcher == null)
            {
                chkShowBrowser.Enabled = true;
                lbSite.Text = "-- site --";
                return;
            }
            chkShowBrowser.Enabled = !searcher.HttpApiMode;
            this.lbSite.Text = $"[{searcher.AreaCode}] {searcher.SiteUrl}";

            // 저장된 지연시간 불러오기
            LoadLibraryDelaySettings(searcher.SiteName);
        }

        /// <summary>
        /// 선택된 도서관의 저장된 지연시간을 불러와서 UI에 설정
        /// </summary>
        /// <param name="libraryName">도서관 이름</param>
        private void LoadLibraryDelaySettings(string libraryName)
        {
            try
            {
                var savedDelay = _delaySettings.GetDelay(libraryName);
                if (savedDelay > 0)
                {
                    nudAddDelay.Value = savedDelay;
                    Console.WriteLine($"도서관 지연시간 불러옴: {libraryName} = {savedDelay}초");
                }
                else
                {
                    // 저장된 설정이 없으면 기본값 유지
                    Console.WriteLine($"도서관 지연시간 설정 없음, 기본값 사용: {libraryName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"도서관 지연시간 불러오기 오류: {ex.Message}");
            }
        }

        /// <summary>
        /// 검색 시작시 현재 지연시간을 저장
        /// </summary>
        /// <param name="libraryName">도서관 이름</param>
        /// <param name="delaySeconds">지연시간(초)</param>
        private void SaveLibraryDelaySettings(string libraryName, int delaySeconds)
        {
            try
            {
                _delaySettings.SetDelay(libraryName, delaySeconds);
                Console.WriteLine($"도서관 지연시간 저장됨: {libraryName} = {delaySeconds}초");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"도서관 지연시간 저장 오류: {ex.Message}");
            }
        }

        private void 유니코드문자로붙여넝ㅎ기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            var newkey = new KeyEventArgs(Keys.Control | Keys.V | Keys.Alt);
            sg.Excel_to_DataGridView(this.dv1, newkey);
        }

        private void 일반문자로붙여넣기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            var newkey = new KeyEventArgs(Keys.Control | Keys.V);
            sg.Excel_to_DataGridView(this.dv1, newkey);
        }
    }
}
