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 System.IO;
using Microsoft.Office.Interop.Excel;
using UniMarc.ListOfValue;
using AR;

namespace UniMarc
{
    public partial class Mac_List_Add : Form
    {
        Helper_DB db = new Helper_DB();
        Skill_Grid sg = new Skill_Grid();
        Mac_List ml;

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

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

            string compidx = PUB.user.CompanyIdx;
            string MyName = PUB.user.UserName;

            #region 콤보박스 채우기

            // 담당자
            string CompQuery = string.Format("SELECT `comp_name` FROM `Comp` WHERE `idx` = {0}", compidx);
            string cmd = string.Format("SELECT `name` FROM `User_Data` WHERE `affil` = ({0});", CompQuery);
            string[] cmdResult = db.DB_Send_CMD_Search(cmd).Split('|');

            foreach (string UserName in cmdResult)
            {
                if (UserName != "")
                    cb_User.Items.Add(UserName);
            }

            cb_User.SelectedItem = MyName;

            // 쉼표구분
            string[] Gubun = { "tap", ",", "|" };
            cb_Gubun.Items.AddRange(Gubun);
            cb_Gubun.SelectedIndex = 0;
            #endregion
        }

        private void Delivery_TextChanged(object sender, EventArgs e)
        {
            string divComp = tb_divComp.Text;
            string divName = tb_divName.Text;

            string ListName = string.Format("[{0}]{1}", divComp, divName);
            tb_ExpectList.Text = ListName;
        }

        private void btn_Empty_Click(object sender, EventArgs e)
        {
            tb_divComp.Text = "";
            tb_divName.Text = "";
            dataGridView1.Rows.Clear();
        }

        private void btn_AddList_Click(object sender, EventArgs e)
        {
            string compidx = PUB.user.CompanyIdx;
            string Today = DateTime.Now.ToString("yyyy-MM-dd");
            string listName = tb_ExpectList.Text;
            string charge = cb_User.Text;

            int custidx = -1;
            if (int.TryParse(tbCustomIDX.Text, out custidx) == false)
            {
                UTIL.MsgE("납품처를 올바르게 선택하세요");
                tb_divComp.Focus();
                tb_divComp.SelectAll();
                return;
            }

            if (!CopyCheck(compidx, listName, Today))
            {
                UTIL.MsgE("목록이 중복되었습니다! 다시 확인해주세요.");
                return;
            }
            if (listName.isEmpty())
            {
                UTIL.MsgE("목록명이 비어있습니다! 다시 확인해주세요.");
                return;
            }

            string InBook_Area = "`compidx`, `list_name`, `date`, `header`, `num`, " +
                                 "`book_name`, `author`, `book_comp`, `pay`, `count`, " +
                                 "`total`, `isbn_marc`, `l_idx`";
            List<string> InBook_List = new List<string>();

            int TotalCount = 0;
            string InList_Idx = "㏓InList_Idx♠";

            string[] InList_Tbl = { "comp_num", "date", "list_name", "m_charge", "state", "vol", "chk_marc", "customer" };
            string[] InList_Col = { compidx, Today, listName, charge, "진행", TotalCount.ToString(), "1", $"{custidx}" };

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                GridNotNull(a);

                if (dataGridView1.Rows[a].Cells["BookName"].Value.ToString() == "")
                    break;

                string header = dataGridView1.Rows[a].Cells["header"].Value.ToString();
                string num = dataGridView1.Rows[a].Cells["num"].Value.ToString();
                string bookname = dataGridView1.Rows[a].Cells["BookName"].Value.ToString();
                string author = dataGridView1.Rows[a].Cells["Author"].Value.ToString();
                string bookcomp = dataGridView1.Rows[a].Cells["BookComp"].Value.ToString();
                string price = dataGridView1.Rows[a].Cells["Price"].Value.ToString().Replace(",", "");
                string count = dataGridView1.Rows[a].Cells["Count"].Value.ToString().Replace(",", "");
                string total = dataGridView1.Rows[a].Cells["Total"].Value.ToString().Replace(",", "");
                string isbn = dataGridView1.Rows[a].Cells["ISBN"].Value.ToString();

                string tmp = string.Format(
                    "(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\", " +
                    "\"{5}\", \"{6}\", \"{7}\", \"{8}\", \"{9}\", " +
                    "\"{10}\", \"{11}\", \"{12}\")",
                    compidx, listName, Today, header, num,
                    bookname, author, bookcomp, price, count,
                    total, isbn, InList_Idx);

                TotalCount += Convert.ToInt32(count);

                InBook_List.Add(tmp);
            }

            InList_Col[5] = TotalCount.ToString();
            string InList_Cmd = db.DB_INSERT("Obj_List", InList_Tbl, InList_Col);

            Helper_DB.ExcuteNonQuery(InList_Cmd);

            string listIdx = db.DB_Send_CMD_Search(db.More_DB_Search("Obj_List", InList_Tbl, InList_Col, "`idx`")).Replace("|", "");
            string InBook_Col = string.Join(", ", InBook_List).Replace(InList_Idx, listIdx);
            string InBook_Cmd = string.Format("INSERT INTO `Obj_List_Book` ({0}) VALUES {1};", InBook_Area, InBook_Col);

            Helper_DB.ExcuteNonQuery(InBook_Cmd);

            UTIL.MsgI("저장되었습니다!");
            ml.btn_Lookup_Click(null, null);
        }

        #region AddList_Sub

        /// <summary>
        /// INSERT할 목록 중복체크
        /// </summary>
        /// <param name="compidx"></param>
        /// <param name="listName"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        bool CopyCheck(string compidx, string listName, string date)
        {
            string cmd = string.Format(
                "SELECT `list_name` " +
                "FROM `Obj_List` " +
                "WHERE `comp_num` = \"{0}\" " +
                "AND `list_name` = \"{1}\" " +
                "AND `date` = \"{2}\";", compidx, listName, date);
            string cmdResult = db.DB_Send_CMD_Search(cmd);

            if (cmdResult.Length > 2)
                return false;

            return true;
        }

        /// <summary>
        /// Grid에서 Null인 부분을 ""로 바꿔줌
        /// </summary>
        /// <param name="row">rowIndex</param>
        void GridNotNull(int row)
        {
            for (int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                if (a == 5 || a == 7)
                {
                    if (dataGridView1.Rows[row].Cells[a].Value == null)
                        dataGridView1.Rows[row].Cells[a].Value = "0";
                }

                else if (a == 6)
                {
                    if (dataGridView1.Rows[row].Cells[a].Value == null)
                        dataGridView1.Rows[row].Cells[a].Value = "1";
                }

                else if (dataGridView1.Rows[row].Cells[a].Value == null)
                    dataGridView1.Rows[row].Cells[a].Value = "";
            }
        }

        #endregion

        private void btn_Upload_Click(object sender, EventArgs e)
        {
            string FilePath = "";
            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                FilePath = openFileDialog1.FileName;

            string[] textValue = File.ReadAllLines(FilePath);

            char Gubun = cb_Gubun.Text[0];
            if (cb_Gubun.SelectedIndex == 0)
            {
                Gubun = '\t';
            }

            if (textValue.Length < 0)
                return;
            try
            {
                foreach (string Value in textValue)
                {
                    string[] grid = Value.Split(Gubun);
                    dataGridView1.Rows.Add(grid);
                }
            }
            catch (Exception ex)
            {
                UTIL.MsgE("오류가 발생했습니다.\n" + ex.Message);
            }
        }

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

            int row = dataGridView1.CurrentCell.RowIndex;

            if (row < 0) return;

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

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

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

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            sg.Excel_to_DataGridView(sender, e);
        }

        private void label1_Click(object sender, EventArgs e)
        {
            LovCustom();
        }
        void LovCustom()
        {
            string compidx = PUB.user.CompanyIdx;
            var inputsearch = tb_divComp.Text.Trim();
            var where = $"campanyidx={compidx}";
            if (inputsearch.isEmpty() == false)
            {
                where += $" and c_sangho like '%{inputsearch.Replace("'", "''")}%'";
            }
            var dt = Helper_DB.ExecuteQueryData("Client", columns: "idx,c_sangho", orders: "c_sangho", wheres: where);
            using (var f = new fSelectDT(dt))
                if (f.ShowDialog() == DialogResult.OK)
                {
                    var dr = f.SelectedRow;
                    if (dr == null) return;
                    tbCustomIDX.Text = dr["idx"]?.ToString() ?? string.Empty;
                    tb_divComp.Text = dr["c_sangho"]?.ToString() ?? string.Empty;
                    tb_divName.Focus(); //납품명으로 커서 이동
                }
        }

        private void tb_divComp_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) LovCustom();
        }
    }
}
