using AR;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace UniMarc
{
    public partial class MarcCopySelect2 : Form
    {
        Helper_DB db = new Helper_DB();
        SortableBindingList<MarcCopyItem> _list = new SortableBindingList<MarcCopyItem>();

        public MarcCopyItem SelectedItem { get; private set; }

        public MarcCopySelect2(string search_col, string search_Target)
        {
            InitializeComponent();
            db.DBcon();

            // Lowercase mapping for common inputs from Marc2.cs or AddMarc2.cs
            string normalizedCol = search_col;
            if (search_col != null && search_col.ToLower() == "isbn") normalizedCol = "ISBN";
            else if (search_col == "도서명") normalizedCol = "서명";

            cb_SearchFilter.Text = normalizedCol;
            if (cb_SearchFilter.SelectedIndex < 0)
                cb_SearchFilter.SelectedIndex = 0;
            tb_SearchBox.Text = search_Target;

            SettingGrid_Book();
            bs1.DataSource = _list;
            dataGridView1.DataSource = bs1;
            dataGridView1.CellFormatting += dataGridView1_CellFormatting;

            if (!string.IsNullOrEmpty(search_Target))
                btn_Search_Click(null, null);
        }
       

        private void tb_SearchBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btn_Search_Click(null, null);
        }

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


            var search_Target = tb_SearchBox.Text.Trim();
            var search_col = cb_SearchFilter.Text.Trim();

            if (search_Target == "") return;

            // 0 1 2 3 4
            string Area = "`idx`, `compidx`, `ISBN`, `서명` AS Title, `저자` AS Author, " +
                          // 5 6 7 8 9
                          "`출판사` AS Comp, `user`, `date`, `grade`, `008tag`, " +
                          // 10 11 12 13 14 15
                          "`marc` AS marc_db, `marc_chk`, `marc1`, `marc_chk1`, `marc2`, `marc_chk2`, `비고1` as remark1, `비고2` as remark2," +
                          "권차,권차서명, `총서명`, `총서번호`, `출판년월`, `판차` as pancha, " +
                          "TRIM(CONCAT(IFNULL(권차, ''), ' ', IFNULL(권차서명, ''))) AS KwonchaFull, " +
                          "TRIM(CONCAT(IFNULL(`총서명`, ''), ' ', IFNULL(`총서번호`, ''))) AS TotalTitleFull";
            string Table = "Marc";

            string Query = string.Format("SELECT {0} FROM {1} WHERE `{2}` like \"%{3}%\";", Area, Table, search_col, search_Target);
            var dt = db.DB_Send_CMD_Search_DataTable(Query);

            InputGrid(dt);
        }

        private void SettingGrid_Book()
        {
            DataGridView dgv = dataGridView1;
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Clear();

            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "idx", HeaderText = "idx", Name = "idx", Visible = false });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "compidx", HeaderText = "compidx", Name = "compidx", Visible = false });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ISBN", HeaderText = "ISBN", Name = "isbn", Width = 100 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Title", HeaderText = "서명", Name = "Title", Width = 200 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Author", HeaderText = "저자", Name = "Author", Width = 150 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "KwonchaFull", HeaderText = "권차", Name = "KwonchaFull", Width = 150 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "TotalTitleFull", HeaderText = "총서명", Name = "TotalTitleFull", Width = 180 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Comp", HeaderText = "출판사", Name = "Comp", Width = 150 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "pancha", HeaderText = "판차", Name = "pancha", Width = 100 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "publishdate", HeaderText = "출판년월", Name = "publishdate", Width = 150 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "User", HeaderText = "수정자", Name = "user", Width = 120 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Date", HeaderText = "수정시각", Name = "date", Width = 150 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "DisplayGrade", HeaderText = "등급", Name = "grade", Width = 60 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Tag008", HeaderText = "008Tag", Name = "tag008", Width = 150 });
            dgv.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Marc", HeaderText = "Marc", Name = "marc", Width = 200 });
        }

        private void InputGrid(System.Data.DataTable dt)
        {
            _list.Clear();
            if (dt == null || dt.Rows.Count == 0) return;

            progressBar1.Value = 0;
            progressBar1.Maximum = dt.Rows.Count;

            foreach (DataRow row in dt.Rows)
            {
                var item = new MarcCopyItem
                {
                    idx =  Convert.ToInt32( row["idx"]),
                    compidx = row["compidx"].ToString(),
                    ISBN = row["ISBN"].ToString(),
                    Title = row["Title"].ToString(),
                    Author = row["Author"].ToString(),

                    KwonchaFull = row["KwonchaFull"].ToString(),
                    TotalTitleFull = row["TotalTitleFull"].ToString(),
                    pancha = row["pancha"].ToString(),
                    publishdate = row["출판년월"].ToString(),

                    Comp = row["Comp"].ToString(),
                    User = row["user"].ToString(),
                    Date = row["date"].ToString(),
                    Grade = row["grade"].ToString(),
                    Tag008 = row["008tag"].ToString(),
                    marc_db = row["marc_db"].ToString(),
                    marc_chk = row["marc_chk"].ToString(),
                    marc1 = row["marc1"].ToString(),
                    marc_chk1 = row["marc_chk1"].ToString(),
                    marc2 = row["marc2"].ToString(),
                    marc_chk2 = row["marc_chk2"].ToString(),
                    remark1 = row["remark1"].ToString(),
                    remark2 = row["remark2"].ToString(),
                };

                // Calculate real Marc based on check flags
                item.Marc = CalculateRealMarc(item);

                // For other company data, replace User with company name
                if (item.compidx != PUB.user.CompanyIdx)
                {
                    string FindCompCmd = string.Format("SELECT `comp_name` FROM `Comp` WHERE `idx` = {0}", item.compidx);
                    item.User = db.DB_Send_CMD_Search(FindCompCmd).Replace("|", "");
                }

                _list.Add(item);
                if (progressBar1.Value < progressBar1.Maximum)
                    progressBar1.Value += 1;
            }
        }

        private string CalculateRealMarc(MarcCopyItem item)
        {
            if (item.marc_chk == "1") return item.marc_db;
            if (item.marc_chk1 == "1") return item.marc1;
            if (item.marc_chk2 == "1") return item.marc2;
            return "";
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0 || e.RowIndex >= dataGridView1.Rows.Count) return;

            var item = (MarcCopyItem)dataGridView1.Rows[e.RowIndex].DataBoundItem;
            if (item == null) return;

            bool isMyData = (item.compidx == PUB.user.CompanyIdx);

            // Row background color
            if (!isMyData)
            {
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray;
            }
            else
            {
                // Date check for yellow highlight
                if (!string.IsNullOrEmpty(item.Date))
                {
                    try
                    {
                        DateTime saveDate = DateTime.ParseExact(item.Date, "yyyy-MM-dd HH:mm:ss",
                            System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
                        DateTime targetDate = DateTime.Today.AddDays(-14);

                        if (DateTime.Compare(saveDate, targetDate) >= 0)
                            dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
                        else
                            dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
                    }
                    catch { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White; }
                }
            }

            // Grade color
            dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = SetGradeColor(item.DisplayGrade, isMyData);
        }


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

            switch (Grade)
            {
                case "A":
                    return Color.Blue;
                case "B":
                    return Color.Black;
                case "C":
                    return Color.Gray;
                case "D":
                    return Color.Red;

                default:
                    return Color.Black;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            String_Text st = new String_Text();
            int row = e.RowIndex;

            if (row < 0) return;

            view_Marc(row);

            st.Color_change("▼", richTextBox1);
            st.Color_change("▲", richTextBox1);
        }

        void view_Marc(int row)
        {
            this.rtEtc1.Text = string.Empty;
            this.rtEtc2.Text = string.Empty;

            var item = (MarcCopyItem)dataGridView1.Rows[row].DataBoundItem;
            if (item == null || string.IsNullOrEmpty(item.Marc)) return;

            rtEtc1.Text = item.remark1;
            rtEtc2.Text = item.remark2;

            string Marc_data = item.Marc;

            if (Marc_data.Length < 3) return;

            string result = string.Empty;

            List<string> TagNum = new List<string>();   // 태그번호
            List<string> field = new List<string>();    // 가변길이필드 저장

            // 특수기호 육안으로 확인하기 쉽게 변환
            Marc_data = Marc_data.Replace("", "▼");
            Marc_data = Marc_data.Replace("", "▲");
            Marc_data = Marc_data.Replace("￦", "\\");

            int startidx = 0;
            string[] data = Marc_data.Substring(24).Split('▲'); // 리더부를 제외한 디렉터리, 가변길이필드 저장

            // List에 필요한 데이터 집어넣는 작업.
            for (int a = 1; a < data.Length - 1; a++)
            {
                TagNum.Add(data[0].Substring(startidx, 3));
                startidx += 12;
                field.Add(data[a] + "▲");
            }

            // List에 들어간 데이터를 메모장에 출력시키는 작업.
            for (int a = 0; a < TagNum.Count; a++)
            {
                string res = TagNum[a];
                if (field[a].IndexOf("▼") == -1)
                {
                    res += "\t  \t" + field[a];
                }
                else
                {
                    string temp = field[a].Insert(2, "\t");
                    res += "\t" + temp;
                }
                result += res + "\n";
            }
            richTextBox1.Text = result;
            return;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            SelectMarc(e.RowIndex);
        }
     
        void SelectMarc(int row)
        {
            var item = (MarcCopyItem)dataGridView1.Rows[row].DataBoundItem;
            if (item == null) return;

            SelectedItem = item;
            this.DialogResult = DialogResult.OK;
        }

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

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            int row = dataGridView1.CurrentRow.Index;
            if (row < 0) return;

            var item = (MarcCopyItem)dataGridView1.Rows[row].DataBoundItem;
            if (item == null) return;

            var idx = item.idx;
            string compidx = item.compidx;

            if (compidx != PUB.user.CompanyIdx)
            {
                UTIL.MsgE("해당 마크를 삭제할 권한이 없습니다.");
                return;
            }

            if (UTIL.MsgQ($"삭제하시겠습니까?\nIDX:{item.idx}") == DialogResult.Cancel)
                return;

            string User = PUB.user.UserName;
            string NowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string SelectArea = "`compidx`, `grade`, `ISBN`, `서명`, `총서명`, " +
                                "`저자`, `출판사`, `출판년월`, `가격`, `008tag`, " +
                                "`division`, `user`, `비고1`, `비고2`, `url`, " +
                                "`marc`, `marc_chk`, `marc1`, `marc_chk1`, `marc2`, `marc_chk2`";

            string SelectCMD = string.Format("SELECT {0} FROM {1} WHERE `idx` = {2};", SelectArea, "Marc", idx);
            string SelectRes = db.self_Made_Cmd(SelectCMD);
            string[] SelectAry = SelectRes.Split('|');

            string[] InsertCol = {
                "compidx", "grade", "ISBN", "서명", "총서명",
                "저자", "출판사", "출판년월", "가격", "008tag",
                "division", "user", "비고1", "비고2", "url",
                "date", "user_Del", "marc"
            };

            string[] InsertData = {
                SelectAry[0], SelectAry[1], SelectAry[2], SelectAry[3], SelectAry[4],
                SelectAry[5], SelectAry[6], SelectAry[7], SelectAry[8], SelectAry[9],
                SelectAry[10], SelectAry[11], SelectAry[12], SelectAry[13], SelectAry[14],
                NowDate, User, item.Marc
            };

            string InsertCmd = db.DB_INSERT("Marc_Del", InsertCol, InsertData);
            Helper_DB.ExcuteNonQuery(InsertCmd);

            string DeleteCmd = string.Format("DELETE FROM `Marc` WHERE `idx` = {0};", idx);
            Helper_DB.ExcuteNonQuery(DeleteCmd);

            _list.RemoveAt(_list.IndexOf(item));
        }

        private void btn_ShowDeleteMarc_Click(object sender, EventArgs e)
        {
            ShowDeleteMarc showDeleteMarc = new ShowDeleteMarc();
            showDeleteMarc.Show();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (dataGridView1.CurrentRow == null) return;
                int row = dataGridView1.CurrentRow.Index;
                if (row < 0) return;

                SelectMarc(row);
            }
        }
    }
}
