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;

namespace UniMarc
{
    public partial class Search_Infor : Form
    {
        Main main;
        //Helper_DB db = new Helper_DB();
        public string compidx;
        public Search_Infor(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }
        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)
        {
            dataGridView1.Rows.Clear();

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

                Helper_DB db = new Helper_DB();
                db.DBcon();

                //(string target, string searchText) = setting_target(true);
                //string WhereQuery = MakeWHEREQurey(target, searchText);

                string Area =
                    "`idx`, `grade`, `user`, `date`, `isbn`, `서명`, "
                  + "`총서명`, `저자`, `출판사`, `가격`, `출판년월`, "
                  + "`marc`,`marc1`, `비고1`, `비고2`";
                string cmd = string.Format("SELECT {0} FROM `{1}` WHERE `compidx` = \"{3}\" {2};", Area, Table, tQuery, compidx);
                db.DB_Send_CMD_Search_ApplyGrid(cmd, dataGridView1);
                // string db_res = db.DB_Send_CMD_Search(cmd);
                // string[] tmp_arr = db_res.Split('|');
                // inputGrid_MyDB(tmp_arr);

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

                //(string target, string searchText) = setting_target(false);
                //string WhereQuery = MakeWHEREQurey(target, searchText);

                string cmd = string.Format("SELECT {0} FROM `{1}` WHERE {2};", Area, Table, tQuery);
                string db_res = db.DB_Send_CMD_Search(cmd);
                string[] tmp_arr = db_res.Split('|');
                inputGrid_ClDB(tmp_arr);
            }

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

        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>
        void inputGrid_MyDB(string[] arr)
        {
            string[] grid = {
                "", "", "", "", "",
                "", "", "", "", "",
                "", "", "", ""
            };

            for (int a = 0; a < arr.Length; a++)
            {
                int index = a % 19;
                if (index == 0) grid[0] = arr[a];                  // idx
                if (index == 1) grid[1] = Change_Grade(arr[a]);    // 등급
                if (index == 2) grid[2] = arr[a];                  // 작성자
                if (index == 3) grid[3] = arr[a];                  // 마지막 저장시각
                if (index == 4) grid[4] = arr[a];                  // isbn
                if (index == 5) grid[5] = arr[a];                  // 도서명
                if (index == 6) grid[6] = arr[a];                  // 총서명
                if (index == 7) grid[7] = arr[a];                  // 저자
                if (index == 8) grid[8] = arr[a];                  // 출판사
                if (index == 9) grid[9] = arr[a];                  // 가격
                if (index == 10) grid[10] = arr[a];                // 출판년월
                if (index == 12 || index == 14 || index == 16)
                {   // *마크*
                    bool CheckMarc = MyDB_Sub(arr[a]);
                    if (!CheckMarc) grid[11] = arr[a - 1];
                }
                if (index == 17) grid[12] = arr[a];                // 비고1
                if (index == 18)
                {                                 // 비고2
                    grid[13] = arr[a];
                    dataGridView1.Rows.Add(grid);
                }
            }
        }
        bool MyDB_Sub(string chk)
        {
            if (chk == "1")
                return true;
            else
                return false;
        }

        void inputGrid_ClDB(string[] arr)
        {
            string[] grid = {
                "", "", "", "", "",
                "", "", "", "", "",
                "", "", "", ""
            };

            for (int a = 0; a < arr.Length; a++)
            {
                if (a % 11 == 0) grid[0] = arr[a];                   // idx
                if (a % 11 == 1) grid[1] = Change_Grade(arr[a]);     // grade
                if (a % 11 == 2) grid[4] = arr[a];                   // isbn
                if (a % 11 == 3) grid[5] = arr[a];                   // book_name
                if (a % 11 == 4) grid[6] = arr[a];                   // series
                if (a % 11 == 5) grid[7] = arr[a];                   // author
                if (a % 11 == 6) grid[8] = arr[a];                   // book_comp
                if (a % 11 == 7) grid[9] = arr[a];                   // price
                if (a % 11 == 8) grid[10] = arr[a];                  // years
                if (a % 11 == 9) grid[11] = arr[a];                  // marc
                if (a % 11 == 10)                                    // etc
                {
                    grid[12] = arr[a];
                    dataGridView1.Rows.Add(grid);
                }
            }
        }

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

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (row < 0) return;
            string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();

            if (row < 0)
                return;


            var me = new Marc_Plan_Sub_MarcEdit(this);
            string[] Marc = {
                dataGridView1.Rows[row].Cells["Marc"].Value.ToString(),
                idx,
                "",
                "",
                dataGridView1.Rows[row].Cells["ISBN"].Value.ToString()
            };

            me.row = row;
            me.UserName = main.botUserLabel.Text;
            me.Init(Marc);
            me.btn_EditNum.Enabled = 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;
            string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();

            if (row < 0)
                return;
            if (dataGridView1.Rows[row].Cells["marc2"].Value.ToString() == "")
            {
                UTIL.MsgE("이전에 저장된 MARC 데이터가 없습니다.");
                return;
            }
            Marc_Plan_Sub_MarcEdit me = new Marc_Plan_Sub_MarcEdit(this);
            string[] Marc = {
                dataGridView1.Rows[row].Cells["marc2"].Value.ToString(),
                idx,
                "",
                "",
                dataGridView1.Rows[row].Cells["ISBN"].Value.ToString()
            };

            me.row = row;
            me.UserName = main.botUserLabel.Text;
            me.Init(Marc, true);
            me.btn_EditNum.Enabled = false;
            me.Show();
        }
    }
}
