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_Add2 : Form
    {
        Helper_DB db = new Helper_DB();
        Skill_Grid sg = new Skill_Grid();
        BindingSource bs1 = new BindingSource();
        BindingList<BookGridItem> bookList = new BindingList<BookGridItem>();
        Mac_List ml;

        public Mac_List_Add2(Mac_List _ml)
        {
            InitializeComponent();
            ml = _ml;

            bs1.DataSource = bookList;
            dataGridView1.DataSource = bs1;
        }

        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 = "";
            bookList.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}" };

            foreach (var item in bookList)
            {
                if (string.IsNullOrEmpty(item.BookName))
                    continue;

                string header = item.header ?? "";
                string num = item.num ?? "";
                string bookname = item.BookName ?? "";
                string author = item.Author ?? "";
                string bookcomp = item.BookComp ?? "";
                string price = (item.Price ?? "0").Replace(",", "");
                string count = (item.Count ?? "1").Replace(",", "");
                string total = (item.Total ?? "0").Replace(",", "");
                string isbn = item.ISBN ?? "";

                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);

                int cVal = 0;
                int.TryParse(count, out cVal);
                TotalCount += cVal;

                InBook_List.Add(tmp);
            }

            if (InBook_List.Count == 0)
            {
                UTIL.MsgE("저장할 데이터가 없습니다.");
                return;
            }

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

            long listIdxLong = Helper_DB.DB_Send_CMD_Insert_GetIdx(InList_Cmd);
            if (listIdxLong == -1)
            {
                UTIL.MsgE("목록 저장에 실패했습니다.");
                return;
            }
            string listIdx = listIdxLong.ToString();
            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);

            var rlt = Helper_DB.ExcuteNonQuery(InBook_Cmd);
            if (rlt.applyCount == 0)
            {
                UTIL.MsgE($"내역 저장에 실패했습니다.\n{rlt.errorMessage}");
                return;
            }

            AR.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;
        }

        #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;

            if (string.IsNullOrEmpty(FilePath)) return;

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

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

            if (textValue.Length == 0)
                return;

            try
            {
                bookList.Clear();
                foreach (string Value in textValue)
                {
                    string[] grid = Value.Split(Gubun);
                    var item = new BookGridItem();
                    if (grid.Length > 0) item.header = grid[0];
                    if (grid.Length > 1) item.num = grid[1];
                    if (grid.Length > 2) item.BookName = grid[2];
                    if (grid.Length > 3) item.Author = grid[3];
                    if (grid.Length > 4) item.BookComp = grid[4];
                    if (grid.Length > 5) item.Count = grid[5];
                    if (grid.Length > 6) item.Price = grid[6];
                    if (grid.Length > 7) item.Total = grid[7];
                    if (grid.Length > 8) item.ISBN = grid[8];

                    bookList.Add(item);
                }
            }
            catch (Exception ex)
            {
                UTIL.MsgE("오류가 발생했습니다.\n" + ex.Message);
            }
        }

        private void btn_DelRow_Click(object sender, EventArgs e)
        {
            if (bs1.Current == null) return;

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

            bs1.RemoveCurrent();
        }

        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)
        {
            Excel_to_BindingSource(sender, e);
        }

        private void Excel_to_BindingSource(object sender, KeyEventArgs e)
        {
            if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V))
            {
                if (Clipboard.ContainsText() == false) return;

                string stringInClipboard = Clipboard.GetText();
                if (string.IsNullOrEmpty(stringInClipboard)) return;

                string[] rowSplitter = { "\r\n", "\r", "\n" };
                char[] columnSplitter = { '\t' };

                List<string> rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.None).ToList();
                if (rowsInClipboard.Count > 0 && string.IsNullOrEmpty(rowsInClipboard.Last()))
                {
                    rowsInClipboard.RemoveAt(rowsInClipboard.Count - 1);
                }

                if (rowsInClipboard.Count == 0) return;

                int startRow = dataGridView1.SelectedCells.Count > 0 ? dataGridView1.SelectedCells[0].RowIndex : 0;
                int startCol = dataGridView1.SelectedCells.Count > 0 ? dataGridView1.SelectedCells[0].ColumnIndex : 0;

                bookList.RaiseListChangedEvents = false;

                for (int iRow = 0; iRow < rowsInClipboard.Count; iRow++)
                {
                    int targetRowIdx = startRow + iRow;
                    
                    // 필요한 경우 행 추가
                    while (bookList.Count <= targetRowIdx)
                    {
                        bookList.Add(new BookGridItem());
                    }

                    BookGridItem item = bookList[targetRowIdx];
                    string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);

                    for (int iCol = 0; iCol < valuesInRow.Length; iCol++)
                    {
                        int targetColIdx = startCol + iCol;

                        if (targetColIdx < dataGridView1.ColumnCount)
                        {
                            string val = valuesInRow[iCol];
                            string colName = dataGridView1.Columns[targetColIdx].DataPropertyName;

                            switch (colName)
                            {
                                case "header": item.header = val; break;
                                case "num": item.num = val; break;
                                case "BookName": item.BookName = val; break;
                                case "Author": item.Author = val; break;
                                case "BookComp": item.BookComp = val; break;
                                case "Count": item.Count = val; break;
                                case "Price": item.Price = val; break;
                                case "Total": item.Total = val; break;
                                case "ISBN": item.ISBN = val; break;
                            }
                        }
                    }
                }

                bookList.RaiseListChangedEvents = true;
                bookList.ResetBindings();
            }
        }

        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();
        }
    }
}
