using ExcelTest;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

using UniMarc.Properties;
using WindowsFormsApp1;

namespace UniMarc.마크
{
    public partial class Marc_mkList : Form
    {
        Marc marc;
        CD_LP cp;
        Helper_DB db = new Helper_DB();
        string compidx = Settings.Default.compidx;

        public Marc_mkList(Marc _marc)
        {
            InitializeComponent();
            marc = _marc;
        }

        public Marc_mkList(CD_LP _cp)
        {
            InitializeComponent();
            cp = _cp;
        }

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

            #region panel1 set
            rb_basicNum.Checked = true;
            rb_autoNum.Enabled = false;
            

            string[] type = { "정리" };
            cb_listType.Items.AddRange(type);
            cb_listType.SelectedIndex = 0;
            #endregion

            #region panel2 set 저자기호 // 분류기호

            AuthorSymbol.Symbol symbol = new AuthorSymbol.Symbol();

            // 저자기호
            string[] First = symbol.authorBook;
            cb_FirstAuthor.Items.AddRange(First);
            cb_FirstAuthor.SelectedIndex = 0;

            string[] authorType = symbol.authorType;
            cb_authorType.Items.AddRange(authorType);
            cb_authorType.SelectedIndex = 0;

            string[] Book = symbol.authorBook;
            cb_FirstBook.Items.AddRange(Book);
            cb_FirstBook.SelectedIndex = 0;

            // 분류기호
            string[] divType = { "KDC", "DDC" };
            cb_divType.Items.AddRange(divType);
            cb_divType.SelectedIndex = 0;
            #endregion
        }

        private void cb_divType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cb_divNum.Items.Clear();
            if (((ComboBox)sender).SelectedIndex == 0) {
                string[] divNum = { "4", "5", "6" };
                cb_divNum.Items.AddRange(divNum);
            }
            else {
                string[] divNum = { "21", "22", "23" };
                cb_divNum.Items.AddRange(divNum);
            }
            cb_divNum.SelectedIndex = 0;
        }

        private void btn_mkList_Click(object sender, EventArgs e)
        {
            String_Text st = new String_Text();
            if (tb_listName.Text == "") {
                MessageBox.Show("목록명을 입력해주세요!");
                return;
            }
            if (tb_outnum.Text == "") {
                MessageBox.Show("차수가 비어있습니다.");
                return;
            }

            string listName = tb_listName.Text;
            string Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string outnum = tb_outnum.Text + "차";
            string user = Settings.Default.User;

            bool isAuthor = false;
            bool isBook = false;
            if (cb_FirstAuthor.SelectedIndex == 0)
                isAuthor = true;
            if (cb_FirstBook.SelectedIndex == 0)
                isBook = true;
            bool[] isType = { isAuthor, isBook };
            
            // 시방서 목록 DB에 들어갈 것들.
            string[] insert_list_col = { 
                "compidx", "work_list", "date", "state", "gu",
                "first_Author", "symbol_Author", "book_Author", "divType", "divNum",
                "etc", "user"
            };
            string[] insert_list_data = {
                compidx, listName, Time, "진행", cb_listType.Text,
                cb_FirstAuthor.Text, cb_authorType.Text, cb_FirstBook.Text, cb_divType.Text, cb_divNum.Text,
                rtb_etc.Text, user
            };
            string cmdByList = db.DB_INSERT("Specs_List", insert_list_col, insert_list_data);

            // 시방서 마크 DB에 들어갈 것들.
            string[] insert_marc_col = {
                "compidx", "work_list", "date", "ISBN", "book_name",
                "s_book_name1", "s_book_num1", "author", "book_comp", "pubdate",
                "price", "tag008", "class_symbol", "author_symbol", "marc",
                "imageURL", "count", "num", "out_num", "midx",
                "editDate", "user"
            };

            string[] insert_marc_data = {
                compidx, listName, Time, "", "",
                "", "", "", "", "",
                "", "", "", "", "",
                "", "", "", "", "",
                Time, user
            };  // 마크에서 추출 ( 3 ~ 12 )

            int[] row = checkGridRow();
            int num = 0;
            progressBar1.Maximum = row.Length + 1;
            string cmdByMarc = string.Format("INSERT INTO {0} {1} value", "Specs_Marc", db.DB_INSERT_SUB("", insert_marc_col));

            bool CountSplit = chk_countSplit.Checked;
            int listCount = 1;
            int addCount = 1;

            // 필터링하여 DB에 집어넣는 작업
            for (int a = 0; a < row.Length; a++)
            {
                if (marc.List_Book.Rows[row[a]].Cells["db_marc"].Value.ToString() == "")
                    continue;

                num += 1;
                listCount = Convert.ToInt32(marc.List_Book.Rows[row[a]].Cells["count"].Value.ToString());

                // ISBN, book_name, s_book_name1, s_book_num1, author, book_comp, pubdate, price, tag008, class_symbol
                string[] Search = { "020a", "245a", "440a", "440v", "245d", "260b", "260c", "950b", "008", "056a" };

                insert_marc_data[14] = marc.List_Book.Rows[row[a]].Cells["db_marc"].Value.ToString();
                insert_marc_data[15] = marc.List_Book.Rows[row[a]].Cells["url"].Value.ToString();
                insert_marc_data[16] = addCount.ToString();
                if (rb_basicNum.Checked)
                    insert_marc_data[17] = marc.List_Book.Rows[row[a]].Cells["num"].Value.ToString();
                else
                    insert_marc_data[17] = num.ToString();
                insert_marc_data[18] = outnum;
                insert_marc_data[19] = marc.List_Book.Rows[row[a]].Cells["marc_idx"].Value.ToString();
                insert_marc_data[20] = marc.List_Book.Rows[row[a]].Cells["SaveDate"].Value.ToString();
                insert_marc_data[21] = marc.List_Book.Rows[row[a]].Cells["user"].Value.ToString(); 

                string[] Marc = st.Take_Tag(insert_marc_data[14], Search);
                string[] Author = { "", Marc[1] };       // 저자, 도서명

                // 100, 110, 111태그중 한개라도 있으면 저자로 인식.
                string[] Author_Search = { "100a", "110a", "111a", "245d" };
                string[] Author_res = st.Take_Tag(insert_marc_data[14], Author_Search);

                if (Author_res[0].Length > 1) Author[0] = Author_res[0];
                if (Author_res[1].Length > 1) Author[0] = Author_res[1];
                if (Author_res[2].Length > 1) Author[0] = Author_res[2];

                if(chk_CompSymbol.Checked)
                    if (Author_res[3].IndexOf("[외]") > -1)
                        Author[0] = Marc[5];

                string tmp_ViewMarc = st.ConvertMarcType(insert_marc_data[14]);

                // 마크에서 추출한 데이터 DB에 적용하기 위한 반복문
                for (int b = 0; b < Marc.Length; b++)
                {
                    insert_marc_data[b + 3] = Marc[b];

                    // 분류기호 설정값적용대로 가져오기.
                    if (b == 9) {
                        string class_symbol = st.TakeTag_ConditionContent(tmp_ViewMarc, "056a", "056" + cb_divNum.Text);
                        if (class_symbol != "")
                            insert_marc_data[b + 3] = class_symbol;
                    }
                }

                // 22.10.24 740태그 삭제
                tmp_ViewMarc = st.RemoveTagNumber(tmp_ViewMarc, "740");

                // 마크 분류기호 설정값대로 적용
                tmp_ViewMarc = st.RemoveTagNumber(tmp_ViewMarc, "056");
                tmp_ViewMarc = st.AddTagInMarc(string.Format("056\t  \t▼a{0}▼2{1}▲", insert_marc_data[12], cb_divNum.Text), tmp_ViewMarc);
                insert_marc_data[14] = st.made_Ori_marc(tmp_ViewMarc);

                if (Author[0].Length < 1) {
                    MessageBox.Show(row[a] + "번째의 저자를 확인해주세요. \n (100a, 110a, 111a 중 1개 필수)");
                    return;
                }

                Author[0] = Regex.Replace(Author[0], @"[^a-zA-Z0-9가-힣_]", "", RegexOptions.Singleline);
                Author[1] = st.RemoveWordInBracket(Author[1]);
                Author[1] = Regex.Replace(Author[1], @"[^a-zA-Z0-9가-힣_]", "", RegexOptions.Singleline);

                AuthorSymbol.Symbol sb = new AuthorSymbol.Symbol();
                string authorType = cb_authorType.SelectedItem.ToString();
                string res_Author = sb.SymbolAuthor(Author[0], Author[1], authorType, isType);

                insert_marc_data[13] = res_Author;

                cmdByMarc += db.DB_INSERT_SUB("value", insert_marc_data) + ",";

                if (CountSplit && listCount > addCount) {
                    a--;
                    addCount++;
                    continue;
                }
                else {
                    addCount = 1;
                    progressBar1.PerformStep();
                }
            }

            cmdByMarc = cmdByMarc.TrimEnd(',');
            cmdByMarc += ";";

            db.DB_Send_CMD_reVoid(cmdByList);
            db.DB_Send_CMD_reVoid(cmdByMarc);
            progressBar1.PerformStep();

            if (progressBar1.Value == progressBar1.Maximum) {
                label2.Text = "완료되었습니다!";
            }
        }
        #region mkList_Sub
        int[] checkGridRow()
        {
            List<int> GridRow = new List<int>();
            for (int a = 0; a < marc.List_Book.Rows.Count; a++)
            {
                bool isSuccess = true;
                if (!marc.Check_BackColor(a) && marc.Check_List_V(a))
                    isSuccess = false;

                if (isSuccess)
                    GridRow.Add(a);
            }

            int[] Result = GridRow.ToArray();
            return Result;
        }
        #endregion

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

    }
}
