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 CD_LP : Form
    {
        Main main;
        Helper_DB db = new Helper_DB();
        public CD_LP(Main _m)
        {
            InitializeComponent();
            main = _m;
        }

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

            string[] Site = { "교보문고", "알라딘" };
            cb_SiteCon.Items.AddRange(Site);
            cb_SiteCon.SelectedIndex = 1;

            string[] Type = { "음반", "DVD" };
            cb_Type.Items.AddRange(Type);
            cb_Type.SelectedIndex = 0;
        }

        private void Btn_Connect_Click(object sender, EventArgs e)
        {
            int site = cb_SiteCon.SelectedIndex;

            CD_LP_Sub sub = new CD_LP_Sub(this);
            sub.Show();

            if (site == 0) {    // 교보문고
                sub.Btn_KyoBo_Click(null, null);
            }
            if (site == 1) {    // 알라딘
                sub.Btn_Aladin_Click(null, null);
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            tb_T005.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
        }

        private void Btn_SelectList_Click(object sender, EventArgs e)
        {
            CD_LP_SelectList selectList = new CD_LP_SelectList(this);
            selectList.Show();
            selectList.LoadList(PUB.user.CompanyIdx);
            dataGridView1.Rows.Clear();
        }

        public void MakeList(string ListName, string date)
        {
            lbl_ListTitle.Text = ListName;
            lbl_date.Text = date;

            string Table = "DVD_List_Product";
            string Area = "`idx`, `num`, `code`, `title`, `artist`, `comp`, `price`, `m_idx`";
            string[] Search_Table = { "compidx", "listname", "date" };
            string[] Search_Column = { PUB.user.CompanyIdx, ListName, date };

            string cmd = db.More_DB_Search(Table, Search_Table, Search_Column, Area);
            string res = db.DB_Send_CMD_Search(cmd);
            string[] ary_res = res.Split('|');

            // idx num code title artist comp price m_idx Marc
            string[] grid = { "", "", "", "", "", "", "", "", "" };
            for (int a = 0; a < ary_res.Length; a++)
            {
                if (a % 8 == 0) grid[0] = ary_res[a];
                if (a % 8 == 1) grid[1] = ary_res[a];
                if (a % 8 == 2) grid[2] = ary_res[a];
                if (a % 8 == 3) grid[3] = ary_res[a];
                if (a % 8 == 4) grid[4] = ary_res[a];
                if (a % 8 == 5) grid[5] = ary_res[a];
                if (a % 8 == 6) grid[6] = ary_res[a];
                if (a % 8 == 7) {  
                    grid[7] = ary_res[a];
                    dataGridView1.Rows.Add(grid);
                }
            }

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string m_idx = dataGridView1.Rows[a].Cells["m_idx"].Value.ToString();
                string code = dataGridView1.Rows[a].Cells["code"].Value.ToString();
                if (m_idx != "")
                    cmd = string.Format("SELECT `Marc` FROM `DVD_Marc` WHERE `idx` = {0};", m_idx);
                else
                    cmd = string.Format("SELECT `Marc` FROM `DVD_Marc` WHERE `Code` = {0} LIMIT 1;", code);
                dataGridView1.Rows[a].Cells["marc"].Value = db.DB_Send_CMD_Search(cmd).Replace("|", "");
            }
        }

        private void btn_CopySelect_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell == null) return;

            int row = dataGridView1.CurrentCell.RowIndex;
            string code = dataGridView1.Rows[row].Cells["code"].Value.ToString();

            MarcCopySelect copySelect = new MarcCopySelect(this);
            copySelect.MarcFormRowIndex = row;
            copySelect.Init("Code", code, "CDLP");
            copySelect.Show();
        }
        public void SelectMarc_Sub(int row, string[] GridData)
        {
            dataGridView1.Rows[row].Cells["m_idx"].Value = GridData[0];
            dataGridView1.Rows[row].Cells["marc"].Value = GridData[6];
        }

        private void btn_mk_marcList_Click(object sender, EventArgs e)
        {
            Marc_mkList mkList = new Marc_mkList(this);
            mkList.Show();
        }

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

            String_Text st = new String_Text();

            int row = dataGridView1.CurrentRow.Index;
            string midx = dataGridView1.Rows[row].Cells["m_idx"].Value.ToString();
            string code = dataGridView1.Rows[row].Cells["code"].Value.ToString();
            string user = PUB.user.UserName;
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string etcData1 = etc1.Text;
            string etcData2 = etc2.Text;

            if (etcData1 == "Remarc1") etcData1 = "";
            if (etcData2 == "Remarc2") etcData2 = "";

            string t005 = tb_T005.Text;
            string t007 = tb_T007.Text;
            string t008 = tb_T008.Text;

            string marc = string.Format("005\t  \t{0}▲\n007\t  \t{1}▲\n008\t  \t{2}▲\n", t005, t007, t008) + richTextBox1.Text;
            string orimarc = st.made_Ori_marc(marc, false);

            if (!isSaveOK(orimarc, code)) {
                UTIL.MsgE("상품코드를 확인해주세요.");
                return;
            }

            string[] EditCol = { "Code", "user", "date", "Marc", "etc1", "etc2" };
            string[] EditData = { code, user, date, orimarc, etcData1, etcData2 };
            string[] SearchCol = { "idx" };
            string[] SearchData = { midx };

            Helper_DB.ExcuteNonQuery(db.More_Update("DVD_Marc", EditCol, EditData, SearchCol, SearchData));
            dataGridView1.Rows[row].Cells["marc"].Value = orimarc;
        }

        #region 마크 저장 서브 함수
        /// <summary>
        /// 태그 100, 110, 111에서 데이터를 따와 값이 있는 데이터만 반환
        /// </summary>
        /// <param name="ValueArray">태그 100, 110, 111</param>
        /// <returns>값이 들어있는 태그의 내용</returns>
        string Takeartist(string[] ValueArray)
        {
            string result = "";
            foreach (string value in ValueArray)
            {
                if (value.Length != 0)
                    result = value;
            }
            return result;
        }
        #endregion

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            richTextBox1.Text = "";
            etc1.Text = "Remark1";
            etc2.Text = "Remark2";
            int row = e.RowIndex;
            string SelectNum = dataGridView1.Rows[row].Cells["num"].Value.ToString();
            string SelectMarc = dataGridView1.Rows[row].Cells["marc"].Value.ToString();
            string SelectMIdx = dataGridView1.Rows[row].Cells["m_idx"].Value.ToString();
            string SelectCode = dataGridView1.Rows[row].Cells["code"].Value.ToString();

            if (SelectMIdx == "0")
                Btn_SaveMarc.Enabled = false;
            else
            {
                Btn_SaveMarc.Enabled = true;
                string[] etcData = db.DB_Send_CMD_Search(string.Format("SELECT `etc1`, `etc2` FROM `DVD_Marc` WHERE `idx` = {0};", SelectMIdx)).Split('|');
                etc1.Text = etcData[0];
                etc2.Text = etcData[1];
            }

            btn_CopySelect.Text = db.DB_Send_CMD_Search(
                string.Format("SELECT Count(`Code`) FROM DVD_Marc WHERE `Code` = \"{0}\" Group by `Code`;", SelectCode)).Replace("|", "");

            tb_Num.Text = SelectNum;

            if (SelectMarc == "")
            {
                richTextBox1.Text =
                    "020\t  \t▼a:▼c▲\n" +
                    "041\t0 \t▼a▼b▼▲\n" +
                    "056\t  \t▼a▼25▲\n" +
                    "090\t  \t▼a▼b▲\n" +
                    "100\t1 \t▼a▲\n" +
                    "245\t10\t▼a▼h[녹음자료]/▼d▲\n" +
                    "260\t  \t▼a:▼b [제작],▼c▲\n" +
                    "300\t  \t▼a음반 1매:▼b디지털, 스테레오;▼c12 cm▲\n" +
                    "505\t00\t▼n01.▼t▲\n" +
                    "508\t  \t▼a제작진:▲\n" +
                    "511\t8 \t▼a▲\n" +
                    "520\t  \t▼a▲\n" +
                    "521\t  \t▼a전체이용가▲\n" +
                    "653\t  \t▼a▲\n" +
                    "700\t1 \t▼a▲\n" +
                    "740\t 2\t▼a▲\n" +
                    "950\t0 \t▼b\\▲";

                if (cb_Type.SelectedIndex == 0)
                {
                    tb_T007.Text = "sd fsngunmmned";
                    tb_T008.Text = DateTime.Now.ToString("yyMMdd") + "s        ulk  n         z a  kor  ";
                }
                else
                {
                    tb_T007.Text = "vd cgairq";
                    tb_T008.Text = DateTime.Now.ToString("yyMMdd") + "s        ulk    d         avlkor  ";
                }
                return;
            }

            String_Text st = new String_Text();

            string ViewMarc = st.ConvertMarcType(SelectMarc,out string errmesage);
            List<string> Tmp = new List<string>(ViewMarc.Split('\n'));
            for (int a = 0; a < Tmp.Count; a++)
            {
                if (Tmp[a] == "") continue;
                else if (Tmp[a].Substring(0, 3) == "005")
                    tb_T005.Text = Tmp[a].Replace("005\t  \t", "").Replace("▲", "");
                else if (Tmp[a].Substring(0, 3) == "007")
                    tb_T007.Text = Tmp[a].Replace("007\t  \t", "").Replace("▲", "");
                else if (Tmp[a].Substring(0, 3) == "008")
                    tb_T008.Text = Tmp[a].Replace("008\t  \t", "").Replace("▲", "");
                else
                    richTextBox1.Text += Tmp[a] + "\n";
            }
        }

        private void Btn_Help007_Click(object sender, EventArgs e)
        {
            Help_007 help007 = new Help_007(this);
            if (cb_Type.Text == "음반") help007.isMusic = true;
            else help007.isMusic = false;

            string Text007 = tb_T007.Text;
            help007.text007 = Text007;
            help007.Show();
        }

        private void Btn_Help008_Click(object sender, EventArgs e)
        {
            Help_008 help008 = new Help_008(this);
            if (cb_Type.Text == "음반") help008.isMusic = true;
            else help008.isMusic = false;
            string Text008 = tb_T008.Text;
            help008.text008 = Text008;
            help008.Show();
        }

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

            String_Text st = new String_Text();

            int row = dataGridView1.CurrentRow.Index;
            string code = dataGridView1.Rows[row].Cells["code"].Value.ToString();
            string user = PUB.user.UserName;// Properties.Settings.Default.User;
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


            string etcData1 = etc1.Text;
            string etcData2 = etc2.Text;

            if (etcData1 == "Remarc1") etcData1 = "";
            if (etcData2 == "Remarc2") etcData2 = "";

            string t005 = tb_T005.Text;
            string t007 = tb_T007.Text;
            string t008 = tb_T008.Text;

            string marc = string.Format("005\t  \t{0}▲\n007\t  \t{1}▲\n008\t  \t{2}▲\n", t005, t007, t008) + richTextBox1.Text;
            string orimarc = st.made_Ori_marc(marc, false);

            // 상품코드 체크
            if (!isSaveOK(orimarc, code)) {
                UTIL.MsgE("상품코드를 확인해주세요.");
                return;
            }

            // 필수태그 확인
            if (!isMustTag(orimarc)) {
                UTIL.MsgE("입력된 마크의 상태를 확인해주세요.");
                return;
            }

            // 마크 형식 체크
            if (!isPass(marc)) {
                UTIL.MsgE("입력된 마크의 상태를 확인해주세요.");
                return;
            }

            string[] InsertCol = { "Code", "user", "date", "Marc", "etc1", "etc2" };
            string[] InsertData = { code, user, date, orimarc, etcData1, etcData2 };
            Helper_DB.ExcuteNonQuery(db.DB_INSERT("DVD_Marc", InsertCol, InsertData));

            dataGridView1.Rows[row].Cells["m_idx"].Value =
                db.DB_Send_CMD_Search(
                    string.Format("SELECT `idx` FROM `DVD_Marc` WHERE `user` = \"{0}\" AND `date` = \"{1}\";", user, date)).Replace("|", "");
            dataGridView1.Rows[row].Cells["marc"].Value = orimarc;
        }

        bool isSaveOK(string oriMarc, string code)
        {
            if (code == "") return false;

            String_Text st = new String_Text();
            string[] SearchTagList = { "020a" };
            string[] TagList = st.Take_Tag(oriMarc, SearchTagList);

            return TagList[0].Contains(code);
        }

        /// <summary>
        /// 마크 오류체크 (형식체크)
        /// </summary>
        /// <param name="BaseData">richTextBox에 들어가있는 텍스트</param>
        /// <returns>True / False</returns>
        private bool isPass(string BaseData)
        {
            string[] EnterSplit = BaseData.Split('\n');

            foreach (string Data in EnterSplit)
            {
                if (Data == "")
                    continue;

                string[] DataSplit = Data.Split('\t');
                if (DataSplit.Length == 3)
                {
                    if (DataSplit[1].Length == 2)
                    {
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        private bool isMustTag(string orimarc)
        {
            String_Text st = new String_Text();
            string[] SearchTag = {
                "056a", "0562", "245a", "245d", "260a", "260b", "260c", "300a", "300c", "653a"
            };

            string[] Tag = st.Take_Tag(orimarc, SearchTag);

            int count = 0;
            string msg = "";
            bool isTag = true;
            foreach (string tag in Tag)
            {
                if (tag == "")
                {
                    msg += SearchTag[count] + " ";
                    isTag = false;
                }
                count++;
            }

            if (!isTag)
            {
                UTIL.MsgE(msg + "태그가 없습니다.");
                return false;
            }

            bool is1XX = false;
            string[] AuthorTag = { "100a", "110a", "111a" };
            Tag = st.Take_Tag(orimarc, AuthorTag);

            foreach (string author in Tag)
            {
                if (author != "")
                    is1XX = true;
            }

            if (!is1XX)
            {
                UTIL.MsgE("기본표목이 존재하지않습니다.");
                return false;
            }

            bool is7XX = false;
            AuthorTag[0] = "700a";
            AuthorTag[1] = "710a";
            AuthorTag[2] = "711a";
            Tag = st.Take_Tag(orimarc, AuthorTag);

            foreach (string author in Tag)
            {
                if (author != "")
                    is7XX = true;
            }

            if (!is7XX)
            {
                UTIL.MsgE("부출표목이 존재하지않습니다.");
                return false;
            }

            return true;
        }

        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F3)
                richTextBox1.SelectedText = "▼";

            else if (e.KeyCode == Keys.F4)
                richTextBox1.SelectedText = "▲";

            else if (e.KeyCode == Keys.F8)
                Btn_New_Click(null, null);

            else if (e.KeyCode == Keys.F9)
                Btn_SaveMarc_Click(null, null);
        }


        DataGridViewRow tempSave = null;
        int TempRow = -1;
        List<string> DeleteIndex = new List<string>();


        private void Btn_SelectRemove_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;

            if (dataGridView1.CurrentRow.Index < 0) return;

            TempRow = dataGridView1.CurrentRow.Index;
            tempSave = dataGridView1.Rows[TempRow];
            DeleteIndex.Add(dataGridView1.Rows[TempRow].Cells["idx"].Value.ToString());

            dataGridView1.Rows.RemoveAt(TempRow);
        }

        private void Btn_Undo_Click(object sender, EventArgs e)
        {
            if (tempSave == null || TempRow < 0) return;

            try {
                dataGridView1.Rows.Insert(TempRow, tempSave);
                DeleteIndex.Remove(tempSave.Cells["idx"].Value.ToString());
            }
            catch (InvalidOperationException ex) {
                return;
            }
        }

        private void btn_SaveList_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["idx"].Value == null) dataGridView1.Rows[a].Cells["idx"].Value = "";
                if (dataGridView1.Rows[a].Cells["idx"].Value.ToString() == "")
                {
                    string[] Insert_col = { "compidx", "listname", "date", "user", "num", "code", "title", "artist", "comp", "price" };
                    string[] Insert_data =
                    {
                         PUB.user.CompanyIdx,
                        lbl_ListTitle.Text,
                        lbl_date.Text,
                        PUB.user.UserName,
                        dataGridView1.Rows[a].Cells["num"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["code"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["title"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["author"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["comp"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["price"].Value.ToString()
                    };
                    Helper_DB.ExcuteNonQuery(db.DB_INSERT("DVD_List_Product", Insert_col, Insert_data));
                }
            }

            if (DeleteIndex.Count < 0) return;

            for (int a = 0; a < DeleteIndex.Count; a++)
            {
                Helper_DB.ExcuteNonQuery(db.DB_Delete("DVD_List_Product", "compidx", PUB.user.CompanyIdx, "idx", DeleteIndex[a]));
            }
        }

        private void btn_AddRow_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            int row = dataGridView1.CurrentRow.Index;
            string[] Grid = { "", dataGridView1.Rows[row].Cells["num"].Value.ToString(), "", "", "", "", "", "", "" };
            dataGridView1.Rows.Insert(row + 1, Grid);
        }

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