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 Excel = Microsoft.Office.Interop.Excel;
using WindowsFormsApp1;
using System.Reflection;
using System.Text.RegularExpressions;


namespace ISBN_Check_test
{
    public partial class Yes24 : Form
    {
        Helper_DB db = new Helper_DB();
        Form1 f1;

        List<string> l_target = new List<string>();
        List<string> l_before = new List<string>();
        List<string> l_after = new List<string>();

        public Yes24(Form1 _f1)
        {
            InitializeComponent();
            f1 = _f1;
        }

        private void Yes24_Load(object sender, EventArgs e)
        {
            db.DBcon();
            Take_DataBase();
            Base_Setting();
            cb_bracket.Checked = true;
        }
        #region Yes24_Load_Sub
        private void Take_DataBase()
        {
            string area = "`target`, `before`, `after`";
            string tmp = db.DB_Select_Search(area, "yes24");
            string[] ary_tmp = tmp.Split('|');

            for (int a = 0; a < ary_tmp.Length; a++)
            {
                if (a % 3 == 0) { l_target.Add(ary_tmp[a]); }
                if (a % 3 == 1) { l_before.Add(ary_tmp[a]); }
                if (a % 3 == 2) { l_after.Add(ary_tmp[a]); }
            }
        }
        private void Base_Setting()
        {
            int count = f1.dataGridView1.Rows.Count - 1;
            string price = "";

            foreach(DataGridViewRow drowview in f1.dataGridView1.Rows)
            {
                if (drowview.Cells["price"].Value != null)
                {
                    price = drowview.Cells["price"].Value.ToString();
                }

                var bookName = drowview.Cells["book_name"].Value?.ToString() ?? string.Empty;
                var author = drowview.Cells["author"].Value?.ToString() ?? string.Empty;
                var bookComp = drowview.Cells["book_comp"].Value?.ToString() ?? string.Empty;
                if (string.IsNullOrEmpty(bookName) && string.IsNullOrEmpty(author) && string.IsNullOrEmpty(bookComp)) continue;

                List<string> grid = new List<string>();
                grid.Add(bookName);
                grid.Add(Replace_target(bookName, "book_name"));
                grid.Add(author);
                grid.Add(Replace_target(author, "author"));
                grid.Add(bookComp);
                grid.Add(Replace_target(bookComp, "book_comp"));
                grid.Add(price);
                dataGridView1.Rows.Add(grid.ToArray());

            }
            dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Bisque;
            dataGridView1.Columns[2].DefaultCellStyle.BackColor = Color.Bisque;
            dataGridView1.Columns[4].DefaultCellStyle.BackColor = Color.Bisque;
            dataGridView1.Columns[1].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
            dataGridView1.Columns[3].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
            dataGridView1.Columns[5].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
        }
        private string Replace_target(string value, string sort)
        {
            try
            {
                int start = value.IndexOf('(');
                int end = value.IndexOf(')');
                value = value.Remove(start, end - start);
                start = value.IndexOf('[');
                end = value.IndexOf(']');
                value = value.Remove(start, end - start);
                start = value.IndexOf('<');
                end = value.IndexOf('>');
                value = value.Remove(start, end - start);
            }
            catch { }

            string[] target = l_target.ToArray();
            string[] before = l_before.ToArray();
            string[] after = l_after.ToArray();

            for (int a = 0; a < before.Length; a++)
            {
                if (target[a] == sort)
                {
                    value = value.Replace(before[a], after[a]);
                }
            }
            return value;
        }
        #endregion

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

        private void btn_change_Click(object sender, EventArgs e)
        {
            string[,] grid = new string[dataGridView1.Rows.Count, 6];
            var idx = 0;
            foreach (DataGridViewRow drv in dataGridView1.Rows)// int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string price = drv.Cells["price"].Value?.ToString() ?? string.Empty;
                int count = idx + 1;
                grid[idx, 0] = count.ToString();
                grid[idx, 1] = drv.Cells["after_book_name"].Value.ToString();
                grid[idx, 3] = drv.Cells["after_book_comp"].Value.ToString();
                grid[idx, 4] = Regex.Replace(price, @"[^0-9]", "");
                grid[idx, 5] = "1";
                idx += 1;
            }
            Excel_change(grid);
        }
        #region 엑셀변환 서브
        void Excel_change(string[,] grid)
        {
            try
            {
                Excel.Application application = new Excel.Application();    // Excel Application Create
                application.Visible = true;         // true 일시 엑셀이 작업되는 내용이 보임
                application.Interactive = false;    // false일 경우 유저의 조작에 방해받지않음.

                Excel._Workbook wb = (Excel._Workbook)(application.Workbooks.Add(Missing.Value));   // 워크북 생성
                Excel._Worksheet ws = (Excel._Worksheet)application.ActiveSheet;    // 시트 가져옴

                Excel.Range rng = null;     // 셀 처리 변수

                #region 엑셀 베이스 (셀의 너비, 높이 설정)
                ws.Columns[1].ColumnWidth = 6.57;      // A
                ws.Columns[2].ColumnWidth = 43.86;     // B
                ws.Columns[3].ColumnWidth = 18.43;     // C
                ws.Columns[4].ColumnWidth = 22.57;      // D
                ws.Columns[5].ColumnWidth = 12.57;      // E
                #endregion

                string[] title = { "번호", "도서명", "ISBN", "출판사", "정가", "수량" };

                #region 제목 셀
                rng = ws.Range["A1", "F1"];
                rng.Value2 = title;
                rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                rng.Font.Bold = true;
                #endregion

                // 기본 정보 입력칸
                int count = dataGridView1.Rows.Count + 1;
                rng = ws.Range["A2", "F" + count.ToString()];
                rng.Value2 = grid;
                rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

                application.Interactive = true;

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        #endregion

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

        private void cb_bracket_CheckedChanged(object sender, EventArgs e)
        {
            int count = dataGridView1.Rows.Count;
            for (int a = 0; a < count; a++)
            {
                if (cb_bracket.Checked)
                {
                    string book_name = dataGridView1.Rows[a].Cells["before_book_name"].Value.ToString();
                    string After = Replace_target(book_name, "book_name");
                    dataGridView1.Rows[a].Cells["after_book_name"].Value = After;
                }
                else
                {

                    string book_name = dataGridView1.Rows[a].Cells["before_book_name"].Value.ToString();
                    dataGridView1.Rows[a].Cells["after_book_name"].Value = book_name;
                }
            }
        }
    }
}
