using AR;
using arCtl.TinyListview;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
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.Web.UI.WebControls.WebParts;
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();
        MacListItem ml;
        public SortableBindingList<MarcBookItem> dataList = new SortableBindingList<MarcBookItem>();
        public MacEditorParameter Param;
        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(MacListItem _ml)
        {
            InitializeComponent();
            ml = _ml;
            mUserName = PUB.user.UserName;
            marcEditorControl1.db = this.db;
      
        }


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

            comboBox8.SelectedIndex = 0;

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

            //refresh data
            this.input_list(ml);

            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(string marcidx)
        {
            string[] sear_tbl = { "idx" };
            string[] sear_col = { marcidx };// 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>
        private 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 = "LB.`idx`, LB.`isbn_marc`, LB.`header`, LB.`num`, LB.`book_name`, LB.`author`, LB.`book_comp`, LB.`count`, LB.`pay`, LB.`image_url`, LB.`m_idx`, LB.category " +
                ", LB.`search_book_name`, LB.`search_author`, LB.`search_book_comp`, LB.`search_description`, LB.`search_url` " +
                ", M.`compidx` AS m_compidx, M.`marc`, M.`grade`, M.`user` AS m_user, M.`date` AS m_date, C.`comp_name` ";
            string[] sear_tbl = { "LB.l_idx", "LB.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} AS LB " +
                "LEFT JOIN `Marc` AS M ON LB.`m_idx` = M.`idx` " +
                "LEFT JOIN `Comp` AS C ON M.`compidx` = C.`idx` " +
                "WHERE {2} = \"{4}\" AND {3} = \"{5}\"" +
                "ORDER BY LB.`idx` ASC;", Area, "Obj_List_Book", sear_tbl[0], sear_tbl[1], sear_col[0], sear_col[1]);
            var db_res = Helper_DB.ExecuteDataTable(cmd);

            mLoadCompleted = false;

            dataList = new SortableBindingList<MarcBookItem>();
            foreach (DataRow dr in db_res.Rows)// (int a = 0; a < db_data.Length - 1; a += 11)
            {
                MarcBookItem bitem = new MarcBookItem();
                bitem.ListIdx = dr["idx"] != DBNull.Value ? Convert.ToInt32(dr["idx"]) : 0; // db_data[a];    // 0: idx
                bitem.ISBN13 = dr["isbn_marc"]?.ToString() ?? string.Empty; // db_data[a + 1];    // 1: isbn
                bitem.Num = (dr["header"]?.ToString() ?? string.Empty) +( dr["num"]?.ToString() ?? string.Empty); 
                //; //db_data[a + 2] + db_data[a + 3];    // 2: header + num
                bitem.BookName = dr["book_name"]?.ToString() ?? string.Empty; // db_data[a + 4];    // 3: book_num
                bitem.Author = dr["author"]?.ToString() ?? string.Empty; // db_data[a + 5];    // 4: author
                bitem.BookComp = dr["book_comp"]?.ToString() ?? string.Empty; //db_data[a + 6];    // 5: book_comp
                bitem.Count = dr["count"]?.ToString() ?? string.Empty; // db_data[a + 7];    // 6: count
                bitem.Pay = dr["pay"] != DBNull.Value ? Convert.ToInt32(dr["pay"]) : 0; //db_data[a + 8];    // 7: pay
                bitem.Url = dr["image_url"]?.ToString() ?? string.Empty; //db_data[a + 9];    // 8: image_url
                bitem.MarcIdx = dr["m_idx"] != DBNull.Value ? Convert.ToInt32(dr["m_idx"]) : 0; //db_data[a + 10];    // 9: m_idx
                bitem.category = dr["category"]?.ToString() ?? string.Empty;
                bitem.search_book_name = dr["search_book_name"]?.ToString() ?? string.Empty; //db_data[a + 11];    // 9: m_idx
                bitem.search_author = dr["search_author"]?.ToString() ?? string.Empty; //db_data[a + 12];    // 9: m_idx
                bitem.search_book_comp = dr["search_book_comp"]?.ToString() ?? string.Empty; //db_data[a + 13];    // 9: m_idx
                bitem.search_description = dr["search_description"]?.ToString() ?? string.Empty; // db_data[a + 14];    // 9: m_idx
                bitem.search_url = dr["search_url"]?.ToString() ?? string.Empty;

                // Joined MARC data
                if (bitem.MarcIdx > 0 && dr["marc"] != DBNull.Value)
                {
                    SetMarcItemInfo(bitem, 
                        bitem.MarcIdx, 
                        dr["m_compidx"]?.ToString() ?? string.Empty, 
                        dr["marc"]?.ToString() ?? string.Empty, 
                        dr["grade"]?.ToString() ?? string.Empty, 
                        dr["m_user"]?.ToString() ?? string.Empty, 
                        dr["m_date"]?.ToString() ?? string.Empty, 
                        dr["comp_name"]?.ToString() ?? string.Empty);
                }
                else
                {
                    bitem.Grade = "3";
                    bitem.Status = MarcRecordStatus.None;
                }

                dataList.Add(bitem);
            }

            chk_Marc();

            List_Book.ClearSelection();
            mLoadCompleted = true;

            bs1.DataSource = dataList;
            List_Book.AutoGenerateColumns = false;
            List_Book.DataSource = bs1;

        }

        /// <summary>
        /// 모든 데이터의 마크 유무 확인하는 함수
        /// </summary>
        void chk_Marc()
        {
            // 1. 자사 마크 ISBN 매칭 (m_idx가 0인 항목들 대상)
            string qMy = string.Format(
                "SELECT LB.`idx` as list_idx, M.`idx` as m_idx, M.`marc`, M.`grade`, M.`user` as m_user, M.`date` as m_date " +
                "FROM `Obj_List_Book` LB " +
                "JOIN `Marc` M ON LB.`isbn_marc` = M.`ISBN` " +
                "WHERE LB.`l_idx` = \"{0}\" AND LB.`compidx` = \"{1}\" AND LB.`m_idx` = 0 " +
                "AND M.`compidx` = \"{1}\" " +
                "GROUP BY LB.`idx`", ml.idx, mCompidx);

            DataTable dtMy = Helper_DB.ExecuteDataTable(qMy);
            UpdateFromMatchedTable(dtMy, true);

            // 2. 타사 마크 ISBN 매칭 (여전히 m_idx가 0인 항목들 대상)
            string qOther = string.Format(
                "SELECT LB.`idx` as list_idx, M.`idx` as m_idx, M.`compidx` as m_compidx, M.`marc`, M.`grade`, M.`user` as m_user, M.`date` as m_date, C.`comp_name` " +
                "FROM `Obj_List_Book` LB " +
                "JOIN `Marc` M ON LB.`isbn_marc` = M.`ISBN` " +
                "JOIN `Comp` C ON M.`compidx` = C.`idx` " +
                "WHERE LB.`l_idx` = \"{0}\" AND LB.`compidx` = \"{1}\" AND LB.`m_idx` = 0 " +
                "AND M.`compidx` != \"{1}\" " +
                "GROUP BY LB.`idx`", ml.idx, mCompidx);

            DataTable dtOther = Helper_DB.ExecuteDataTable(qOther);
            UpdateFromMatchedTable(dtOther, false);

            // 3. 최종 정리 (매칭되지 않은 항목들)
            foreach (var item in dataList)
            {
                if (item.MarcIdx <= 0)
                {
                    item.Grade = "3";
                    item.Status = MarcRecordStatus.None;
                }
            }
        }

        /// <summary>
        /// 조인 결과 테이블을 바탕으로 dataList와 DB를 업데이트합니다.
        /// </summary>
        private void UpdateFromMatchedTable(DataTable dt, bool isMyData)
        {
            if (dt == null) return;
            foreach (DataRow row in dt.Rows)
            {
                int listIdx = Convert.ToInt32(row["list_idx"]);
                var item = dataList.FirstOrDefault(x => x.ListIdx == listIdx);
                // 이미 매칭된 경우(MarcIdx > 0)는 건너뜀 (자사 우선순위 보장)
                if (item != null && item.MarcIdx <= 0)
                {
                    int midx = Convert.ToInt32(row["m_idx"]);
                    string compIdx = isMyData ? mCompidx : (row["m_compidx"]?.ToString() ?? string.Empty);
                    string user = row["m_user"]?.ToString() ?? string.Empty;
                    string compName = isMyData ? "" : (row["comp_name"]?.ToString() ?? string.Empty);

                    SetMarcItemInfo(item, 
                        midx, 
                        compIdx, 
                        row["marc"]?.ToString() ?? string.Empty, 
                        row["grade"]?.ToString() ?? string.Empty, 
                        user, 
                        row["m_date"]?.ToString() ?? string.Empty, 
                        compName);

                    // DB에 m_idx 영구 저장
                    string updCmd = string.Format("UPDATE `Obj_List_Book` SET `m_idx` = {0} WHERE `idx` = {1};", midx, listIdx);
                    Helper_DB.ExcuteNonQuery(updCmd);
                }
            }
        }

        /// <summary>
        /// 마크 아이템의 상태, 등급, 배경색 등을 설정하는 공용 함수
        /// </summary>
        private void SetMarcItemInfo(MarcBookItem item, int marcIdx, string compIdx, string dbMarc, string grade, string user, string saveDate, string compName = "")
        {
            bool isMyData = (compIdx == mCompidx);
            item.MarcIdx = marcIdx;
            item.DbMarc = dbMarc;
            item.Grade = grade;
            item.SaveDate = saveDate;
            item.Status = isMyData ? MarcRecordStatus.MyCompany : MarcRecordStatus.OtherCompany;

            if (isMyData)
            {
                item.User = user;
                if (!string.IsNullOrEmpty(saveDate))
                {
                    item.BackColor = GetSaveDateColor(saveDate);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(compName))
                {
                    string FindCompCmd = string.Format("SELECT `comp_name` FROM `Comp` WHERE `idx` = \"{0}\"", compIdx);
                    item.User = db.DB_Send_CMD_Search(FindCompCmd).Replace("|", "");
                }
                else
                {
                    item.User = compName;
                }
                item.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;
        }

        /// <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 int mOldMarIdx = -1;
        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; }

            if (check_V(row_idx, col_idx))
                return;

        }


        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)
            {
                if (combo == 0)
                {
                    this.bs1.Sort = "Grade";
                    //sorted = list.OrderBy(x => x.Grade).ToList();
                }
                else
                {
                    this.bs1.Sort = "ISBN13";
                    //sorted = list.OrderBy(x => x.ISBN13).ToList();
                }
            }
            else
            {
                int comboIdx;
                if (combo == 0)
                {
                    comboIdx = comboBox9.SelectedIndex;
                    if (comboIdx == 0) //전체
                        this.bs1.Filter = "";
                    else
                        this.bs1.Filter = $"Grade={comboIdx}";
                    //Search_Filter("grade", comboIdx);
                }
                else
                {      // 수정필요
                    UTIL.MsgE("이 기능은 구현되지 않았습니다");
                }
            }
        }
        #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;

            //isbn으로 검색을 하게한다.
            using (var copySelect = new MarcCopySelect2("isbn", dr.ISBN13))
            {
                if (copySelect.ShowDialog() == DialogResult.OK)
                {
                    //사용자가 마크를 선택하면 해당 마크인덱스를 셋팅해준다
                    var selected = copySelect.SelectedItem;
                    dr.MarcIdx = selected.idx;
                    dr.User = selected.User;
                    dr.SaveDate = selected.Date;
                    dr.Grade = selected.Grade;
                    // text008.Text = selected.Tag008;
                    dr.DbMarc = selected.marc_db;
                    dr.Status = PUB.user.CompanyIdx == selected.compidx ? MarcRecordStatus.MyCompany : MarcRecordStatus.OtherCompany;
                    mOldMarc = selected.marc_db;

                    // row.ForeColor = SetGradeColor(row.Grade); // Handled by MarcBookItem automatically
                    dr.BackColor = Color.Yellow;

                    var currentitem = this.bs1.Current as MarcBookItem;
                    if (currentitem != null && currentitem == dr)
                    {
                        bs1_CurrentChanged(null, null);
                    }
                }
            }


        }




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

        }





        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)
        {
            var item = bs1.List[row] as MarcBookItem;
            if (item != null && item.Status != MarcRecordStatus.None)
                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;

            this.bs1.Filter = null;
            this.bs1.Sort = "ListIdx";
            //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.ExecuteQueryData("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();
            }
            else
                SaveGrade(e.KeyCode);
        }

        /// <summary>
        /// F9~F12로 등급별 저장
        /// </summary>
        /// <param name="key">F9~F12</param>
        private void SaveGrade(Keys key)
        {
            switch (key)
            {
                case Keys.F9:
                    uC_SelectGrade1.GradeName = "A";
                    //radA.Checked = true;//  cb_grade.SelectedIndex = 0;// = "A (F9)";
                    break;
                case Keys.F10:
                    uC_SelectGrade1.GradeName = "B";
                    //radB.Checked = true;//  cb_grade.SelectedIndex = 1;// = "B (F10)";
                    //Btn_Save_Click(null, null);
                    break;
                case Keys.F11:
                    uC_SelectGrade1.GradeName = "C";
                    //radC.Checked = true;//  cb_grade.SelectedIndex = 2;// = "C (F11)";
                    //Btn_Save_Click(null, null);
                    break;
                case Keys.F12:
                    uC_SelectGrade1.GradeName = "D";
                    //radD.Checked = true;// cb_grade.SelectedIndex = 3;//.SelectedItem = "D (F12)";
                    //Btn_Save_Click(null, null);
                    break;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

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

        private void btFindISBN_Click(object sender, EventArgs e)
        {
            string tSearchText = pItem.list_name;
            string tSearchIDX = pItem.idx;

            var main = Application.OpenForms.OfType<Main>().FirstOrDefault();
            if (main != null)
            {
                var isbn = main.OpenFormInTab(() => new Check_ISBN2(tSearchText, tSearchIDX));
                if (isbn != null)
                {
                    isbn.tb_list_name.Enabled = true;
                }
            }
        }

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

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

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

        private void button2_Click(object sender, EventArgs e)
        {
            var fullmarc = marcEditorControl1.MakeMarcString();
            using (var fb = new Marc_CopyForm(fullmarc))
                fb.ShowDialog();
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (Param.NewMake == false && string.IsNullOrEmpty(Param.ISBN13))
            {
                UTIL.MsgE("마크가 선택되지않았습니다.");
                return;
            }

            // 중앙 집중식 유효성 검사 수행
            if (!marcEditorControl1.CheckValidation())
            {
                return;
            }

            var v_isbn = marcEditorControl1.lbl_ISBN.Text.Trim();

            //// ISBN 중복체크
            //var exist = DB_Utils.ExistISBN(v_isbn);
            //if (exist)
            //{
            //    if (UTIL.MsgQ($"입력하신 ISBN({v_isbn})은 이미 등록된 데이터가 존재합니다.\n그래도 저장하시겠습니까?") != DialogResult.Yes)
            //    {
            //        return;
            //    }
            //}

            this.Param.text008 = marcEditorControl1.text008.Text.Trim();
            this.Param.tag056 = marcEditorControl1.Tag056(out string with008fullmarcstring);

            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string orimarc = marcEditorControl1.MakeMarcString();


            //아래는 실제 폼에서의 저장코드
            // [신규 방식: 데이터 객체(Item) 중심 로직]
            var item = this.dataList.Where(t => t.ListIdx == this.Param.ListIdx).FirstOrDefault();
            if (item == null) return;

            //string table_name = "Marc";
            string newsavedMarc = orimarc;

            // cb_grade.SelectedIndex.ToString(); // 등급은 0~3의 숫자로 저장된다고 가정
            var v_grade = uC_SelectGrade1.Grade == -1 ? "" : uC_SelectGrade1.Grade.ToString();
            //if (radA.Checked) v_grade = "0";
            //else if (radB.Checked) v_grade = "1";
            //else if (radC.Checked) v_grade = "2";
            //else if (radD.Checked) v_grade = "3";

            var v_etc1 = this.etc1.Text.Trim();
            var v_etc2 = this.etc2.Text.Trim();

            // 1. DB 작업 (공용 메서드로 통합 관리)
            int targetMarcIdx = (item.Status == MarcRecordStatus.MyCompany) ? item.MarcIdx : 0;
            var saveResult = Helper_DB.UpdateMarc(targetMarcIdx, orimarc, uC_SelectGrade1.Grade, v_etc1, v_etc2, this.Param.URL, this.Param.OriginalMarc);

            if (saveResult.result == false)
            {
                UTIL.MsgE(saveResult.message);
                return;
            }

            // 새로 생성된 인덱스 반영
            item.MarcIdx = saveResult.newidx;


            // 2. 객체 데이터 업데이트 및 시각적 상태 계산
            item.Status = MarcRecordStatus.MyCompany;
            item.BackColor = GetSaveDateColor(date);
            item.Grade = v_grade;   //등급업데이트추가

            // 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();
            bs1_CurrentChanged(null, null);
            UTIL.MsgI("저장되었습니다!");
        }

        private void btn_FillBlank_Click(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))
            {
                UTIL.MsgE("ISBN이 존재하지않습니다!");
                return;
            }

            var fb = new Marc_FillBlank();
            for (int a = 0; a < bs1.Count; a++)
            {
                var item = bs1.List[a] as MarcBookItem;
                if (item != null && item.Status == MarcRecordStatus.None)
                {
                    var fbItem = new FillBlankItem
                    {
                        Idx = item.ListIdx,
                        Isbn = item.ISBN13 ?? "",
                        BookName = item.BookName ?? "",
                        Author = item.Author ?? "",
                        Publisher = item.BookComp ?? "",
                        Price = item.Pay
                    };
                    fb.InitFillBlank(fbItem);
                }
            }
            fb.ISBN = ISBN;
            if (fb.ShowDialog() == DialogResult.OK)
            {
                String_Text st = new String_Text();
                if (fb.FillBlankItems.Any(t => !string.IsNullOrEmpty(t.BookMarc)))
                {
                    foreach (var fbItem in fb.FillBlankItems)
                    {
                        if (string.IsNullOrEmpty(fbItem.BookMarc)) continue;

                        int targetListIdx = fbItem.Idx;
                        foreach (MarcBookItem item in this.dataList)
                        {
                            if (item.ListIdx == targetListIdx)
                            {
                                item.DbMarc = fbItem.BookMarc;
                                item.Status = MarcRecordStatus.NewFetched;
                                break;
                            }
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(fb.SingleMarcResult))
                {
                    // Update current Editor
                    marcEditorControl1.SetMarcString(fb.SingleMarcResult);
                }
            }
        }

        private void panel6_Paint(object sender, PaintEventArgs e)
        {

        }

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

        private void etc1_KeyDown(object sender, KeyEventArgs e)
        {
            var rt = sender as RichTextBox;
            if (rt == null) return;
            if (e.KeyCode == Keys.F5)
            {
                rt.AppendText("[" + DateTime.Now.ToString("yy-MM-dd") + "]");
            }
        }

        private void bs1_CurrentChanged(object sender, EventArgs e)
        {
            if (!mLoadCompleted) return;
            var dr = bs1.Current as MarcBookItem;
            if (dr == null) 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;
            if (dr.DbMarc != null && dr.DbMarc.Equals(mOldMarc) && dr.MarcIdx.Equals(this.mOldMarIdx)) return;

            mOldMarc = dr.DbMarc ?? string.Empty;// List_Book.Rows[row_idx].Cells["db_marc"].Value?.ToString() ?? string.Empty;
            mOldMarIdx = dr.MarcIdx;

            string isbn = dr.ISBN13;// 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;
            }


            string isbn13 = dr.ISBN13;// List_Book.Rows[row_idx].Cells["ISBN13"].Value?.ToString() ?? "";
            string bookName = dr.BookName;// List_Book.Rows[row_idx].Cells["book_name"].Value?.ToString() ?? "";
            string author = dr.Author;// List_Book.Rows[row_idx].Cells["author"].Value?.ToString() ?? "";
            string publisher = dr.BookComp;// List_Book.Rows[row_idx].Cells["book_comp"].Value?.ToString() ?? "";
            var price = dr.Pay;// List_Book.Rows[row_idx].Cells["pay"].Value?.ToString() ?? "";
            string url = dr.Url;// List_Book.Rows[row_idx].Cells["url"].Value?.ToString() ?? ""; // or image_url?
            var marcIdx = dr.MarcIdx;// List_Book.Rows[row_idx].Cells["marc_idx"].Value?.ToString() ?? "";
            string dbMarc = dr.DbMarc ?? string.Empty;// List_Book.Rows[row_idx].Cells["db_marc"].Value?.ToString() ?? "";
            string grade = dr.Grade;// List_Book.Rows[row_idx].Cells["grade"].Value?.ToString() ?? "";
            string user = dr.User;// List_Book.Rows[row_idx].Cells["user"].Value?.ToString() ?? "";
            string saveDate = dr.SaveDate;// List_Book.Rows[row_idx].Cells["SaveDate"].Value?.ToString() ?? "";
            var listIdx = dr.ListIdx;// List_Book.Rows[row_idx].Cells["list_idx"].Value?.ToString() ?? ""; // verify this column name in input_list
            this.lbListIdx.Text = $"Row:{bs1.Position},List:{listIdx},Marc:{marcIdx}";
            var remark = ReadRemark(dr.MarcIdx.ToString());
            this.Param = new MacEditorParameter
            {
                ISBN13 = isbn13,
                URL = url,
                ListIdx = listIdx,
                MarcIdx = marcIdx,
                SaveDate = saveDate,
                User = user,
                BookName = bookName,
                Author = author,
                Publisher = publisher,
                Price = price,
                OriginalMarc = dbMarc,
            };
            var defMarc = PUB.MakeEmptyMarc(isbn13, bookName, author, publisher, price);
            marcEditorControl1.LoadBookData(dbMarc, isbn13, defMarc);

            //등급선택 (dbMarc 데이터를 확인하여. 등급을 결정한다)
            int gradeNo;
            bool check_Marc = dbMarc.Length >= 3;
            if (!check_Marc)
            {
                //richTextBox1.Text = Make_Empty();
                gradeNo = 3; //마크가 없는것은 D등급으로 한다
            }
            else
            {
                etc1.Text = remark.remark1;
                etc2.Text = remark.remark2;

                //자료의 등급 다시 선택
                if (int.TryParse(grade, out gradeNo) == false)
                    gradeNo = 2;
            }

            uC_SelectGrade1.Grade = gradeNo;

            lbl_SaveData.Multiline = true;
            lbl_SaveData.Text = $"[{user}-{saveDate}]\r\n{dr.search_book_name}\r\n{dr.search_author}\r\n{dr.search_book_comp}\r\n{dr.category}";
            if (dr.search_url.isEmpty())
            {
                linkLabel1.Enabled = false;
                linkLabel1.Text = "ISBN 검색 URL이 존재하지않습니다.";
                linkLabel1.Tag = null;
            }
            else
            {
                linkLabel1.Text = dr.search_url;
                linkLabel1.Tag = dr.search_url;
                linkLabel1.Enabled = true;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (linkLabel1.Tag == null) return;
            var ulr = linkLabel1.Tag.ToString();
            System.Diagnostics.Process.Start(ulr);
        }
    }
}