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 Marc_Plan_Sub_SelectList : Form
    {
        Helper_DB db = new Helper_DB();
        //string compidx;

        public int ResultIdx { get; private set; }
        public string ResultListName { get; private set; }
        public string ResultDate { get; private set; }
        public List<MarcPlanItem> ResultItems { get; private set; }

        public Marc_Plan_Sub_SelectList()
        {
            InitializeComponent();
            //compidx = Properties.Settings.Default.compidx;
        }

        private void Marc_Plan_Sub_SelectList_Load(object sender, EventArgs e)
        {
            db.DBcon();

            string[] gu = { "진행", "완료" };
            cb_gu.Items.AddRange(gu);
            cb_gu.SelectedIndex = 0;

            dataGridView1.Columns["list_name"].ReadOnly = true;
            dataGridView1.Columns["date"].ReadOnly = true;
            dataGridView1.Columns["user"].ReadOnly = true;

            // btn_Search_Click(null, e);
        }

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

        private void tb_Search_Enter(object sender, EventArgs e)
        {
            ((TextBox)sender).BackColor = Color.Khaki;
        }

        private void tb_Search_Leave(object sender, EventArgs e)
        {
            ((TextBox)sender).BackColor = Color.White;
        }

        public void btn_Search_Click(object sender, EventArgs e)
        {
            // dataGridView1.Rows.Clear();

            string gu = cb_gu.Text;         // 검색 필터
            string text = tb_Search.Text;   // 검색어 DB LIKE 검색
            string Area = "`idx`, `work_list`, `date`, `user`";

            string cmd = string.Format("SELECT {0} FROM `Specs_List` WHERE `compidx` = {1} AND `state` = \"{2}\" AND `work_list` LIKE \"%{3}%\"",
                Area, PUB.user.CompanyIdx, gu, text);

            string res = db.DB_Send_CMD_Search(cmd);
            string[] ary = res.Split('|');
            Input_Grid(ary);
        }
        #region Search_Sub
        private void Input_Grid(string[] ary)
        {
            List<MarcPlanItem> dataList = new List<MarcPlanItem>();
            string[] grid = { "", "", "", "", "F" };
            for (int a = 0; a < ary.Length; a++)
            {
                if (a % 4 == 0) grid[0] = ary[a];
                if (a % 4 == 1) grid[1] = ary[a];
                if (a % 4 == 2) grid[2] = ary[a];
                if (a % 4 == 3)
                {
                    grid[3] = ary[a];

                    MarcPlanItem item = new MarcPlanItem
                    {
                        Idx = int.Parse(grid[0]),
                        ListName = grid[1],
                        Date = grid[2],
                        User = grid[3],
                        ColCheck = "F"
                    };
                    dataList.Add(item);
                    //dataGridView1.Rows.Add(grid);
                }
            }
            bs1.DataSource = dataList;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = bs1;
        }
        #endregion

        private void Change_State(object sender, EventArgs e)     // 완료, 진행처리
        {
            string name = ((Button)sender).Text;
            int[] CheckRow = CheckIndex();

            if (CheckRow.Length != 1)
            {
                UTIL.MsgE("처리할 목록 [1]개 선택하여 주세요.");
                return;
            }

            int row = CheckRow[0];

            string msg = string.Format("【{0}】을(를) {1} 하시겠습니까?", dataGridView1.Rows[row].Cells["list_name"].Value.ToString(), name);
            if (UTIL.MsgQ(msg) == DialogResult.Cancel)
                return;

            string[] search_col = { "idx", "work_list", "date" };
            string[] update_col = { "state" };
            string[] search_data = {
                dataGridView1.Rows[row].Cells["idx"].Value.ToString(),
                dataGridView1.Rows[row].Cells["list_name"].Value.ToString(),
                dataGridView1.Rows[row].Cells["date"].Value.ToString() };
            string[] update_data = { "" };

            if (name == "완료처리")
                update_data[0] = "완료";
            else
                update_data[0] = "진행";

            string cmd = db.More_Update("Specs_List", update_col, update_data, search_col, search_data);
            Helper_DB.ExcuteNonQuery(cmd);

            btn_Search_Click(null, e);
        }

        private void btn_Edit_Click(object sender, EventArgs e)         // 편집 (V 확인필요)
        {
            int[] CheckRow = CheckIndex();

            if (CheckRow.Length != 1)
            {
                UTIL.MsgE("수정할 목록 [1]개 선택하여 주세요.");
                return;
            }

            int row = CheckRow[0];

            Marc_Plan_Sub_SelectList_Edit edit = new Marc_Plan_Sub_SelectList_Edit(this);
            edit.TopMost = true;
            edit.Show();
            edit.BaseSetting(dataGridView1.Rows[row].Cells["idx"].Value.ToString());
            edit.TextBoxSetting(dataGridView1.Rows[row].Cells["list_name"].Value.ToString());
        }

        private void btn_Morge_Click(object sender, EventArgs e)       // 병합 (V 확인필요)
        {
            int[] CheckRow = CheckIndex();

            if (CheckRow.Length < 2)
            {
                UTIL.MsgE("병합할 목록 [2]개이상 선택하여 주세요.");
                return;
            }

            List<string> ListIndex = new List<string>();
            List<string> ListName = new List<string>();
            List<string> ListDate = new List<string>();
            List<string> ListUser = new List<string>();

            foreach (int row in CheckRow)
            {
                ListIndex.Add(dataGridView1.Rows[row].Cells["idx"].Value.ToString());
                ListName.Add(dataGridView1.Rows[row].Cells["list_name"].Value.ToString());
                ListDate.Add(dataGridView1.Rows[row].Cells["date"].Value.ToString());
                ListUser.Add(dataGridView1.Rows[row].Cells["user"].Value.ToString());
            }

            Marc_Plan_Sub_SelectList_Morge morge = new Marc_Plan_Sub_SelectList_Morge(this);
            morge.Init(ListIndex, ListName, ListDate, ListUser);
            morge.TopMost = true;
            morge.Show(this);
        }

        private void btn_Delete_Click(object sender, EventArgs e)       // 삭제 (V 확인필요)
        {
            int[] CheckRow = CheckIndex();

            if (CheckRow.Length != 1)
            {
                UTIL.MsgE("삭제할 목록 [1]개 선택하여 주세요.");
                return;
            }

            int row = CheckRow[0];
            string msg = string.Format("【{0}】을(를) 삭제하시겠습니까?", dataGridView1.Rows[row].Cells["list_name"].Value.ToString());

            if (UTIL.MsgQ(msg) == DialogResult.No)
                return;

            string idx = dataGridView1.Rows[row].Cells["idx"].Value.ToString();
            string[] search_col = { "work_list", "date" };
            string[] search_data = { dataGridView1.Rows[row].Cells["list_name"].Value.ToString(),
                                     dataGridView1.Rows[row].Cells["date"].Value.ToString() };

            // 목록 제거
            string cmd = db.DB_Delete_More_term("Specs_List", "idx", idx, search_col, search_data);
            Helper_DB.ExcuteNonQuery(cmd);

            // 목록 내 마크 제거
            cmd = db.DB_Delete_No_Limit("Specs_Marc", "compidx", PUB.user.CompanyIdx, search_col, search_data);
            Helper_DB.ExcuteNonQuery(cmd);

            UTIL.MsgI("삭제되었습니다.");
            btn_Search_Click(null, null);
        }

        #region ButtonSub
        /// <summary>
        /// colCheck에 체크가 된 RowIndex값을 가져옴
        /// </summary>
        /// <returns></returns>
        private int[] CheckIndex()
        {
            List<int> CheckRow = new List<int>();
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["colCheck"].Value == null)
                    continue;

                if (dataGridView1.Rows[a].Cells["colCheck"].Value.ToString().IndexOf("T") > -1)
                    CheckRow.Add(a);
            }

            return CheckRow.ToArray();
        }
        #endregion

        private void btn_OpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFileDialog = new OpenFileDialog();
            if (OpenFileDialog.ShowDialog() != DialogResult.OK) return;

            var filePath = OpenFileDialog.FileName;

            try
            {
                var filedata = System.IO.File.ReadAllText(filePath, System.Text.Encoding.Default);
                InputGridByFileData(filedata);
                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                UTIL.MsgE(ex.ToString());
            }
        }

        #region OpenFileSub

        /// <summary>
        /// 파일로부터 목록을 가져온다
        /// </summary>
        /// <param name="text"></param>
        void InputGridByFileData(string text)
        {
            String_Text st = new String_Text();

            string[] grid = text.Split(new char[] { (char)0x1D }, StringSplitOptions.RemoveEmptyEntries);

            var fullparser = new MarcParser();
            var warnmessage = new System.Text.StringBuilder();
            for (int a = 0; a < grid.Length - 1; a++)
            {
                //string[] Search = {
                //// 등록번호, 분류기호, 저자기호, 볼륨v, 복본c, 별치f
                //    "049l", "090a", "090b", "049v", "049c", "049f",
                //// ISBN, 도서명, 총서명1, 총서번호1, 총서명2, 총서번호2, 출판사, 정가, 저자
                //    "020a", "245a", "440a", "440v", "490a", "490v", "260b", "950b", "245d" };

                var fullmarc = grid[a] + (char)0x1D;
                var rlt = fullparser.ParseFullMarc(fullmarc);
                if (rlt.success == false)
                {
                    warnmessage.AppendLine($"[{a + 1}] 번 줄 마크 인식 실패 : {rlt.message}");
                    continue;
                }

                // string[] Search_Res = st.Take_Tag(grid[a], Search);

                //저자기호목록 마지막것을 우선시한다 ("100a", "110a", "111a")
                // string[] Author_Search = { "100a", "110a", "111a" };

                //저자기호확인
                var v_author = string.Empty;
                var v_111a = fullparser.GetTag("111a").FirstOrDefault();
                var v_110a = fullparser.GetTag("110a").FirstOrDefault();
                var v_100a = fullparser.GetTag("100a").FirstOrDefault();

                if (v_111a.isEmpty() == false) v_author = v_111a;
                else if (v_110a.isEmpty() == false) v_author = v_110a;
                else if (v_100a.isEmpty() == false) v_author = v_100a;


                var item = new MarcPlanItem
                {
                    RegNum = fullparser.GetTag("049l").FirstOrDefault(),// Search_Res[0], 등록번호
                    ClassCode = fullparser.GetTag("090a").FirstOrDefault(),//Search_Res[1], 분류기호
                    AuthorCode = fullparser.GetTag("090b").FirstOrDefault(),//Search_Res[2], 저자기호
                    Volume = fullparser.GetTag("049v").FirstOrDefault(),//Search_Res[3], 볼륨v
                    Copy = fullparser.GetTag("049c").FirstOrDefault(),//Search_Res[4], 복본c
                    Prefix = fullparser.GetTag("049f").FirstOrDefault(),//Search_Res[5], 별치f
                    Isbn = fullparser.GetTag("020a").FirstOrDefault(),//Search_Res[6], ISBN
                    BookName = fullparser.GetTag("245a").FirstOrDefault(),// Search_Res[7], 도서명
                    SBookName1 = fullparser.GetTag("440a").FirstOrDefault(),// Search_Res[8],총서명1
                    SBookNum1 = fullparser.GetTag("440v").FirstOrDefault(),//Search_Res[9],총서번호1
                    SBookName2 = fullparser.GetTag("490a").FirstOrDefault(),//Search_Res[10],총서명2
                    SBookNum2 = fullparser.GetTag("490v").FirstOrDefault(),//Search_Res[11],총서번호2
                    Author = v_author,
                    BookComp = fullparser.GetTag("260b").FirstOrDefault(),//Search_Res[12],출판사
                    Price = Convert.ToInt32(fullparser.GetTag("950b").FirstOrDefault()),//Search_Res[13],정가
                    Marc = fullmarc,
                    ColCheck = "T"
                };

                // idx, 연번, 등록번호, 분류, 저자기호
                // "", "", Search_Res[0], Search_Res[1], Search_Res[2],
                // 볼륨v, 복본c, 별치f, 구분, isbn
                // Search_Res[3], Search_Res[4], Search_Res[5], "", Search_Res[6],
                // 도서명, 총서명1, 총서번호1, 총서명1, 총서번호2
                // Search_Res[7], Search_Res[8], Search_Res[9], Search_Res[10], Search_Res[11],
                // 저자, 출판사, 정가, midx, 마크
                // author_Fin, Search_Res[12], Search_Res[13], "", grid[a],
                // 검색태그
                // "", "T" 


                if (ResultItems == null) ResultItems = new List<MarcPlanItem>();
                ResultItems.Add(item);
            }
            if (warnmessage.Length > 0)
                UTIL.MsgI(warnmessage.ToString());
        }

        #endregion

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

        private void cb_gu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_gu.SelectedIndex == 0)
            {
                btn_Progress.Enabled = false;
                btn_Complite.Enabled = true;
                btn_Search_Click(null, e);
            }
            else
            {
                btn_Complite.Enabled = false;
                btn_Progress.Enabled = true;
                btn_Search_Click(null, e);
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int col = e.ColumnIndex;
            int row = e.RowIndex;
            if (col < 0 || row < 0) return;
            if (dataGridView1.Columns[col].Name == "colCheck")
                return;

            var drow = dataGridView1.Rows[row].DataBoundItem as MarcPlanItem;
            ResultIdx = drow.Idx;//idx;
            ResultListName = drow.ListName;// list_name;
            ResultDate = drow.Date;//date;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

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