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 System.Reflection;
using System.Text.RegularExpressions;
using System.IO;
using AR;

namespace UniMarc
{
    public partial class Check_ISBN_Yes242 : Form
    {
        Helper_DB db = new Helper_DB();
        Check_ISBN2 isbn;

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

        public Check_ISBN_Yes242(Check_ISBN2 _isbn)
        {
            InitializeComponent();
            isbn = _isbn;
        }

        private void Check_ISBN_Yes24_Load(object sender, EventArgs e)
        {
            db.DBcon();
            Take_DataBase();
            Base_Setting();
        }
        #region Load_Sub
        private void Take_DataBase()
        {
            string area = "`target`, `before`, `after`";
            string cmd = db.DB_Select_Search(area, "yes24");
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] ary_tmp = db_res.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 = isbn.dataGridView1.Rows.Count;

            for (int a = 0; a < count; a++)
            {
                string book_name = isbn.dataGridView1.Rows[a].Cells["book_name"].Value.ToString();
                string author = isbn.dataGridView1.Rows[a].Cells["author"].Value.ToString();
                string book_comp = isbn.dataGridView1.Rows[a].Cells["book_comp"].Value.ToString();
                string unit = isbn.dataGridView1.Rows[a].Cells["unit"].Value.ToString();
                string[] grid = {
                    book_name, Replace_target(book_name, "book_name"),
                    author, Replace_target(author, "author"),
                    book_comp, Replace_target(book_comp, "book_comp"),
                    unit
                };
                dataGridView1.Rows.Add(grid);
            }
            dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Bisque;
            dataGridView1.Columns[1].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
            dataGridView1.Columns[2].DefaultCellStyle.BackColor = Color.Bisque;
            dataGridView1.Columns[3].DefaultCellStyle.BackColor = Color.FromArgb(234, 226, 202);
            dataGridView1.Columns[4].DefaultCellStyle.BackColor = Color.Bisque;
            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];
            for(int a= 0; a < dataGridView1.Rows.Count; a++)
            {
                int count = a + 1;
                string price = dataGridView1.Rows[a].Cells["price"].Value.ToString();
                grid[a, 0] = count.ToString();
                grid[a, 1] = dataGridView1.Rows[a].Cells["after_book_name"].Value.ToString();
                grid[a, 2] = dataGridView1.Rows[a].Cells["after_author"].Value.ToString();
                grid[a, 3] = dataGridView1.Rows[a].Cells["after_book_comp"].Value.ToString();
                grid[a, 4] = Regex.Replace(price, @"[^0-9]", "");
                grid[a, 5] = "1";
            }
            Excel_change(grid);
        }

        #region 엑셀변환 서브

        private void Excel_change(string[,] grid)
        {
            string DesktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop);       // 바탕화면 경로
            string FilePath =
                Path.Combine(DesktopPath, "Excel.xlsx");                            // 엑셀 파일 저장 경로
            try
            {
                Excel.Application application = new Excel.Application();
                application.Visible = true;
                application.Interactive = false;

                Excel._Workbook wb = application.Workbooks.Add(Missing.Value);
                Excel._Worksheet ws = (Excel._Worksheet)application.ActiveSheet;

                Excel.Range rng = null;

                #region 엑셀 베이스 (너비 높이)
                ws.Columns[1].ColumnWidth = 6.57;
                ws.Columns[2].ColumnWidth = 43.86;
                ws.Columns[3].ColumnWidth = 18.43;
                ws.Columns[4].ColumnWidth = 22.57;
                ws.Columns[5].ColumnWidth = 12.57;
                #endregion

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

                #region 내용 삽입
                rng = ws.Range["A1", "F1"];
                rng.Value2 = title;
                rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                rng.Font.Bold = true;

                int count = dataGridView1.Rows.Count + 1;
                rng = ws.Range["A2", "F" + count.ToString()];
                rng.Value2 = grid;
                rng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                #endregion

                application.Interactive = true;
            }
            catch (Exception e) { UTIL.MsgE(e.Message); }
        }
        #endregion

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

        private void btn_Yes24Connect_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://www.yes24.com/Mall/CorpLargeOrder/CorpMain");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url = webBrowser1.Url.AbsoluteUri;

            if (url.IndexOf("yes24.com/Main") > -1)
                webBrowser1.Navigate("http://www.yes24.com/Mall/CorpLargeOrder/CorpMain");

            if (url.IndexOf("CorpLargeOrder/CorpMain") > -1)
                if (isLogin())
                    webBrowser1.Navigate("https://www.yes24.com/Templates/FTLogin.aspx");
                else
                    ExcelUpLoadSearch();

            if (url.IndexOf("FTLogin") > -1)
                Login();
        }

        #region DocumentCompleted Sub

        bool isLogin()
        {
            string InnerText = "";

            foreach (HtmlElement li in webBrowser1.Document.GetElementsByTagName("li"))
            {
                if (li.Id == null)
                    continue;

                if (li.Id.IndexOf("LoginText") > -1)
                {
                    if (li.InnerText.IndexOf("로그") > -1)
                    {
                        InnerText = li.InnerText;
                        break;
                    }
                }
            }

            if (InnerText.IndexOf("로그인") > -1)
                return true;

            return false;
        }

        void ExcelUpLoadSearch()
        {
            webBrowser1.Navigate("http://www.yes24.com/Mall/CorpLargeOrder/ExcelUploadSearch");
        }

        void Login()
        {
            foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
            {
                if (input.Id == null)
                    continue;

                if (input.Id == "SMemberID")
                    input.SetAttribute("value", tb_ID.Text);

                if (input.Id == "SMemberPassword")
                    input.SetAttribute("value", tb_PW.Text);
            }

            foreach (HtmlElement btn in webBrowser1.Document.GetElementsByTagName("button"))
            {
                if (btn.Id == null)
                    continue;

                if (btn.Id.IndexOf("btnLogin") > -1)
                    btn.InvokeMember("click");
            }
        }
        #endregion

        private void webBrowser1_FileDownload(object sender, EventArgs e)
        {
            UTIL.MsgI("You are in the WebBrowser. FileDownload event.");
        }
    }
}
