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 DLS_Lookup : Form
    {
        Main main;
        public string compidx;
        public DLS_Lookup(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }

        #region SHDocVw
        SHDocVw.WebBrowser nativeBrowser;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            nativeBrowser = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
            nativeBrowser.NewWindow2 += nativeBrowser_NewWindow2;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            nativeBrowser.NewWindow2 -= nativeBrowser_NewWindow2;
            base.OnFormClosing(e);
        }

        void nativeBrowser_NewWindow2(ref object ppDisp, ref bool Cancel)
        {
            var popup = new DLS_Manage();
            popup.Show(this);
            ppDisp = popup.Browser.ActiveXInstance;
        }
        #endregion

        private void School_Lookup_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://reading.jnei.go.kr");
        }

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

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

        private void tb_SearchClient_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // 검색 함수
                ClientSearch();
            }
        }
        #region KeyDown SUB

        private void ClientSearch()
        {
            Commodity_Search cs = new Commodity_Search(this);
            cs.Clinet_name = tb_SearchClient.Text;
            cs.Show();
        }
        #endregion

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            if (lbl_Client.Text == "Client")
            {
                UTIL.MsgE("납품처명을 선택해주세요");
                return;
            }
            if (lbl_Area.Text == "")
            {
                UTIL.MsgE("설정된 지역이 없습니다. 납품처 관리에서 확인해주세요.");
                return;
            }

            string url = webBrowser1.Url.AbsoluteUri;

            webBrowser1.Document.GetElementById("headerLoginBtn").InvokeMember("click");

            Delay(5000);

            DLS_Login(url);
        }
        #region Connect_SUB

        private void DLS_Login(string url)
        {
            if (lbl_ID.Text == "" || lbl_PW.Text == "")
            {
                UTIL.MsgE("ID 혹은 PW가 없습니다.");
                return;
            }
            string ID = lbl_ID.Text, PW = lbl_PW.Text;
            url = webBrowser1.Document.GetElementById(SetArea(lbl_Area.Text)).GetAttribute("value");

            webBrowser1.Document.GetElementById("s_id").SetAttribute("value", ID);
            webBrowser1.Document.GetElementById("s_pwd").SetAttribute("value", PW);

            webBrowser1.Document.GetElementById("s_login").InvokeMember("click");

            Delay(4000);
            webBrowser1.Navigate(url + "/r/dls_new/bookInfo/collectionFormMA.jsp");
        }
        #endregion

        /// <summary>
        /// DLS지역 코드 변환
        /// </summary>
        /// <returns>코드</returns>
        public string SetArea(string dlsArea, bool move = false)
        {
            string[] Area = {
                "서울", "부산", "대구", "인천", "광주",
                "대전", "울산", "세종", "경기", "강원",
                "충북", "충남", "전북", "전남", "경북",
                "경남", "제주"
            };

            string[] Code = {
                "SU", "BS", "DG", "IC", "KJ",
                "DJ", "US", "SJ", "KG", "KW",
                "CB", "CN", "JB", "JN", "KB",
                "KN", "JJ"
            };

            int idx = 0;
            foreach (string code in Area)
            {
                if (code == dlsArea)
                    break;

                idx++;
            }

            if (move)
            {
                var areacode = Code[idx];
                if(webBrowser1.Document == null)
                {
                    UTIL.MsgE("웹브라우저가 준비되지 않아 URL을 이동할 수 없습니다");
                }
                else
                {
                    var elm = webBrowser1.Document.GetElementById(areacode);
                    var val = elm.GetAttribute("value");
                    webBrowser1.Navigate(val);
                }
                 
            }
                

            return Code[idx];
        }

        /// <summary>
        /// 지연시키는 함수
        /// </summary>
        /// <param name="ms">1000 = 1초</param>
        void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);
            while (dateTimeAdd >= dateTimeNow)
            {
                Application.DoEvents();
                dateTimeNow = DateTime.Now;
            }
            return;
        }

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

        private void btn_Back_Click(object sender, EventArgs e)
        {
            webBrowser1.GoBack();
        }

        private void btn_Forward_Click(object sender, EventArgs e)
        {
            webBrowser1.GoForward();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            tb_URL.Text = webBrowser1.Url.AbsoluteUri;
        }

        private void tb_URL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string url = tb_URL.Text;
                webBrowser1.Navigate(url);
            }
        }
    }
}
