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_List : Form
    {
        string compidx;
        Helper_DB db = new Helper_DB();
        Main main;
        public CD_LP_List(Main _main)
        {
            InitializeComponent();
            main = _main;
        }

        private void CD_LP_List_Load(object sender, EventArgs e)
        {
            db.DBcon();
            compidx = PUB.user.CompanyIdx;// Properties.Settings.Default.compidx;
        }

        private void Btn_SelectList_Click(object sender, EventArgs e)
        {
            CD_LP_SelectList selectList = new CD_LP_SelectList(this);
            selectList.Show();
            selectList.LoadList(compidx);
            dataGridView1.Rows.Clear();
            dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
        }

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

            string Table = "DVD_List_Product";
            string Area = "`idx`, `num`, `title`, `artist`, `comp`, `price`, `type`, `marc`";
            string[] Search_Table = { "compidx", "listname", "date" };
            string[] Search_Column = { compidx, 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('|');

            /// [0]idx [1]num [2]title [3]artist [4]comp [5]price [6]type [7]marc

            /// 선택 idx 연번 등록번호 분류
            /// 저자기호 볼륨 복본 별치 서명
            /// 감독 제작 정가 유형 마크
            string[] grid = { 
                "T", "", "", "", "",
                "", "", "", "", "",
                "", "", "", "", ""
            };
            for (int a = 0; a < ary_res.Length; a++)
            {
                if (a % 8 == 0) grid[1] = ary_res[a];           // idx
                if (a % 8 == 1) grid[2] = ary_res[a];           // num
                if (a % 8 == 2) grid[9] = ary_res[a];           // title
                if (a % 8 == 3) grid[10] = ary_res[a];          // artist
                if (a % 8 == 4) grid[11] = ary_res[a];          // comp
                if (a % 8 == 5) grid[12] = ary_res[a];          // price
                if (a % 8 == 6) grid[13] = ary_res[a];          // type
                if (a % 8 == 7) { grid[14] = ary_res[a];        // marc
                    dataGridView1.Rows.Add(grid);
                }
            }
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (row < 0) return;
            int col = dataGridView1.CurrentCell.ColumnIndex;

            if (col == 2 || col == 3 || col == 4 || col == 5 || col == 6 || col == 7)
            {
                if (dataGridView1.Rows[row].Cells["Marc"].Value.ToString() == "" &&
                    dataGridView1.Rows[row].Cells["Marc"].Value == null)
                {
                    UTIL.MsgE("저장된 마크가 없습니다!");
                    return;
                }

                string Marc = dataGridView1.Rows[row].Cells["Marc"].Value.ToString();

                string AddTag = "";
                if (col == 2 || col == 5 || col == 6 || col == 7)
                {
                    string L = dataGridView1.Rows[row].Cells[2].Value.ToString();
                    string V = dataGridView1.Rows[row].Cells[5].Value.ToString();
                    string C = dataGridView1.Rows[row].Cells[6].Value.ToString();
                    string F = dataGridView1.Rows[row].Cells[7].Value.ToString();

                    if (L != "")
                        L = string.Format("▼l{0}", L);

                    if (V != "")
                        V = string.Format("▼v{0}", V);

                    if (C != "")
                        C = string.Format("▼c{0}", C);

                    if (F != "")
                        F = string.Format("▼f{0}", F);

                    AddTag = string.Format("049\t  \t{0}{1}{2}{3}▲", L, V, C, F);
                }
                if (col == 3 || col == 4 || col == 5)
                {
                    string A = dataGridView1.Rows[row].Cells[3].Value.ToString();
                    string B = dataGridView1.Rows[row].Cells[4].Value.ToString();
                    string C = dataGridView1.Rows[row].Cells[5].Value.ToString();

                    if (A != "")
                        A = string.Format("▼a{0}", A);

                    if (B != "")
                        B = string.Format("▼b{0}", B);

                    if (C != "")
                        C = string.Format("▼c{0}", C);

                    AddTag = string.Format("090\t  \t{0}{1}{2}▲", A, B, C);
                }
                string TypeView = ConvertMarcType(Marc);
                string AddMarc = AddTagInMarc(AddTag, TypeView);

                String_Text st = new String_Text();
                dataGridView1.Rows[row].Cells["Marc"].Value = st.made_Ori_marc(AddMarc);
            }
        }

        #region CellValueChanged_Sub

        /// <summary>
        /// 한줄짜리 마크를 보기 쉬운 형태로 변환
        /// </summary>
        /// <param name="Marc">한줄짜리 마크</param>
        /// <returns></returns>
        string ConvertMarcType(string Marc)
        {
            if (Marc.Length < 3) return "";

            string result = "";

            List<string> TagNum = new List<string>();   // 태그번호 저장용
            List<string> Field = new List<string>();    // 가변길이필드 저장용

            // 특수기호 육안으로 확인하기 쉽게 변환
            Marc = Marc.Replace("", "▼");
            Marc = Marc.Replace("", "▲");
            Marc = Marc.Replace("￦", "\\");

            int StartIdx = 0;

            // 리더부를 제외한 디렉토리, 가변길이필드 저장
            string[] data = Marc.Substring(24).Split('▲');
            for (int a = 1; a < data.Length - 1; a++)
            {
                TagNum.Add(data[0].Substring(StartIdx, 3));
                StartIdx += 12;
                Field.Add(data[a] + "▲");
            }

            // List에 들어간 데이터를 메모장에 출력
            for (int a = 0; a < TagNum.Count; a++)
            {
                string res = TagNum[a];
                if (Field[a].IndexOf("▼") == -1)
                {
                    res += "\t  \t" + Field[a];
                }
                else
                {
                    string temp = Field[a].Insert(2, "\t");
                    res += "\t" + temp;
                }
                result += res + "\n";
            }
            return result;
        }

        string AddTagInMarc(string Tag, string TypeView)
        {
            if (Tag.Length < 3) return "";

            int TargetTagNum = Convert.ToInt32(Tag.Substring(0, 3));

            string[] SplitView = TypeView.Split('\n');
            List<string> View = new List<string>(SplitView);

            int ViewCount = 0;
            foreach (string LineMarc in View)
            {
                string LineTag = LineMarc.Substring(0, 3);
                int TagNum = Convert.ToInt32(LineTag);

                if (TargetTagNum == TagNum)
                {
                    View[ViewCount] = Tag;
                    break;
                }
                else if (TargetTagNum < TagNum)
                {
                    View.Insert(ViewCount, Tag);
                    break;
                }
                ViewCount++;
            }
            return string.Join("\n", View);
        }
        #endregion

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

        private void Btn_SelectGrid(object sender, EventArgs e)
        {
            string t = ((Button)sender).Name;

            if (t.Contains("True"))
                GridCheckAllChange(true);
            else
                GridCheckAllChange(false);
        }

        void GridCheckAllChange(bool TF)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].Cells["Check"].Value = TF;
            }
        }

        private void Btn_ViewMarc_Click(object sender, EventArgs e)
        {
            string t = (((Button)sender).Text);
            if (t.Contains("보이기"))
            {
                panel2.Height = 250;
                ((Button)sender).Text = "마크감추기";
            }
            else
            {
                panel2.Height = 1;
                ((Button)sender).Text = "마크보이기";
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            String_Text st = new String_Text();

            int row;

            if (e.RowIndex > -1)
                row = e.RowIndex;
            else
                return;
            
            richTextBox1.Text = st.ConvertMarcType(dataGridView1.Rows[row].Cells["Marc"].Value.ToString(),out string errmesage);
        }

        private void Btn_Excel_Click(object sender, EventArgs e)
        {
            Excel_text et = new Excel_text();
            int rowCount = dataGridView1.RowCount;

            string[] title = { "NO", "등록번호", "분류", "저자", "볼륨", "복본", "별치", "서명", "감독/뮤지션", "제작", "정가" };
            string[,] Content = new string[rowCount, 11];

            for (int a = 0; a < rowCount; a++)
            {
                if (!(bool)dataGridView1.Rows[a].Cells["Check"].Value) continue;
                Content[a, 0] = dataGridView1.Rows[a].Cells["Num"].Value.ToString();
                Content[a, 1] = dataGridView1.Rows[a].Cells["RegNum"].Value.ToString();
                Content[a, 2] = dataGridView1.Rows[a].Cells["ClassNum"].Value.ToString();
                Content[a, 3] = dataGridView1.Rows[a].Cells["AuthorSymbol"].Value.ToString();
                Content[a, 4] = dataGridView1.Rows[a].Cells["Vol"].Value.ToString();
                Content[a, 5] = dataGridView1.Rows[a].Cells["Copy"].Value.ToString();
                Content[a, 6] = dataGridView1.Rows[a].Cells["Fix"].Value.ToString();
                Content[a, 7] = dataGridView1.Rows[a].Cells["Title"].Value.ToString();
                Content[a, 8] = dataGridView1.Rows[a].Cells["Artist"].Value.ToString();
                Content[a, 9] = dataGridView1.Rows[a].Cells["Comp"].Value.ToString();
                Content[a, 10] = dataGridView1.Rows[a].Cells["Price"].Value.ToString();
            }
            et.Mk_Excel(title, Content);
        }

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

        private void Btn_OutPut_Click(object sender, EventArgs e)
        {
            string Marc_data = "";
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["Marc"].Value.ToString() == "" &&
                    dataGridView1.Rows[a].Cells["Marc"].Value == null) continue;

                string marc = dataGridView1.Rows[a].Cells["Marc"].Value.ToString();
                Marc_data += marc.Replace("￦", "\\");
            }

            string FileName;
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "저장 경로를 지정해주세요.";
            saveFile.OverwritePrompt = true;
            saveFile.Filter = "마크 파일 (*.mrc)|*.mrc|모든 파일 (*.*)|*.*";

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                FileName = saveFile.FileName;
                switch (cb_EncodingType.SelectedIndex)
                {
                    case 0:
                        System.IO.File.WriteAllText(FileName, Marc_data, Encoding.Default);
                        break;
                    case 1:
                        System.IO.File.WriteAllText(FileName, Marc_data, Encoding.UTF8);
                        break;
                    case 2:
                        System.IO.File.WriteAllText(FileName, Marc_data, Encoding.Unicode);
                        break;
                }
            }
        }

        private void Btn_SelectRemove_Click(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("정말 삭제하시겠습니까?")  != DialogResult.Yes)
                return;

            List<int> SelectIndex = new List<int>();

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["Check"].Value.ToString() == "T")
                {
                    SelectIndex.Add(a);
                }
            }

            if (SelectIndex.Count <= 0) {
                UTIL.MsgE("선택 사항이 없습니다.");
                return;
            }

            for (int a = SelectIndex.Count - 1; a >= 0; a--)
            {
                dataGridView1.Rows.RemoveAt(SelectIndex[a]);
                Helper_DB.ExcuteNonQuery(
                    db.DB_Delete("DVD_List_Product", "idx", dataGridView1.Rows[SelectIndex[a]].Cells["idx"].Value.ToString(), "compidx", compidx)
                    );
            }
            UTIL.MsgI("삭제되었습니다");
        }

    }
}
