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 Mac_List_Merge : Form
    {
        Mac_List ml;
        Helper_DB db = new Helper_DB();
        Skill_Grid skill = new Skill_Grid();

        public string ListState = "";
        string date = DateTime.Now.ToString("yyyy-MM-dd");

        public Mac_List_Merge(Mac_List _ml)
        {
            InitializeComponent();
            ml = _ml;
        }

        private void Mac_List_Merge_Load(object sender, EventArgs e)
        {
            lbl_charge.Text = PUB.user.UserName;
            lbl_state.Text = ListState;

            db.DBcon();
            data_Input();
        }

        void data_Input()
        {
            string[] input_data = { "", "", "", "" };
            int count = ml.dataGridView1.Rows.Count;
            for(int a = 0; a < count; a++)
            {
                if (ml.dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    input_data[0] = ml.dataGridView1.Rows[a].Cells["idx"].Value.ToString();
                    input_data[1] = ml.dataGridView1.Rows[a].Cells["list_name"].Value.ToString();
                    input_data[2] = ml.dataGridView1.Rows[a].Cells["start_date"].Value.ToString();
                    input_data[3] = ml.dataGridView1.Rows[a].Cells["count"].Value.ToString();
                    dataGridView1.Rows.Add(input_data);
                }
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            skill.Print_Grid_Num(sender, e);
        }

        private void tb_list_name_Click(object sender, EventArgs e)
        {
            if (tb_list_name.Text == "설정할 목록명") {
                tb_list_name.Text = "";
            }
        }

        private void btn_Merge_Click(object sender, EventArgs e)
        {
            if (!rb_Delete.Checked && !rb_Keep.Checked) {
                UTIL.MsgE("기존목록의 유지여부를 선택해주세요.");
                return;
            }
            if (tb_list_name.Text == "변경할 작업처의 이름") {
                UTIL.MsgE("작업처의 이름을 입력해주세요.");
                return;
            }
            if (!chk_Overlap()) {
                UTIL.MsgE("작업처의 이름이 중복됩니다. 다시 설정해주세요.");
                return;
            }
            
            // 이 밑으론 DB적용사항. 기존목록유지시 INSERT만 / 기존목록삭제시 INSERT이후 기존목록DELETE
            data_Insert();
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                book_Insert(a);
            }

            if (rb_Delete.Checked) {
                // 기존 목록 삭제 함수
                data_delete();
            }

            UTIL.MsgI("목록이 병합되었습니다.");
            ml.btn_Lookup_Click(null, null);
            this.Close();
        }

        void data_Insert()
        {
            string table = "Obj_List";
            string start = date;
            string end = end_date.Value.ToString().Substring(0, 10);

            string[] in_col = {
                "comp_num", "date", "date_res", "list_name", "m_charge",
                "vol","state", "m_etc", "chk_marc"
            };
            string[] in_data = {
                ml.compidx, start, end, tb_list_name.Text, lbl_charge.Text,
                cal_Total("vol").ToString(), lbl_state.Text, rtb_etc.Text, "1"
            };
            string Incmd = db.DB_INSERT(table, in_col, in_data);

            Helper_DB.ExcuteNonQuery(Incmd);
        }

        void book_Insert(int row)
        {
            string table = "Obj_List_Book";

            string Area = "`compidx`, `header`, `num`, `isbn_marc`, `book_name`, `author`, `book_comp`, `pay`, `count`, `total`";

            string[] sear_col = {
                "compidx",
                "list_name",
                "date"
            };
            string[] sear_data = {
                ml.compidx,
                dataGridView1.Rows[row].Cells["list_name"].Value.ToString(),
                dataGridView1.Rows[row].Cells["list_date"].Value.ToString()
            };

            string cmd = db.More_DB_Search(table, sear_col, sear_data, Area);
            string[] Search_Data = db.DB_Send_CMD_Search(cmd).Split('|');

            List<string> tmpList = new List<string>();

            for (int a = 0; a < Search_Data.Length; a++)
            {
                if (a % 10 == 9)
                {
                    string tmpString = string.Format(
                        "(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\", " +
                        "\"{5}\", \"{6}\", \"{7}\", \"{8}\", \"{9}\", " +
                        "\"{10}\", \"{11}\", \"{12}\")",
                        Search_Data[a - 9], Search_Data[a - 8], Search_Data[a - 7], tb_list_name.Text, date,
                        Search_Data[a - 6], Search_Data[a - 5], Search_Data[a - 4], Search_Data[a - 3], Search_Data[a - 2],
                        Search_Data[a - 1], Search_Data[a], Find_ListIndex());

                    tmpList.Add(tmpString);
                }
            }

            string Insert_Col =
                "`compidx`, `header`, `num`, `list_name`, `date`, " +
                "`isbn_marc`, `book_name`, `author`, `book_comp`, `pay`, " +
                "`count`, `total`, `l_idx`";
            string InsertData = string.Join(", ", tmpList);

            string InCmd = string.Format("INSERT INTO `{0}` ({1}) VALUES {2};", table, Insert_Col, InsertData);
            Helper_DB.ExcuteNonQuery(InCmd);
        }

        string Find_ListIndex()
        {
            string table = "Obj_List";
            string Area = "idx";
            string[] Col = { "comp_num", "list_name", "date" };
            string[] Data = { ml.compidx, tb_list_name.Text, date };
            string cmd = db.More_DB_Search(table, Col, Data, Area);
            return db.DB_Send_CMD_Search(cmd).Replace("|", "");
        }

        void data_delete()
        {
            string table = "Obj_List";
            string[] target_area = { "idx" };
            string[] target = { "" };
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                target[0] = dataGridView1.Rows[a].Cells["idx"].Value.ToString();
                string cmd = db.DB_Delete_More_term(table, "comp_num", ml.compidx, target_area, target);
                Helper_DB.ExcuteNonQuery(cmd);

                book_Delete(a);
            }
        }

        void book_Delete(int row)
        {
            string table = "Obj_List_Book";

            string[] target_Col = {
                "list_name", "date"
            };
            string[] targetData = {
                dataGridView1.Rows[row].Cells["list_name"].Value.ToString(),
                dataGridView1.Rows[row].Cells["list_date"].Value.ToString()
            };

            string cmd = db.DB_Delete_No_Limit(table, "compidx", ml.compidx, target_Col, targetData);
            Helper_DB.ExcuteNonQuery(cmd);
        }

        bool chk_Overlap()
        {
            string cmd = db.DB_Select_Search("list_name", "Obj_List", "comp_num", ml.compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] db_data = db_res.Split('|');

            for (int a = 0; a < db_data.Length; a++)
            {
                if (tb_list_name.Text == db_data[a])
                    return false;
            }
            return true;
        }

        /// <summary>
        /// 합계를 구하는 함수.
        /// </summary>
        /// <param name="column">현 Grid의 컬럼명</param>
        /// <returns></returns>
        int cal_Total(string column)
        {
            int result = 0;
            List<int> total = new List<int>();

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
                total.Add(Convert.ToInt32(dataGridView1.Rows[a].Cells[column].Value.ToString()));
            
            for (int a = 0; a < total.Count; a++)
                result += total[a];
            
            return result;
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}