using AR;
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;

namespace UniMarc
{
    public partial class Search_Infor2 : Form
    {
        Main main;
        public string compidx;
        SortableBindingList<SearchInforItem> searchList = new SortableBindingList<SearchInforItem>();

        public Search_Infor2(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;

            dataGridView1.AutoGenerateColumns = false;
            bs1.DataSource = searchList;
            dataGridView1.DataSource = bs1;
        }
        private void Search_Infor_Load(object sender, EventArgs e)
        {
            //db.DBcon();

            string[] area = { "자체 DB", "국립 중앙 도서관" };
            cb_data_area.Items.AddRange(area);
            cb_data_area.SelectedIndex = 0;

            dataGridView1.Columns["etc1"].ReadOnly = true;
            dataGridView1.Columns["etc2"].ReadOnly = true;
        }
        private void btn_search_Click(object sender, EventArgs e)
        {
            searchList.Clear();

            string Table = "Marc";
            string tQuery = MakeWHEREQurey();
            if (cb_data_area.SelectedIndex == 0)
            {
                Helper_DB db = new Helper_DB();
                db.DBcon();

                string Area =
                    "`idx`, `grade`, `user`, `date`, `isbn`, `서명` AS `book_name`, "
                  + "`총서명` AS `series`, `저자` AS `author`, `출판사` AS `book_comp`, `가격` AS `price`, `출판년월` AS `years`, "
                  + "`marc`, `marc1` AS `marc2`, `비고1` AS `etc1`, `비고2` AS `etc2` ";
                string cmd = string.Format("SELECT {0} FROM `{1}` WHERE `compidx` = \"{3}\" {2};", Area, Table, tQuery, compidx);

                System.Data.DataTable dt = db.DB_Send_CMD_Search_DataTable(cmd);
                PopulateSearchList(dt, 19);
            }
            else if (cb_data_area.SelectedIndex == 1)
            {
                Helper_DB db = new Helper_DB();
                db.DBcon_cl();
                // -user date 비고2
                string Area = "`idx`, `grade`, `isbn`, `book_name`, `series`, `author`, "
                            + "`book_comp`, `price`, `years`, `marc`, `etc` AS `etc1` ";

                string cmd = string.Format("SELECT {0} FROM `{1}` WHERE {2};", Area, Table, tQuery);
                System.Data.DataTable dt = db.DB_Send_CMD_Search_DataTable(cmd);
                PopulateSearchList(dt, 11);
            }

            label3.Text = string.Format("검색결과 {0:0,0}건", searchList.Count.ToString());
        }

        void PopulateSearchList(DataTable dt, int colCount)
        {
            if (dt == null || dt.Rows.Count == 0) return;

            foreach (DataRow row in dt.Rows)
            {
                SearchInforItem item = new SearchInforItem();
                if (colCount == 19) // MyDB
                {
                    item.idx = row["idx"].ToString();
                    item.grade = Change_Grade(row["grade"].ToString());
                    item.User = row["user"].ToString();
                    item.date = row["date"].ToString();
                    item.ISBN = row["isbn"].ToString();
                    item.book_name = row["book_name"].ToString();
                    item.sBookName = row["series"].ToString();
                    item.author = row["author"].ToString();
                    item.book_comp = row["book_comp"].ToString();
                    item.price = row["price"].ToString();
                    item.pub_date = row["years"].ToString();
                    item.Marc = row["marc"].ToString();
                    item.marc2 = row["marc2"].ToString();
                    item.etc1 = row["etc1"].ToString();
                    item.etc2 = row["etc2"].ToString();
                }
                else if (colCount == 11) // ClDB
                {
                    item.idx = row["idx"].ToString();
                    item.grade = Change_Grade(row["grade"].ToString());
                    item.ISBN = row["isbn"].ToString();
                    item.book_name = row["book_name"].ToString();
                    item.sBookName = row["series"].ToString();
                    item.author = row["author"].ToString();
                    item.book_comp = row["book_comp"].ToString();
                    item.price = row["price"].ToString();
                    item.pub_date = row["years"].ToString();
                    item.Marc = row["marc"].ToString();
                    item.etc1 = row["etc1"].ToString();
                }
                searchList.Add(item);
            }
        }
        #region search_Click_Sub

        string MakeWHEREQurey(string target, string searchText)
        {
            string Where;
            if (target == "date")
            {
                string start = dtp_Start.Text;
                string end = dtp_End.Text;
                Where = string.Format("AND `{0}` BETWEEN \"{1}\" AND \"{2}\"", target, start, end);
            }
            else if (target == "" && cb_data_area.SelectedIndex == 0)
            {
                string start = DateTime.Now.ToString("yyyy-01-01");
                string end = DateTime.Now.ToString("yyyy-12-31");
                Where = string.Format("AND `{0}` BETWEEN \"{1}\" AND \"{2}\"", "date", start, end);
            }
            else if (target == "" && cb_data_area.SelectedIndex == 1)
            {
                Where = "";
            }
            else
            {
                Where = string.Format("AND `{0}` LIKE \"%{1}%\"", target, searchText, compidx);
                if (cb_data_area.SelectedIndex == 1)
                    Where = "WHERE" + Where.Substring(3);
            }
            return Where;
        }
        string MakeWHEREQurey()
        {
            string tWhere = string.Empty;
            string tText = string.Empty;
            string[] tTextBox = new string[] { tbTitle.Text, tbWriter.Text, tbPublisher.Text, tbISBN.Text, Change_Grade(cbGrade.Text), cbUser.Text };
            string[] tTitle_IDX_0 = new string[] { "서명", "저자", "출판사", "isbn", "grade", "user", "date" };
            string[] tTitle_IDX_1 = new string[] { "book_name", "author", "book_comp", "isbn", "grade" };
            if (cb_data_area.SelectedIndex == 0)
            {
                for (int i = 0; i < tTitle_IDX_0.Length; i++)
                {
                    if (tTextBox.Length > i && tTextBox[i] != "")
                    {
                        if (i < 4)
                        {
                            tText = string.Format("AND `{0}` LIKE \"%{1}%\"", tTitle_IDX_0[i], tTextBox[i]);
                            tWhere += tText;
                        }
                        else
                        {
                            if (tTextBox[i] != "전체")
                            {
                                tText = string.Format("AND `{0}` LIKE \"%{1}%\"", tTitle_IDX_0[i], tTextBox[i]);
                                tWhere += tText;
                            }
                        }
                    }
                    else if (i == tTitle_IDX_0.Length - 1 && CkDateTime.Checked && DtpStartTime.Value <= DtpEndTime.Value)
                    {
                        string start = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DtpStartTime.Value);

                        string end = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DtpEndTime.Value);
                        tWhere += string.Format("AND `date` BETWEEN \"{0}\" AND \"{1}\"", start, end);
                    }
                }
            }
            else
            {
                for (int i = 0; i < tTitle_IDX_1.Length; i++)
                {
                    if (tTextBox.Length > i && tTextBox[i] != "")
                    {

                        if (i < 4)
                        {
                            tText = string.Format("AND `{0}` LIKE \"%{1}%\"", tTitle_IDX_1[i], tTextBox[i]);
                            if (tWhere == "") tText = string.Format("`{0}` LIKE \"%{1}%\"", tTitle_IDX_1[i], tTextBox[i]);
                            tWhere += tText;
                        }
                        else
                        {
                            if (tTextBox[i] != "전체")
                            {
                                tText = string.Format("AND `{0}` LIKE \"%{1}%\"", tTitle_IDX_1[i], tTextBox[i]);
                                if (tWhere == "") tText = string.Format("`{0}` LIKE \"%{1}%\"", tTitle_IDX_1[i], tTextBox[i]);
                                tWhere += tText;
                            }
                        }
                    }
                }
            }

            return tWhere;
        }
        /// <summary>
        /// 검색결과에 따라 Grid를 새로 그림
        /// </summary>
        /// <param name="arr"></param>
        bool MyDB_Sub(string chk)
        {
            if (chk == "1")
                return true;
            else
                return false;
        }


        /// <summary>
        /// idx값에 따라 Grade를 보기 쉽게 바꿔줌.
        /// </summary>
        /// <param name="idx">DB에서 가져온 마크등급</param>
        /// <returns></returns>
        string Change_Grade(string idx)
        {
            string result = string.Empty;
            switch (idx)
            {
                case "0":
                    result = "A";
                    break;
                case "1":
                    result = "B";
                    break;
                case "2":
                    result = "C";
                    break;
                case "3":
                    result = "D";
                    break;

                case "D":
                    result = "3";
                    break;
                case "C":
                    result = "2";
                    break;
                case "B":
                    result = "1";
                    break;
                case "A":
                    result = "0";
                    break;
            }
            return result;
        }
        /// <summary>
        /// 검색 필터에 따라 target이 변경됨
        /// </summary>
        /// <returns></returns>
        (string, string) setting_target(bool isMyDB)
        {
            string res = "";
            string search = "";
            if (isMyDB)
            {
                switch (cb_filter.SelectedIndex)
                {
                    case 1:
                        res = "서명";
                        search = tb_search.Text;
                        break;
                    case 2:
                        res = "저자";
                        search = tb_search.Text;
                        break;
                    case 3:
                        res = "출판사";
                        search = tb_search.Text;
                        break;
                    case 4:
                        res = "isbn";
                        search = tb_search.Text;
                        break;
                    case 5:
                        res = "grade";
                        search = Change_Grade(cb_filterDetail.Text);
                        break;
                    case 6:
                        res = "user";
                        search = cb_filterDetail.Text;
                        break;
                    case 7:
                        res = "date";
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (cb_filter.SelectedIndex)
                {
                    case 1:
                        res = "book_name";
                        search = tb_search.Text;
                        break;
                    case 2:
                        res = "author";
                        search = tb_search.Text;
                        break;
                    case 3:
                        res = "book_comp";
                        search = tb_search.Text;
                        break;
                    case 4:
                        res = "isbn";
                        search = tb_search.Text;
                        break;
                    case 5:
                        res = "grade";
                        search = Change_Grade(cb_filterDetail.Text);
                        break;
                    default:
                        break;
                }
            }
            return (res, search);
        }

        #endregion
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //에디트 창을 연다
            if (e.RowIndex < 0) return;

            SearchInforItem item = (SearchInforItem)bs1[e.RowIndex];
            if (item == null) return;

            var v_grade = 2;
            if (item.grade == "A") v_grade = 0;
            else if (item.grade == "B") v_grade = 1;
            else if (item.grade == "C") v_grade = 2;
            else if (item.grade == "D") v_grade = 3;

            //int.TryParse(item.grade, out v_grade);

            var me = new fMarc_Editor(item.ISBN, item.Marc, SaveTarget.MasterMarc, item.etc1, item.etc2, v_grade);
            me.row = e.RowIndex;

            // Helper to load data at specific binding source position
            Action<int> loadAt = (pos) =>
            {
                if (pos < 0 || pos >= bs1.Count) return;
                bs1.Position = pos;
                var currentItem = (SearchInforItem)bs1.Current;
                me.LoadBook(currentItem.Marc, new MacEditorParameter
                {
                    Author = currentItem.author,
                    BookName = currentItem.book_name,
                    ISBN13 = currentItem.ISBN,
                    MarcIdx = int.TryParse(currentItem.idx, out int midx) ? midx : 0,
                    User = currentItem.User,
                    SaveDate = currentItem.date,
                    Publisher = currentItem.book_comp,
                    Price = int.TryParse(currentItem.price, out int pr) ? pr : 0,
                    text008 = "",
                    tag056 = "",
                    NewMake = false,
                    OriginalMarc = currentItem.Marc
                });
            };

            loadAt(e.RowIndex);

            me.RequestNext += (s, args) =>
            {
                if (bs1.Position < bs1.Count - 1)
                {
                    loadAt(bs1.Position + 1);
                }
            };
            me.RequestPrev += (s, args) =>
            {
                if (bs1.Position > 0)
                {
                    loadAt(bs1.Position - 1);
                }
            };
            me.BookUpdated += (s, args) =>
            {
                var currentItem = (SearchInforItem)bs1.Current;
                currentItem.book_name = args.BookName;

                //원본마크값을 marc2에 저장한다.
                if (string.IsNullOrEmpty(currentItem.marc2)) currentItem.marc2 = currentItem.Marc;
                currentItem.Marc = args.Marc;
                currentItem.ISBN = args.ISBN;
                currentItem.author = args.Author;
                currentItem.book_comp = args.Publisher;
                currentItem.price = args.Price;
                currentItem.grade = Change_Grade(args.Grade);
                currentItem.etc1 = args.Etc1;
                currentItem.etc2 = args.Etc2;
                currentItem.date = args.SaveDate;
                currentItem.User = args.User;
                bs1.ResetCurrentItem();
            };

            me.RequestFillBlankData += (s, args) =>
            {
                var dataList = new List<FillBlankItem>();
                var currentBoundItem = (SearchInforItem)bs1.Current;

                for (int a = 0; a < bs1.Count; a++)
                {
                    var mItem = (SearchInforItem)bs1.List[a];
                    string mData = mItem.Marc ?? "";
                    if (mData.Length < 10)
                    {
                        var itemfb = new FillBlankItem
                        {
                            Idx = a,
                            Isbn = mItem.ISBN ?? "",
                            BookName = mItem.book_name ?? "",
                            Author = mItem.author ?? "",
                            Publisher = mItem.book_comp ?? "",
                            Price = int.TryParse(mItem.price, out int prfb) ? prfb : 0
                        };
                        dataList.Add(itemfb);
                    }
                }
                if (dataList.Any() == false)
                {
                    // UTIL.MsgE("비마크 데이터가 존재하지 않아 기능을 사용할 수 없습니다");
                    UTIL.MsgE("비마크 데이터가 존재하지 않아 기능을 사용할 수 없습니다");
                }
                else me.OpenFillBlank(dataList, currentBoundItem.ISBN);
            };

            me.BulkBooksUpdated += (s, args) =>
            {
                foreach (var fbItem in args.Updates)
                {
                    if (string.IsNullOrEmpty(fbItem.BookMarc)) continue;

                    int rowIdx = fbItem.Idx;
                    if (rowIdx >= 0 && rowIdx < bs1.Count)
                    {
                        var mItem = (SearchInforItem)bs1.List[rowIdx];
                        if (string.IsNullOrEmpty(mItem.marc2)) mItem.marc2 = mItem.Marc;
                        mItem.Marc = fbItem.BookMarc;
                    }
                }
                bs1.ResetBindings(false);
            };

            me.Show();

            // Search_Infor_Sub sis = new Search_Infor_Sub(this);
            // sis.isbn = dataGridView1.Rows[row].Cells["ISBN"].Value.ToString();
            // sis.marc = dataGridView1.Rows[row].Cells["Marc"].Value.ToString();
            // sis.Show();
        }
        private void tb_search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { btn_search_Click(null, null); }
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cb_data_area_SelectedIndexChanged(object sender, EventArgs e)
        {

            cb_filter.Items.Clear();
            List<string> filter = new List<string>
            {
                "전체", "도서명", "저자", "출판사", "ISBN", "등급"
            };

            if (cb_data_area.SelectedIndex == 0)
            {
                Helper_DB db = new Helper_DB();
                db.DBcon();
                filter.Add("작성자");
                filter.Add("날짜");

                cbUser.Items.Clear();
                cbUser.Items.Add("전체");
                string compName = main.lbCompanyName.Text;
                string cmd = string.Format("SELECT `name` FROM `User_Data` WHERE `affil` = \"{0}\"", compName);
                string res = db.self_Made_Cmd(cmd);
                List<string> Aryres = res.Split('|').ToList();
                Aryres.RemoveAll(x => x == "");
                cbUser.Items.AddRange(Aryres.ToArray());
                //foreach (string PName in Aryres)
                //{
                //    if (PName == "")
                //        continue;
                //    cbUser.Items.Add(PName);
                //}
                cbUser.SelectedIndex = 0;
                DtpStartTime.Enabled = true;
                DtpEndTime.Enabled = true;
                cbUser.Enabled = true;

            }
            else
            {
                Helper_DB db = new Helper_DB();
                db.DBcon_cl();
                cbUser.Items.Clear();
                cbUser.Items.Add("전체");
                cbUser.SelectedIndex = 0;
                DtpStartTime.Enabled = false;
                DtpEndTime.Enabled = false;
                cbUser.Enabled = false;
            }
            cbGrade.SelectedIndex = 0;


            string[] filterAry = filter.ToArray();
            cb_filter.Items.AddRange(filterAry);
            cb_filter.SelectedIndex = 0;
        }

        private void cb_filter_SelectedIndexChanged(object sender, EventArgs e)
        {
            Helper_DB db = new Helper_DB();
            cb_filterDetail.Items.Clear();
            cb_filterDetail.Enabled = true;

            if (cb_filter.SelectedItem.ToString() == "등급")
            {
                string[] grade = { "A", "B", "C", "D" };
                cb_filterDetail.Items.AddRange(grade);
                cb_filterDetail.SelectedIndex = 0;
            }
            else if (cb_filter.SelectedItem.ToString() == "작성자")
            {
                cb_filterDetail.Items.Add("전체");
                string compName = main.lbCompanyName.Text;
                string cmd = string.Format("SELECT `name` FROM `User_Data` WHERE `affil` = \"{0}\"", compName);
                string res = db.self_Made_Cmd(cmd);
                string[] Aryres = res.Split('|');

                foreach (string PName in Aryres)
                {
                    if (PName == "")
                        continue;
                    cb_filterDetail.Items.Add(PName);
                }
                cb_filterDetail.SelectedIndex = 0;
            }
            else if (cb_filter.SelectedItem.ToString() == "날짜")
            {
                dtp_Start.Enabled = true;
                dtp_End.Enabled = true;
            }
            else
            {
                dtp_Start.Enabled = false;
                dtp_End.Enabled = false;
                cb_filterDetail.Enabled = false;
            }
        }

        private void btnViewOldData_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell == null) return;
            int row = dataGridView1.CurrentCell.RowIndex;
            if (row < 0) return;

            SearchInforItem item = (SearchInforItem)bs1[row];
            if (item == null) return;

            if (string.IsNullOrEmpty(item.marc2))
            {
                UTIL.MsgE("이전에 저장된 MARC 데이터가 없습니다.");
                return;
            }

            var v_grade = 2;
            int.TryParse(item.grade, out v_grade);
            var me = new fMarc_Editor(item.ISBN, item.marc2, SaveTarget.MasterMarc, item.etc1, item.etc2, v_grade);
            me.row = row;

            // Helper to load data at specific binding source position (using marc2 for old data)
            Action<int> loadAt = (pos) =>
            {
                if (pos < 0 || pos >= bs1.Count) return;
                bs1.Position = pos;
                var currentItem = (SearchInforItem)bs1.Current;
                me.LoadBook(currentItem.marc2, new MacEditorParameter
                {
                    Author = currentItem.author,
                    BookName = currentItem.book_name,
                    ISBN13 = currentItem.ISBN,
                    MarcIdx = int.TryParse(currentItem.idx, out int midx) ? midx : 0,
                    User = currentItem.User,
                    SaveDate = currentItem.date,
                    Publisher = currentItem.book_comp,
                    Price = int.TryParse(currentItem.price, out int pr) ? pr : 0,
                    text008 = "",
                    tag056 = "",
                    NewMake = false,
                    OriginalMarc = currentItem.marc2
                });
            };

            loadAt(row);

            me.RequestNext += (s, args) =>
            {
                if (bs1.Position < bs1.Count - 1)
                {
                    loadAt(bs1.Position + 1);
                }
            };
            me.RequestPrev += (s, args) =>
            {
                if (bs1.Position > 0)
                {
                    loadAt(bs1.Position - 1);
                }
            };
            me.BookUpdated += (s, args) =>
            {
                var currentItem = (SearchInforItem)bs1.Current;
                currentItem.book_name = args.BookName;
                currentItem.Marc = args.Marc;   //이전데이터보기에서 저장했다면 실제마크데이터를 업데이트한다.
                currentItem.ISBN = args.ISBN;
                currentItem.author = args.Author;
                currentItem.book_comp = args.Publisher;
                currentItem.price = args.Price;
                currentItem.grade = Change_Grade(args.Grade);
                currentItem.etc1 = args.Etc1;
                currentItem.etc2 = args.Etc2;
                currentItem.date = args.SaveDate;
                currentItem.User = args.User;
                bs1.ResetCurrentItem();
            };

            me.RequestFillBlankData += (s, args) =>
            {
                var dataList = new List<FillBlankItem>();
                var currentBoundItem = (SearchInforItem)bs1.Current;

                for (int a = 0; a < bs1.Count; a++)
                {
                    var mItem = (SearchInforItem)bs1.List[a];
                    string mData = mItem.marc2 ?? "";
                    if (mData.Length < 10)
                    {
                        var itemfb = new FillBlankItem
                        {
                            Idx = a,
                            Isbn = mItem.ISBN ?? "",
                            BookName = mItem.book_name ?? "",
                            Author = mItem.author ?? "",
                            Publisher = mItem.book_comp ?? "",
                            Price = int.TryParse(mItem.price, out int prfb) ? prfb : 0
                        };
                        dataList.Add(itemfb);
                    }
                }
                if (dataList.Any() == false)
                {
                    // UTIL.MsgE("비마크 데이터가 존재하지 않아 기능을 사용할 수 없습니다");
                    UTIL.MsgE("비마크 데이터가 존재하지 않아 기능을 사용할 수 없습니다");
                }
                else me.OpenFillBlank(dataList, currentBoundItem.ISBN);
            };

            me.BulkBooksUpdated += (s, args) =>
            {
                foreach (var fbItem in args.Updates)
                {
                    if (string.IsNullOrEmpty(fbItem.BookMarc)) continue;

                    int rowIdx = fbItem.Idx;
                    if (rowIdx >= 0 && rowIdx < bs1.Count)
                    {
                        var mItem = (SearchInforItem)bs1.List[rowIdx];
                        mItem.marc2 = fbItem.BookMarc;
                    }
                }
                bs1.ResetBindings(false);
            };

            me.Show();
        }
    }
}
