using AR;
using arCtl.TinyListview;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Windows.Forms;
using UniMarc.ListOfValue;

namespace UniMarc
{
    public partial class Marc2 : Form
    {
        /// <summary>
        /// isbn / 도서명 / 저자 / 출판사 / 가격
        /// </summary>
        string[] data_book = { "", "", "", "", "" };
        int SaveRowIdx = -1;
        public string mUserName;
        string mCompidx = PUB.user.CompanyIdx;
        string mListIdx = "";
        public string find;
        public string change;
        public string call = "";
        private string data008 = string.Empty;
        private bool mLoadCompleted = false;
        string tbName = "";
        public int checkCout = 0;
        public bool gridViewChk = false;        // True / False
        Helper_DB db = new Helper_DB();
        Help008Tag tag008 = new Help008Tag();
        Skill_Search_Text search_Text = new Skill_Search_Text();
        String_Text st = new String_Text();
        Mac_List ml;
        public BindingList<MarcBookItem> dataList = new BindingList<MarcBookItem>();
        MacListItem pItem = null;

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Alt 키 하나만 눌렸을 때 메뉴가 활성화되는 것을 방지
            if (keyData == Keys.Alt || keyData == (Keys.Alt | Keys.Menu))
            {
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }



        private void MarcEditorControl1_NextButton(object sender, EventArgs e)
        {
            bs1.MoveNext();
        }

        private void MarcEditorControl1_PrevButton(object sender, EventArgs e)
        {
            bs1.MovePrevious();
        }

        public Marc2(Mac_List _ml)
        {
            InitializeComponent();
            ml = _ml;
            mUserName = PUB.user.UserName;
            marcEditorControl1.db = this.db;
            marcEditorControl1.BookSaved += MarcEditorControl_BookSaved;
            marcEditorControl1.FillBlankClicked += MarcEditorControl_FillBlankClicked;
            marcEditorControl1.PrevButton += MarcEditorControl1_PrevButton;
            marcEditorControl1.NextButton += MarcEditorControl1_NextButton;
            marcEditorControl1.CloseButton += (s1, e1) => { this.Close(); };
        }


        private void Marc_Load(object sender, EventArgs e)
        {
            // 콤보박스 정렬및 필터
            string[] combo8 = { "등급", "복본" };
            comboBox8.Items.AddRange(combo8);

            comboBox8.SelectedIndex = 0;
            List_Book.RowPrePaint += List_Book_RowPrePaint;
        }

        public void input_list()
        {
            var dlg = UTIL.MsgQ("데이터베이스 내용을 다시 불러옵니다\n저장되지 않은 사항은 손실됩니다.다시 불러올까요?");
            if (dlg != DialogResult.Yes) return;
            input_list(pItem);
        }

        (string remark1, string remark2) ReadRemark(int row)
        {
            string[] sear_tbl = { "idx" };
            string[] sear_col = { List_Book.Rows[row].Cells["marc_idx"].Value.ToString() };
            string cmd = db.More_DB_Search("Marc", sear_tbl, sear_col, "`비고1`, `비고2`");
            string res = db.DB_Send_CMD_Search(cmd);

            string[] ary = res.Split('|');
            if (res.Length < 1) return (res, "");
            return (ary[0], ary[1]);
        }


        /// <summary>
        /// 가져온 목록을 책목록과 연동하여 Grid에 집어넣음.
        /// </summary>
        /// <param name="date">목록일자</param>
        /// <param name="value">목록명</param>
        public void input_list(MacListItem item)// )
        {
            this.pItem = item;
            //string l_idx, string value, string C_idx, string custidx, string custname

            //p_lidx = l_idx;
            //p_value = value;
            //p_cidx = C_idx;
            //p_cust = custidx;
            //p_name = custname;

            //item.idx,
            //item.list_name,
            //compidx,
            //item.customer,
            //item.customer_name
            //);


            db.DBcon();

            //var value = item.list_name;
            //this.List_Book.Rows.Clear();
            if (item.list_name.isEmpty() == false)
            {
                if (item.list_name.IndexOf("]") != -1)
                    this.Text = $"마크 작성(1)-{item.list_name.Substring(item.list_name.IndexOf("]") + 1)}";
                else
                    this.Text = $"마크 작성(1){item.list_name}";
            }


            string Area = "`idx`, `isbn_marc`, `header`, `num`, `book_name`, `author`, `book_comp`, `count`, `pay`, `image_url`, `m_idx`";
            string[] sear_tbl = { "l_idx", "compidx" };
            string[] sear_col = { item.idx, PUB.user.CompanyIdx };

            lbl_BookDate.Text = $"{item.start_date}";
            lbl_BookList.Text = item.list_name;
            tbCustName.Text = item.customer_name;
            lbCustIDX.Text = item.customer;

            string cmd =
                string.Format("SELECT {0} " +
                "FROM {1} " +
                "WHERE `{2}` = \"{4}\" AND `{3}` = \"{5}\"" +
                "ORDER BY `idx` ASC;", Area, "Obj_List_Book", sear_tbl[0], sear_tbl[1], sear_col[0], sear_col[1]);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] db_data = db_res.Split('|');
            string[] grid = {
                "", "", "", "", "",
                "", "", "", "", "",
                "", "", "V", "", "" };

            mLoadCompleted = false;

            dataList = new BindingList<MarcBookItem>();
            for (int a = 0; a < db_data.Length - 1; a += 11)
            {
                MarcBookItem bitem = new MarcBookItem();
                bitem.ListIdx = db_data[a];    // 0: idx
                bitem.ISBN13 = db_data[a + 1];    // 1: isbn
                bitem.Num = db_data[a + 2] + db_data[a + 3];    // 2: header + num
                bitem.BookName = db_data[a + 4];    // 3: book_num
                bitem.Author = db_data[a + 5];    // 4: author
                bitem.BookComp = db_data[a + 6];    // 5: book_comp
                bitem.Count = db_data[a + 7];    // 6: count
                bitem.Pay = db_data[a + 8];    // 7: pay
                bitem.Url = db_data[a + 9];    // 8: image_url
                bitem.MarcIdx = db_data[a + 10];    // 9: m_idx

                dataList.Add(bitem);
            }
            bs1.DataSource = dataList;
            List_Book.AutoGenerateColumns = false;
            List_Book.DataSource = bs1;

            chk_Marc();

            List_Book.ClearSelection();
            mLoadCompleted = true;

            if (this.List_Book.RowCount > 0)
                List_Book.Rows[0].Selected = true;
        }

        /// <summary>
        /// 마크 유무 확인하는 함수
        /// </summary>
        void chk_Marc()
        {

            foreach (var dr in this.dataList) // (int a = 0; a < this.dataList.Count; a++)
            {
                string Area =
                    // 0 1
                    "`idx`, `compidx`, " +
                    // 2 3 4 5 6 7
                    "`marc`, `marc_chk`, `marc1`, `marc_chk1`, `marc2`, `marc_chk2`, " +
                    // 8 9 10 11
                    "`grade`, `008tag`, `user`, `date`";

                string Table = "Marc";

                string[] sear_tbl = { "ISBN" };

                var isbn = dr.ISBN13;//.isbn List_Book.Rows[a].Cells["ISBN13"].Value?.ToString() ?? string.Empty;
                string[] sear_col = { isbn };

                //if (List_Book.Rows[a].Cells["marc_idx"].Value.ToString() != "0") {//여기 조건이 이상함.. 여기 조건때문에 순서가 잘 못 뜨는 경우 발생..
                //    sear_tbl[0] = "idx";
                //    sear_col[0] = List_Book.Rows[a].Cells["marc_idx"].Value.ToString();
                //}

                string Chk_Cmd = string.Format("SELECT {0} FROM {1} WHERE `{2}` = \"{3}\" ORDER BY FIELD(`compidx`, {4}) DESC;",
                    Area, Table, sear_tbl[0], sear_col[0], mCompidx);

                string Chk_Res = db.DB_Send_CMD_Search(Chk_Cmd);
                string[] Chk_Arr = Chk_Res.Split('|');

                bool isMyData = true;
                if (Chk_Arr.Length < 2) //마크DB에서 데이터가 없다면?
                {
                    dr.Grade = "3"; //List_Book.Rows[a].Cells["grade"].Value = "3";
                    dr.ForeColor = Color.Red;//List_Book.Rows[a].DefaultCellStyle.ForeColor = Color.Red;
                    continue;
                }

                if (Chk_Arr[1] != mCompidx)
                    isMyData = false;

                string[] MarcData = { Chk_Arr[2], Chk_Arr[4], Chk_Arr[6] };
                string[] CheckData = { Chk_Arr[3], Chk_Arr[5], Chk_Arr[7] };

                dr.ForeColor = SetGradeColor(Chk_Arr[8], isMyData); // Temporary, chk_Marc updates item below
                dr.MarcIdx = Chk_Arr[0]; //List_Book.Rows[a].Cells["marc_idx"].Value = Chk_Arr[0];
                dr.DbMarc = MarcData[0];// List_Book.Rows[a].Cells["db_marc"].Value = MarcData[0];//NewestMarc(MarcData, CheckData);
                dr.Grade = Chk_Arr[8];// List_Book.Rows[a].Cells["grade"].Value = Chk_Arr[8];
                                      // text008.Text = Chk_Arr[9];
                dr.User = Chk_Arr[10];//  List_Book.Rows[a].Cells["user"].Value = Chk_Arr[10];
                dr.SaveDate = Chk_Arr[11];//  List_Book.Rows[a].Cells["SaveDate"].Value = Chk_Arr[11];

                //var item = List_Book.Rows[a].DataBoundItem as MarcBookItem;
                Color gradeColor = SetGradeColor(Chk_Arr[8], isMyData);
                dr.ForeColor = gradeColor;
                //if (item != null) item.ForeColor = gradeColor;
                //List_Book.Rows[a].DefaultCellStyle.ForeColor = gradeColor;

                if (isMyData)
                {
                    Color saveColor = GetSaveDateColor(Chk_Arr[11]);
                    dr.BackColor = saveColor;
                }
                else
                {
                    string FindCompCmd = string.Format("SELECT `comp_name` FROM `Comp` WHERE `idx` = {0}", Chk_Arr[1]);
                    dr.User = db.DB_Send_CMD_Search(FindCompCmd).Replace("|", "");
                    dr.BackColor = Color.LightGray;
                }
            }
        }

        private string NewestMarc(string[] marc, string[] marc_chk)
        {
            string result = "";
            int count = 0;
            foreach (string chk in marc_chk)
            {
                if (chk == "1")
                    result = marc[count];

                count++;
            }
            return result;
        }

        private Color SetGradeColor(string Grade, bool isMyData = true)
        {
            if (!isMyData)
                return Color.Orange;

            switch (Grade)
            {
                case "0": // A
                    return Color.Blue;

                case "1": // B
                    return Color.Black;

                case "2": // C
                    return Color.Gray;

                case "3": // D
                    return Color.DarkViolet;

                default:
                    return Color.Black;
            }
        }

        /// <summary>
        /// 마지막 저장시각 14일이전일 경우 배경 색 변경
        /// </summary>
        /// <param name="Date">마지막 저장시각</param>
        private Color GetSaveDateColor(string Date)
        {
            DateTime SaveDate = DateTime.ParseExact(Date, "yyyy-MM-dd HH:mm:ss",
                System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
            DateTime TargetDate = DateTime.Today.AddDays(-14);

            int result = DateTime.Compare(SaveDate, TargetDate);

            if (result >= 0)    // SaveDate가 같거나 큼
                return Color.Yellow;

            else                // TargetDate가 큼
                return Color.White;

        }

        private void List_Book_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex < 0 || e.RowIndex >= List_Book.RowCount) return;
            var item = List_Book.Rows[e.RowIndex].DataBoundItem as MarcBookItem;
            if (item != null)
            {
                List_Book.Rows[e.RowIndex].DefaultCellStyle.ForeColor = item.ForeColor;
                List_Book.Rows[e.RowIndex].DefaultCellStyle.BackColor = item.BackColor;
            }
            else
            {
                List_Book.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Gray;
                List_Book.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.DimGray;
            }
        }


        private string mOldMarc = string.Empty;
        private void List_Book_SelectionChanged(object sender, EventArgs e)
        {
            if (!mLoadCompleted) return;
            if (List_Book.CurrentCell == null) return;
            int row_idx = List_Book.CurrentCell.RowIndex;
            int col_idx = List_Book.CurrentCell.ColumnIndex;

            if (List_Book.SelectedCells.Count > 0)
            {
                row_idx = List_Book.SelectedCells[0].RowIndex;
                col_idx = List_Book.SelectedCells[0].ColumnIndex;
            }

            if (row_idx == -1 || col_idx == -1) { return; }
            SaveRowIdx = row_idx;

            mOldMarc = List_Book.Rows[row_idx].Cells["db_marc"].Value?.ToString() ?? string.Empty;
            string isbn = List_Book.Rows[row_idx].Cells["ISBN13"].Value.ToString();
            if (isbn != "")
            {
                string CountQuery = string.Format("SELECT Count(isbn) FROM Marc WHERE isbn = {0} GROUP BY isbn;", isbn);
                string CountResult = db.self_Made_Cmd(CountQuery).Replace("|", "");

                if (CountResult == "")
                    btn_CopySelect.Text = "0";

                if (CountResult == "0")
                {
                    btn_CopySelect.Enabled = false;
                    btn_CopySelect.BackColor = Color.Silver;
                }
                else
                {
                    btn_CopySelect.Enabled = true;
                    btn_CopySelect.BackColor = Color.Khaki;
                }

                btn_CopySelect.Text = CountResult;
            }

            if (check_V(row_idx, col_idx))
                return;

            string isbn13 = List_Book.Rows[row_idx].Cells["ISBN13"].Value?.ToString() ?? "";
            string bookName = List_Book.Rows[row_idx].Cells["book_name"].Value?.ToString() ?? "";
            string author = List_Book.Rows[row_idx].Cells["author"].Value?.ToString() ?? "";
            string publisher = List_Book.Rows[row_idx].Cells["book_comp"].Value?.ToString() ?? "";
            string price = List_Book.Rows[row_idx].Cells["pay"].Value?.ToString() ?? "";
            string url = List_Book.Rows[row_idx].Cells["url"].Value?.ToString() ?? ""; // or image_url?
            string marcIdx = List_Book.Rows[row_idx].Cells["marc_idx"].Value?.ToString() ?? "";
            string dbMarc = List_Book.Rows[row_idx].Cells["db_marc"].Value?.ToString() ?? "";
            string grade = List_Book.Rows[row_idx].Cells["grade"].Value?.ToString() ?? "";
            string user = List_Book.Rows[row_idx].Cells["user"].Value?.ToString() ?? "";
            string saveDate = List_Book.Rows[row_idx].Cells["SaveDate"].Value?.ToString() ?? "";
            string listIdx = List_Book.Rows[row_idx].Cells["list_idx"].Value?.ToString() ?? ""; // verify this column name in input_list
            this.lbListIdx.Text = $"Row:{SaveRowIdx},List:{listIdx}";
            var remark = ReadRemark(row_idx);
            var p = new MacEditorParameter
            {
                ISBN13 = isbn13,
                URL = url,
                Grade = grade,
                ListIdx = listIdx,
                MarcIdx = marcIdx,
                SaveDate = saveDate,
                User = user,
                BookName = bookName,
                Author = author,
                Publisher = publisher,
                Price = price,
                Remark1 = remark.remark1,
                Remark2 = remark.remark2,
                OriginalMarc = dbMarc,
            };
            marcEditorControl1.LoadBookData(dbMarc, p);
        }


        bool check_V(int row, int col)
        {
            string name = List_Book.Columns[col].Name;
            if (name == "colCheck")
            {
                if (List_Book.Rows[row].Cells[col].Value.ToString() == "V")
                    List_Book.Rows[row].Cells[col].Value = "";

                else
                    List_Book.Rows[row].Cells["colCheck"].Value = "V";

                return true;
            }
            else
                return false;
        }


        private void btn_Search_Click(object sender, EventArgs e)
        {
            if (List_Book.RowCount < 0) return;

            Search_ReSet();

            bool isSort = rb_Sort.Checked;
            int combo = comboBox8.SelectedIndex;        // 0: 등급 / 1: 복본

            if (isSort)
            {
                var list = bs1.DataSource as BindingList<MarcBookItem>;
                if (list != null)
                {
                    List<MarcBookItem> sorted;
                    if (combo == 0)
                    {
                        sorted = list.OrderBy(x => x.Grade).ToList();
                    }
                    else
                    {
                        sorted = list.OrderBy(x => x.ISBN13).ToList();
                    }

                    list.RaiseListChangedEvents = false;
                    list.Clear();
                    foreach (var item in sorted) list.Add(item);
                    list.RaiseListChangedEvents = true;
                    list.ResetBindings();
                }
            }
            else
            {
                int comboIdx;
                if (combo == 0)
                {
                    comboIdx = comboBox9.SelectedIndex;
                    Search_Filter("grade", comboIdx);
                }
                else
                {      // 수정필요

                }
            }
        }
        #region Search_Click_Sub
        private void Search_ReSet()
        {
            DataGridViewBand reSet;
            for (int a = 0; a < List_Book.RowCount; a++)
            {
                reSet = List_Book.Rows[a];
                reSet.Visible = true;
            }
        }

        private void Search_Filter(string target, int comboIdx)
        {
            int count = List_Book.Rows.Count;
            DataGridViewBand band;
            if (comboIdx == 0)
            {
                for (int a = 0; a < count; a++)
                {
                    band = List_Book.Rows[a];
                    band.Visible = true;
                }
                return;
            }

            comboIdx--;
            for (int a = 0; a < count; a++)
            {
                if (List_Book.Rows[a].Cells[target].Value.ToString() != comboIdx.ToString())
                {
                    band = List_Book.Rows[a];
                    band.Visible = false;
                }
            }
        }
        #endregion

        private void btn_CopySelect_Click(object sender, EventArgs e)
        {
            //TODO: 마크 물리는쪽
            //int row = List_Book.CurrentCell.RowIndex;
            //string isbn = List_Book.Rows[row].Cells["ISBN13"].Value.ToString();
            //var item = List_Book.CurrentRow.DataBoundItem as MarcBookItem;

            var dr = this.bs1.Current as MarcBookItem;

            var copySelect = new MarcCopySelect2(this,dr);
            copySelect.Init("isbn", dr.ISBN13);
            copySelect.Show();
        }

        /// <summary>
        /// 선택된 마크에 대한 정보를 그리드뷰에 저장.
        /// </summary>
        /// <param name="row"></param>
        /// <param name="GridData">[0] idx, [1] compidx, [2] user, [3] date, [4] grade, [5] tag008, [6] marc </param>
        public void SelectMarc_Sub(MarcBookItem row, string[] GridData)
        {
           row.MarcIdx = GridData[0];
            row.User= GridData[2];
            row.SaveDate = GridData[4];
            row.Grade= GridData[3];
            // text008.Text = GridData[5];
            row.DbMarc= GridData[6];
            mOldMarc = GridData[6];
            
            row.ForeColor = SetGradeColor(row.Grade);
            row.BackColor = Color.Yellow;
          
            var currentitem = this.bs1.Current as MarcBookItem;  
            if (currentitem  != null && currentitem == row)
            {
                List_Book_SelectionChanged(null, null);
            }
        }

        private void MarcEditorControl_BookSaved(object sender, MarcEditorControl.BookSavedEventArgs e)
        {
            // [신규 방식: 데이터 객체(Item) 중심 로직]
            var item = this.dataList.Where(t => t.ListIdx == e.Param.ListIdx).FirstOrDefault();
            if (item == null) return;

            string table_name = "Marc";
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string newsavedMarc = e.DBMarc;
            //string Midx = item.MarcIdx;

            // 1. DB 작업 (저장 전략 결정: Foreground 색상 기준)
            if (item.ForeColor == Color.Orange || item.ForeColor == Color.Red)
            {
                string[] Insert_tbl = { "ISBN", "서명", "저자", "출판사", "가격", "marc", "비고1", "비고2", "url", "grade", "marc_chk", "user", "division", "008tag", "date", "compidx" };
                string[] Insert_col = { e.Param.ISBN13, e.Param.BookName, e.Param.Author, e.Param.Publisher, e.Param.Price, newsavedMarc, e.Param.Remark1, e.Param.Remark2, e.Param.URL, e.Param.Grade, "1", mUserName, e.Param.tag056, e.Param.text008, date, mCompidx };

                string Incmd = db.DB_INSERT(table_name, Insert_tbl, Insert_col);
                PUB.log.Add("INSERT", string.Format("{0}({1},{2}) : {3}", mUserName, mCompidx, item.ForeColor, Incmd));

                long newIdx = db.DB_Send_CMD_Insert_GetIdx(Incmd);
                if (newIdx > 0)
                {
                    item.MarcIdx = newIdx.ToString();
                }
            }
            else
            {
                string[] Edit_tbl = { "compidx", "marc", "marc_chk", "marc1", "marc_chk1", "비고1", "비고2", "url", "division", "008tag", "date", "user", "grade" };
                string[] Edit_col = { mCompidx, newsavedMarc, "1", e.Param.OriginalMarc, "0", e.Param.Remark1, e.Param.Remark2, e.Param.URL, e.Param.tag056, e.Param.text008, date, mUserName, e.Param.Grade };
                string[] Sear_tbl = { "idx", "compidx" };
                string[] Sear_col = { item.MarcIdx, mCompidx };

                if (string.IsNullOrEmpty(e.Param.ISBN13)) { MessageBox.Show("ISBN 데이터가 없습니다."); return; }

                string U_cmd = db.More_Update(table_name, Edit_tbl, Edit_col, Sear_tbl, Sear_col);
                PUB.log.Add("Update", string.Format("{0}({1},{2}) : {3}", mUserName, mCompidx, item.ForeColor, U_cmd.Replace("\r", " ").Replace("\n", " ")));
                Helper_DB.ExcuteNonQuery(U_cmd);
            }

            // 2. 객체 데이터 업데이트 및 시각적 상태 계산
            item.Grade = e.Param.Grade;
            item.SaveDate = date;
            item.User = mUserName;
            item.DbMarc = e.DBMarc;
            item.ForeColor = SetGradeColor(item.Grade);
            item.BackColor = GetSaveDateColor(date);

            // 3. 목록 인덱스 연동 업데이트 (Obj_List_Book)
            string UpdateListIndex = string.Format("UPDATE `Obj_List_Book` SET `m_idx` = {0} WHERE `idx` = {1} AND `compidx` ={2};", item.MarcIdx, item.ListIdx, mCompidx);
            Helper_DB.ExcuteNonQuery(UpdateListIndex);

            // 4. BindingSource 갱신으로 UI 자동 업데이트
            bs1.ResetCurrentItem();
            MessageBox.Show("저장되었습니다!");
        }

        #region Save_Click_Sub

        /// <summary>
        /// 마크 저장시 사용하며, 마지막 수정일과 수정자를 가져와 덮어씌울지 백업데이터를 만들지 구분
        /// </summary>
        /// <param name="TimeSpanDaysValue">저장할 마크의 마지막 수정일</param>
        /// <param name="user">저장할 마크의 마지막 수정자</param>
        /// <returns>마지막 수정일로부터 2일이 지나지않고, 마지막 수정자와 해당 유저가 동일 할 경우 true 반환</returns>
        private bool IsCoverData(int TimeSpanDaysValue, string user)
        {
            if (TimeSpanDaysValue < -1)
                return false;
            if (user != mUserName)
                return false;

            return true;
        }

        private TimeSpan spspsp(string LastDate, string SaveDate)
        {
            DateTime date1 = Convert.ToDateTime(LastDate);
            DateTime date2 = Convert.ToDateTime(SaveDate);

            TimeSpan result = date1 - date2;
            return result;
        }

        #endregion

        private void MarcEditorControl_FillBlankClicked(object sender, EventArgs e)
        {
            if (List_Book.CurrentRow == null) return;
            int row = List_Book.CurrentRow.Index;
            string ISBN = List_Book.Rows[row].Cells["ISBN13"].Value?.ToString();

            if (string.IsNullOrEmpty(ISBN))
            {
                MessageBox.Show("ISBN이 존재하지않습니다!");
                return;
            }

            var fb = new Marc_FillBlank();
            for (int a = 0; a < List_Book.Rows.Count; a++)
            {
                if (List_Book.Rows[a].DefaultCellStyle.ForeColor == Color.Red)
                {
                    var item = new FillBlankItem
                    {
                        Idx = a.ToString(),
                        Isbn = List_Book.Rows[a].Cells["ISBN13"].Value?.ToString() ?? "",
                        BookName = List_Book.Rows[a].Cells["book_name"].Value?.ToString() ?? "",
                        Author = List_Book.Rows[a].Cells["author"].Value?.ToString() ?? "",
                        Publisher = List_Book.Rows[a].Cells["book_comp"].Value?.ToString() ?? "",
                        Price = List_Book.Rows[a].Cells["pay"].Value?.ToString() ?? ""
                    };
                    fb.InitFillBlank(item);
                }
            }
            fb.ISBN = ISBN;
            if (fb.ShowDialog() == DialogResult.OK)
            {
                String_Text st = new String_Text();
                if (fb.BulkMarcResults.Count > 0)
                {
                    foreach (var kvp in fb.BulkMarcResults)
                    {
                        // Use list_idx to find row? Or assume key matches?
                        // Marc_FillBlank used 'idx' from 'List_idx' column.
                        // We need to iterate List_Book to find matching List_idx or if key is row index?
                        // In Marc_FillBlank, I stored 'idx' which was from 'List_idx'.
                        // Key = List_idx.
                        int targetListIdx = kvp.Key;
                        // Find row with this list_idx
                        foreach (DataGridViewRow r in List_Book.Rows)
                        {
                            if (r.Cells["List_idx"].Value != null && Convert.ToInt32(r.Cells["List_idx"].Value) == targetListIdx)
                            {
                                r.Cells["db_marc"].Value = kvp.Value;
                                // Update color etc?
                                r.DefaultCellStyle.ForeColor = Color.Blue;
                                // Need to update 'item' too if bound
                                var item = r.DataBoundItem as MarcBookItem;
                                if (item != null) item.ForeColor = Color.Blue;
                                break;
                            }
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(fb.SingleMarcResult))
                {
                    // Update current Editor
                    marcEditorControl1.SetMarcString(fb.SingleMarcResult);
                }
            }
        }





        private void btn_mk_marcList_Click(object sender, EventArgs e)
        {
            var mkList = new Marc_mkList2(this);
            mkList.StartPosition = FormStartPosition.CenterScreen;
            mkList.Show();
        }
        #region 마크생성목록_Sub

        /// <summary>
        /// 글자색이 빨간색이 아니라면 True 를 반환합니다.
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public bool Check_BackColor(int row)
        {
            if (List_Book.Rows[row].DefaultCellStyle.ForeColor != Color.Red)
                return true;

            return false;
        }
        /// <summary>
        /// ColCheck 값이 V 라면 True 를 반환합니다.
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public bool Check_List_V(int row)
        {
            if (List_Book.Rows[row].Cells["colCheck"].Value.ToString() == "V")
                return true;

            return false;
        }
        #endregion

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            bool isCheck = chkColCheck.Checked;
            if (isCheck)
            {
                for (int a = 0; a < List_Book.Rows.Count; a++)
                {
                    List_Book.Rows[a].Cells["colCheck"].Value = "V";
                }
            }
            else
            {
                for (int a = 0; a < List_Book.Rows.Count; a++)
                {
                    List_Book.Rows[a].Cells["colCheck"].Value = "";
                }
            }
        }

        private void List_Book_KeyDown(object sender, KeyEventArgs e)
        {
            int row = List_Book.CurrentCell.RowIndex;
            if (e.KeyCode == Keys.Space)
            {
                if (List_Book.Rows[row].Cells["colCheck"].Value.ToString() == "V")
                    List_Book.Rows[row].Cells["colCheck"].Value = "";

                else
                    List_Book.Rows[row].Cells["colCheck"].Value = "V";
            }
        }

        private void FillTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;

            if (e.Alt && e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z)
            {
                var letter = e.KeyCode.ToString().ToLower();
                tb.InvokeInsertText("▽" + letter);
                e.SuppressKeyPress = true;
                return;
            }

            if (e.KeyCode == Keys.F3)
            {
                tb.InvokeInsertText("▽");
            }
            else if (e.KeyCode == Keys.F4)
            {
                tb.InvokeInsertText("△");
            }
        }


        #region DataGridView 드래그 행이동 이벤트 함수

        Skill_Grid sg = new Skill_Grid();

        private void List_Book_MouseMove(object sender, MouseEventArgs e)
        {
            sg.MouseMove(sender, e);
        }

        private void List_Book_MouseDown(object sender, MouseEventArgs e)
        {
            sg.MouseDown(sender, e);
        }

        private void List_Book_DragOver(object sender, DragEventArgs e)
        {
            sg.DragOver(sender, e);
        }

        private void List_Book_DragDrop(object sender, DragEventArgs e)
        {
            sg.DragDrop(sender, e);
        }

        #endregion



        private bool isEmpty(string boxText)
        {
            if (boxText == "")
                return false;
            return true;
        }

        private bool isEmpty(string[] boxText)
        {
            bool[] isText = new bool[boxText.Length];
            int count = 0;
            int chkCount = 0;
            foreach (string Check in boxText)
            {
                if (Check == "")
                    isText[count] = false;
                else
                {
                    isText[count] = true;
                    chkCount++;
                }
                count++;
            }

            if (chkCount == 0)
                return false;

            return true;
        }


        private void btn_FilterReturn_Click(object sender, EventArgs e)
        {
            rb_Filter.Checked = false;
            rb_Sort.Checked = false;

            comboBox8.SelectedIndex = 0;
            comboBox9.SelectedIndex = 0;

            List_Book.Sort(list_idx, System.ComponentModel.ListSortDirection.Ascending);
        }

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

        private void lbl_BookList_Click(object sender, EventArgs e)
        {
            LovCustom();

        }

        void LovCustom()
        {
            var inputsearch = "";// tbCustName.Text.Trim();
            var where = "";
            if (inputsearch.isEmpty() == false)
            {
                where = $"c_sangho like '%{inputsearch.Replace("'", "''")}%'";
            }
            var dt = Helper_DB.GetDT("Client", columns: "idx,c_sangho", orders: "c_sangho", wheres: where);
            using (var f = new fSelectDT(dt))
                if (f.ShowDialog() == DialogResult.OK)
                {
                    var dr = f.SelectedRow;
                    if (dr == null) return;
                    lbCustIDX.Text = dr["idx"]?.ToString() ?? string.Empty;
                    tbCustName.Text = dr["c_sangho"]?.ToString() ?? string.Empty;

                    if (int.TryParse(lbCustIDX.Text, out int custidx) && custidx >= 0)
                    {
                        var sql = $"update Obj_List set customer={custidx} where idx = {pItem.idx} and comp_num={PUB.user.CompanyIdx}";
                        var ret = Helper_DB.ExcuteNonQuery(sql);
                        if (ret.applyCount != 1)
                            UTIL.MsgE($"데이터 저장시 오류가 발생했습니다. 영향을 받은 행 수 = {ret.applyCount},메세지={ret.errorMessage}");
                    }

                }
        }

        private void Marc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                if (UTIL.MsgQ("현재 화면을 닫을까요?") != DialogResult.Yes) return;
                this.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 현재 데이터를 한줄 복사하고 ISBN 값을 삭제한다
            // 생성된 자료는 좌측 목록에 추가되어야하고, 그 목록이 선택되도록 한다.
            if (List_Book.SelectedRows.Count == 0)
                return;

            DataGridViewRow selectedRow = List_Book.SelectedRows[0];
            int nRow = List_Book.Rows.Add();
            DataGridViewRow newRow = List_Book.Rows[nRow];

            for (int i = 0; i < selectedRow.Cells.Count; i++)
            {
                newRow.Cells[i].Value = selectedRow.Cells[i].Value;
            }

            newRow.Cells["ISBN13"].Value = "";
            newRow.Cells["marc_idx"].Value = "";
            newRow.Cells["list_idx"].Value = "";
            //newRow.Cells["grade"].Value = "3"; // 등급 초기화 (D)
            newRow.DefaultCellStyle.ForeColor = Color.Red; // 색상 초기화 (D급 색상)

            List_Book.ClearSelection();
            newRow.Selected = true;
            List_Book.FirstDisplayedScrollingRowIndex = nRow;
        }

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

        private void Marc2_SizeChanged(object sender, EventArgs e)
        {
            // this.toolStripStatusLabel1.Text = $"{this.Size}";
        }

        private void rb_Sort_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            string text = rb.Text;
            if (text == "정렬")
                comboBox9.Enabled = false;

            else
                comboBox9.Enabled = true;
        }

        private void comboBox8_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            comboBox9.Items.Clear();

            ComboBox cb = sender as ComboBox;
            if (cb.SelectedIndex == 0)
            {
                comboBox9.Enabled = true;
                string[] grade = { "전체", "A", "B", "C", "D" };
                comboBox9.Items.AddRange(grade);
                comboBox9.SelectedIndex = 0;
            }
            else
                comboBox9.Enabled = false;
        }


        private void button1_Click_1(object sender, EventArgs e)
        {
            //re load data
            input_list();
        }
    }
}