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;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace UniMarc
{
    public partial class MarcCopySelect : Form
    {
        Helper_DB db = new Helper_DB();
        Marc m;
        AddMarc am;
        CD_LP cp;
        public int MarcFormRowIndex;

        public MarcCopySelect()
        {
            InitializeComponent();
        }
        public MarcCopySelect(CD_LP cD)
        {
            InitializeComponent();
            cp = cD;
            db.DBcon();
        }
        public MarcCopySelect(Marc _m)
        {
            InitializeComponent();
            m = _m;
            db.DBcon();
        }

        public MarcCopySelect(AddMarc _am)
        {
            InitializeComponent();
            am = _am;
            db.DBcon();
        }

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

        private void btn_Search_Click(object sender, EventArgs e)
        {
            if (cb_SearchFilter.SelectedIndex < 0) return;

            dataGridView1.Rows.Clear();
            richTextBox1.Text = "";

            string search_Col = "";
            string search_Target = tb_SearchBox.Text;
            switch (cb_SearchFilter.SelectedIndex)
            {
                case 0:
                    search_Col = "ISBN";
                    break;
                case 1:
                    search_Col = "서명";
                    break;
                case 2:
                    search_Col = "저자";
                    break;
                case 3:
                    search_Col = "출판사";
                    break;
            }
            Init(search_Col, search_Target);
        }

        public void Init(string search_col, string search_Target, string CD_LP)
        {
            SettingGrid_CDLP();

            btn_ShowDeleteMarc.Visible = false;
            btn_Delete.Visible = false;

            if (search_Target == "") return;

            string Area = "`idx`, `Code`, `user`, `date`, `Marc`";
            string Table = "DVD_Marc";
            string Query = string.Format("SELECT {0} FROM {1} WHERE `{2}` = \"{3}\"", Area, Table, search_col, search_Target);
            string Result = db.DB_Send_CMD_Search(Query);
            string[] GridData = Result.Split('|');

            InputGrid_CDLP(GridData);
        }

        private void SettingGrid_CDLP()
        {
            DataGridView dgv = dataGridView1;
            dgv.Columns.Add("idx", "idx");
            dgv.Columns.Add("code", "CODE");
            dgv.Columns.Add("user", "수정자");
            dgv.Columns.Add("date", "수정시각");
            dgv.Columns.Add("marc", "Marc");

            dgv.Columns["idx"].Visible = false;
            dgv.Columns["user"].Width = 120;
            dgv.Columns["date"].Width = 120;
            dgv.Columns["marc"].Width = 300;
        }

        private void InputGrid_CDLP(string[] Value)
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = Value.Length / 5;

            string[] Grid = { "", "", "", "", "" };

            for (int a = 0; a < Value.Length; a++)
            {
                if (a % 5 == 0) Grid[0] = Value[a];       // idx
                if (a % 5 == 1) Grid[1] = Value[a];       // CODE
                if (a % 5 == 2) Grid[2] = Value[a];       // user
                if (a % 5 == 3) Grid[3] = Value[a];       // date
                if (a % 5 == 4)
                {
                    Grid[4] = Value[a];   // marc
                    dataGridView1.Rows.Add(Grid);
                    progressBar1.Value += 1;
                }
            }

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string savedate = dataGridView1.Rows[a].Cells["date"].Value.ToString();
                SaveDataCheck(savedate, a);
            }
        }

        public void Init(string search_col, string search_Target)
        {
            SettingGrid_Book();
            if (search_Target == "") return;

                          // 0 1 2 3 4
            string Area = "`idx`, `compidx`, `ISBN`, `서명`, `저자`, " +
                          // 5 6 7 8 9
                          "`출판사`, `user`, `date`, `grade`, `008tag`, " +
                          // 10 11 12 13 14 15
                          "`marc`, `marc_chk`, `marc1`, `marc_chk1`, `marc2`, `marc_chk2`";
            string Table = "Marc";

            string Query = string.Format("SELECT {0} FROM {1} WHERE `{2}` like \"%{3}%\";", Area, Table, search_col, search_Target);
            string Result = db.DB_Send_CMD_Search(Query);
            string[] GridData = Result.Split('|');

            InputGrid(GridData);
        }

        private void SettingGrid_Book()
        {
            DataGridView dgv = dataGridView1;
            dgv.Columns.Add("idx", "idx");
            dgv.Columns.Add("compidx", "compidx");
            dgv.Columns.Add("isbn", "ISBN");
            dgv.Columns.Add("Title", "서명");
            dgv.Columns.Add("Author", "저자");
            dgv.Columns.Add("Comp", "출판사");
            dgv.Columns.Add("user", "수정자");
            dgv.Columns.Add("date", "수정시각");
            dgv.Columns.Add("grade", "등급");
            dgv.Columns.Add("tag008", "008Tag");
            dgv.Columns.Add("marc", "Marc");

            dgv.Columns["idx"].Visible = false;
            dgv.Columns["compidx"].Visible = false;
            dgv.Columns["user"].Width = 120;
            dgv.Columns["date"].Width = 120;
            dgv.Columns["grade"].Width = 60;
            dgv.Columns["tag008"].Width = 150;
            dgv.Columns["marc"].Width = 200;
        }

        private void InputGrid(string[] Value)
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = Value.Length / 16;

            string[] Grid = {
                "", "", "", "", "",
                "", "", "", "", "",
                "" };
            string[] MarcData = { "", "", "", "", "", "" };
        
            for (int a = 0; a < Value.Length; a++)
            {
                if (a % 16 == 0)    Grid[0] = Value[a];       // idx
                if (a % 16 == 1)    Grid[1] = Value[a];       // compidx
                if (a % 16 == 2)    Grid[2] = Value[a];       // isbn
                if (a % 16 == 3)    Grid[3] = Value[a];       // 서명
                if (a % 16 == 4)    Grid[4] = Value[a];       // 저자
                if (a % 16 == 5)    Grid[5] = Value[a];       // 출판사
                if (a % 16 == 6)    Grid[6] = Value[a];       // user
                if (a % 16 == 7)    Grid[7] = Value[a];       // date
                if (a % 16 == 8)    Grid[8] = ChangeGrade(Value[a]);       // grade
                if (a % 16 == 9)    Grid[9] = Value[a];       // 008tag
                if (a % 16 == 10)   MarcData[0] = Value[a];   // marc
                if (a % 16 == 11)   MarcData[1] = Value[a];   // marc_chk
                if (a % 16 == 12)   MarcData[2] = Value[a];   // marc1
                if (a % 16 == 13)   MarcData[3] = Value[a];   // marc_chk1
                if (a % 16 == 14)   MarcData[4] = Value[a];   // marc2
                if (a % 16 == 15) { MarcData[5] = Value[a];   // marc_chk2
                    Grid[10] = RealMarc(MarcData);
                    dataGridView1.Rows.Add(Grid);
                    progressBar1.Value += 1;
                }
            }
        
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string compidx = dataGridView1.Rows[a].Cells["compidx"].Value.ToString();
                string grade = dataGridView1.Rows[a].Cells["grade"].Value.ToString();
                string savedate = dataGridView1.Rows[a].Cells["date"].Value.ToString();
        
                bool isMyData = true;
        
                if (compidx != PUB.user.CompanyIdx) { 
                    isMyData = false;
                    string FindCompCmd = string.Format("SELECT `comp_name` FROM `Comp` WHERE `idx` = {0}", compidx);
                    dataGridView1.Rows[a].Cells["user"].Value = db.DB_Send_CMD_Search(FindCompCmd).Replace("|", "");
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.LightGray;
                }
        
                dataGridView1.Rows[a].DefaultCellStyle.ForeColor = SetGradeColor(grade, isMyData);
                SaveDataCheck(savedate, a);
            }
        }

        private string ChangeGrade(string Grade)
        {
            switch (Grade)
            {
                case "0":
                    return "A";
                case "1":
                    return "B";
                case "2":
                    return "C";
                case "3":
                    return "D";

                case "A":
                    return "0";
                case "B":
                    return "1";
                case "C":
                    return "2";
                case "D":
                    return "3";

                default:
                    return "D";
            }
        }

        private Color SetGradeColor(string Grade, bool isMyData = true)
        {
            if (!isMyData)
                return Color.Orange;

            switch (Grade)
            {
                case "A":
                    return Color.Blue;
                case "B":
                    return Color.Black;
                case "C":
                    return Color.Gray;
                case "D":
                    return Color.Red;

                default:
                    return Color.Black;
            }
        }

        private void SaveDataCheck(string Date, int row)
        {
            DateTime SaveDate = DateTime.ParseExact(Date, "yyyy-MM-dd HH:mm:ss",
                System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
            DateTime TargetDate = DateTime.Today.AddDays(-14);

            int result = DateTime.Compare(SaveDate, TargetDate);

            if (result >= 0)   // SaveDate가 같거나 큼
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.Yellow;

            else               // TargetDate가 큼
                dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.White;
        }

        private string RealMarc(string[] MarcData)
        {
            string result = "";
            if (MarcData[1] == "1")
                result = MarcData[0];

            if (MarcData[3] == "1")
                result = MarcData[2];

            if (MarcData[5] == "1")
                result = MarcData[4];

            return result;
        }

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

            if (row < 0) return;

            view_Marc(row);

            st.Color_change("▼", richTextBox1);
            st.Color_change("▲", richTextBox1);
        }

        /// <summary>
        /// 마크데이터가 있는지 확인하고 메모장으로 출력
        /// </summary>
        /// <param name="row">해당 데이터의 row값</param>
        /// <returns></returns>
        void view_Marc(int row)
        {
            // 마크 데이터
            string Marc_data = dataGridView1.Rows[row].Cells["marc"].Value.ToString();

            if (Marc_data.Length < 3) return;

            string result = string.Empty;

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

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

            int startidx = 0;
            string[] data = Marc_data.Substring(24).Split('▲'); // 리더부를 제외한 디렉터리, 가변길이필드 저장

            // List에 필요한 데이터 집어넣는 작업.
            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";
            }
            richTextBox1.Text = result;
            return;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            if (cp != null)
            {
                string[] GridData = {
                    dataGridView1.Rows[row].Cells["idx"].Value.ToString(),
                    dataGridView1.Rows[row].Cells["marc"].Value.ToString()
                };
                cp.SelectMarc_Sub(row, GridData);

                return;
            }
            SelectMarc(row);
        }

        void SelectMarc(int row)
        {
            string[] GridData = {
                dataGridView1.Rows[row].Cells["idx"].Value.ToString(),
                dataGridView1.Rows[row].Cells["compidx"].Value.ToString(),
                dataGridView1.Rows[row].Cells["user"].Value.ToString(),
                ChangeGrade(dataGridView1.Rows[row].Cells["grade"].Value.ToString()),
                dataGridView1.Rows[row].Cells["date"].Value.ToString(),
                dataGridView1.Rows[row].Cells["tag008"].Value.ToString(),
                dataGridView1.Rows[row].Cells["marc"].Value.ToString()
            };

            if (m != null)
                m.SelectMarc_Sub(MarcFormRowIndex, GridData);


            if (am != null)
            {
                string Marc = richTextBox1.Text;
                string isbn = dataGridView1.Rows[row].Cells["isbn"].Value.ToString();
                am.SelectMarc_Sub(Marc, isbn, GridData);
            }
            this.Close();
        }

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

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell.RowIndex < -1)
                return;

            int row = dataGridView1.CurrentCell.RowIndex;

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

            string User = PUB.user.UserName;
            string compidx = PUB.user.CompanyIdx;
            string NowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string SelectArea = "`compidx`, `grade`, `ISBN`, `서명`, `총서명`, " +
                                "`저자`, `출판사`, `출판년월`, `가격`, `008tag`, " +
                                "`division`, `user`, `비고1`, `비고2`, `url`, " +
                                "`marc`, `marc_chk`, `marc1`, `marc_chk1`, `marc2`, `marc_chk2`";

            string SelectCMD = string.Format("SELECT {0} FROM {1} WHERE `idx` = {2};", SelectArea, "Marc", idx);
            string SelectRes = db.self_Made_Cmd(SelectCMD);
            string[] SelectAry = SelectRes.Split('|');

            if (SelectAry[0] != compidx)
            {
                UTIL.MsgE("해당 마크를 삭제할 권한이 없습니다.");
                return;
            }

            if (UTIL.MsgQ("삭제하시겠습니까?") == DialogResult.Cancel)
                return;

            string[] InsertCol = {
                "compidx", "grade", "ISBN", "서명", "총서명",
                "저자", "출판사", "출판년월", "가격", "008tag",
                "division", "user", "비고1", "비고2", "url",
                "date", "user_Del", "marc"
            };

            string marc = "";

            if (SelectAry[16] == "1")
                marc = SelectAry[15];
            else if (SelectAry[18] == "1")
                marc = SelectAry[17];
            else if (SelectAry[20] == "1")
                marc = SelectAry[19];

            string[] InsertData = {
                SelectAry[0], SelectAry[1], SelectAry[2], SelectAry[3], SelectAry[4],
                SelectAry[5], SelectAry[6], SelectAry[7], SelectAry[8], SelectAry[9],
                SelectAry[10], SelectAry[11], SelectAry[12], SelectAry[13], SelectAry[14],
                NowDate, User, marc
            };

            string InsertCmd = db.DB_INSERT("Marc_Del", InsertCol, InsertData);
            Helper_DB.ExcuteNonQuery(InsertCmd);

            string DeleteCmd = string.Format("DELETE FROM `Marc` WHERE `idx` = {0};", idx);
            Helper_DB.ExcuteNonQuery(DeleteCmd);

            dataGridView1.Rows.Remove(dataGridView1.Rows[row]);
        }

        private void btn_ShowDeleteMarc_Click(object sender, EventArgs e)
        {
            ShowDeleteMarc showDeleteMarc = new ShowDeleteMarc();
            showDeleteMarc.Show();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                if (dataGridView1.CurrentCell.RowIndex < 0)
                    return;

                int row = dataGridView1.CurrentCell.RowIndex;
                SelectMarc(row);
            }
        }
    }
}
