private void btnXuatExcel_Click(object sender, EventArgs e)
 {
     colDaiLyTT.GroupIndex = -1;
     XuLyGiaoDien.ExportExcel(GCSI, GVSI, "Cấp Sign-" + DateTime.Now.ToString("dd-MM-yyy"));
     colDaiLyTT.GroupIndex = 0;
     GVSI.ExpandAllGroups();
 }
        private void btnXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            O_SIGNIN si = GVSI.GetRow(GVSI.GetSelectedRows()[0]) as O_SIGNIN;

            if (si != null)
            {
                _lstSIChinh.Remove(si);
                GCSI.DataSource = null;
                GCSI.DataSource = _lstSIChinh;
                GVSI.ExpandAllGroups();
            }
        }
        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (_lstSIChinh.Where(w => w.SignIn.Equals(iSignIn.Text) && iSignIn.Text.Length > 0).Count() == 0)
            {
                GCSI.DataSource = null;
                List <KiemTra> kiemTras = new List <KiemTra>();
                kiemTras.Add(new KiemTra()
                {
                    _Control = icmb, _Tu = 1, _Den = 50
                });
                kiemTras.Add(new KiemTra()
                {
                    _Control = iHangBay, _Tu = 1, _Den = 50
                });
                kiemTras.Add(new KiemTra()
                {
                    _Control = iSignIn, _Tu = 1, _Den = 50, _ChoQuaThang = icmb.SelectedIndex == 0
                });
                XuLyGiaoDien.KiemTra(kiemTras, dxValidationProvider1);
                if (!dxValidationProvider1.Validate())
                {
                    XuLyGiaoDien.Alert("Thông tin không hợp lệ", Form_Alert.enmType.Warning);
                    return;
                }

                O_SIGNIN si = new O_SIGNIN();
                si.CanLam  = icmb.SelectedIndex;
                si.DaiLy   = (int)iIDKhachHang.EditValue;
                si.HangBay = (int)iHangBay.EditValue;
                si.SignIn  = iSignIn.Text;
                si.MatKhau = iMatKhau.Text;
                si.Chinh   = iChinh.Checked;
                _lstSIChinh.Add(si);
                GCSI.DataSource = _lstSIChinh;
                GVSI.ExpandAllGroups();
                XulyDulieuKhiThem();
                iMatKhau.Text = RandomPassword();
                iSignIn.Text  = "";
            }
        }
        private void btnNhapExcel_Click(object sender, EventArgs e)
        {
            XtraOpenFileDialog ofd = new XtraOpenFileDialog();

            ofd.Title      = "Mở File";
            ofd.Filter     = "Excel File (*.xlsx, *.xls) | *.xlsx; *.xls";
            ofd.DefaultExt = ".xlsx";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string ChuoiKetNoi = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ofd.FileName + "; Extended Properties='Excel 12.0 Xml;HDR=YES';";
                using (OleDbConnection conn = new OleDbConnection(ChuoiKetNoi))
                {
                    conn.Open();
                    DataTable        dbSchema   = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    string           CauTruyVan = "SELECT * FROM [" + dbSchema.Rows[0].Field <string>("TABLE_NAME").Replace("'", string.Empty) + ']';
                    OleDbDataAdapter da         = new OleDbDataAdapter(CauTruyVan, conn);
                    DataTable        dt         = new DataTable();
                    da.Fill(dt);
                    _lstSIChinh.Clear();
                    foreach (DataRow row in dt.Rows)
                    {
                        O_SIGNIN signInO = new O_SIGNIN();
                        signInO.DaiLy   = _lstDL.Where(w => w.TenTam.ToUpper().Equals(row[0].ToString().ToUpper())).First().ID;
                        signInO.HangBay = _lstHB.Where(w => w.TenTat.Equals(row[1].ToString())).First().ID;
                        signInO.SignIn  = ((row[2] ?? null) ?? string.Empty).ToString();
                        signInO.MatKhau = row[3].ToString();
                        signInO.Chinh   = row[4].ToString() != "False";
                        signInO.CanLam  = int.Parse(row[5].ToString());
                        signInO.End     = row[6].ToString() != "False";
                        _lstSIChinh.Add(signInO);
                    }
                    GCSI.DataSource = null;
                    GCSI.DataSource = _lstSIChinh;
                    _lstSIChinh     = _lstSIChinh.OrderBy(w => w.HangBay).OrderBy(w => w.Khoa).ToList();
                    XulyDulieuKhiThem();
                    GVSI.ExpandAllGroups();
                }
            }
        }
        private void wVJ_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (wVJ.ReadyState == WebBrowserReadyState.Complete && !wVJ.IsBusy)
            {
                HtmlElement        head     = wVJ.Document.GetElementsByTagName("head")[0];
                HtmlElement        scriptEl = wVJ.Document.CreateElement("script");
                IHTMLScriptElement element  = (IHTMLScriptElement)scriptEl.DomElement;
                if (wVJ.Url.ToString().Contains("/Login.aspx")) // Đăng nhập
                {
                    wVJ.Document.GetElementById("txtUsernameVNiSC").SetAttribute("value", "admin");
                    wVJ.Document.GetElementById("txtMatKhau").SetAttribute("value", "11223399");
                    wVJ.Document.GetElementById("txtAgentCode").SetAttribute("value", "THD");
                    SoLanDangNhap++;
                    if (SoLanDangNhap < 4)
                    {
                        dynamic body         = wVJ.Document.Body.DomElement;
                        dynamic controlRange = body.createControlRange();
                        dynamic element1     = wVJ.Document.GetElementById("imgImageValidate").DomElement;
                        controlRange.add(element1);
                        controlRange.execCommand("Copy", false, null);

                        string res = string.Empty;
RetunA:
                        try
                        {
                            res = XuLyGiaoDien.ConvertImgToText((Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap));
                            if (res.Length < 3)
                            {
                                goto RetunA;
                            }
                        }
                        catch { wVJ.Navigate("http://ags.thanhhoang.vn/Login.aspx"); }

                        if (wVJ.Document.GetElementById("RequiredFieldValidator3").OuterHtml.Contains("VISIBILITY: hidden"))
                        {
                            wVJ.Document.GetElementById("txtImageValidate").SetAttribute("value", res);
                            wVJ.Visible = true;
                            wVJ.Document.GetElementById("btnLogin").InvokeMember("click");
                        }
                        else
                        {
                            goto RetunA;
                        }
                    }
                }  // Đăng nhập
                else if (wVJ.Url.ToString().Contains("/Default.aspx") || wVJ.Url.AbsolutePath.Contains("/Booking.aspx")) //Vào trang thêm đại lý
                {
                    wVJ.Navigate("http://ags.thanhhoang.vn/Agent.aspx?Do=SubAgent");
                }
                else if (wVJ.Url.ToString().EndsWith("Agent.aspx?Do=SubAgent&Act=Add"))// Thêm đại lý
                {
                    dldl = _lstDL.Where(w => w.MaAGS.Equals(lstDLAGS[0])).First();
                    wVJ.Document.GetElementById("ctl08_txtAgentCode").SetAttribute("value", lstDLAGS[0]);
                    wVJ.Document.GetElementById("ctl08_txtAgentName").SetAttribute("value", dldl.Ten);
                    if (lstDLAGS.Count > 0)
                    {
                        if (_lstSIChinh.Where(w => w.DaiLy.Equals(dldl.ID) && w.HangBay.Equals(3) && w.Chinh).Count() > 0)
                        {
                            lstQAGS.Remove(lstDLAGS[0]);
                        }
                        lstDLAGS.Remove(lstDLAGS[0]);
                    }
                    wVJ.Document.GetElementById("ctl08_btOK").InvokeMember("click");
                }// Thêm đại lý
                else if (wVJ.Url.ToString().EndsWith("Agent.aspx?Do=SubAgent"))//Kiểm tra tồn tại đại lý
                {
                    if (lstDLAGS.Count == 0)
                    {
                        if (lstQAGS.Count == 0)
                        {
                            wVJ.Navigate("http://ags.thanhhoang.vn/Agent.aspx?Do=Ticketing");
                        }
                        else
                        {
                            wVJ.Navigate("http://ags.thanhhoang.vn/Accounting.aspx?Do=Deposit");
                        }
                    }
                    else
                    {
                        if (!ThemDaiLy)
                        {
                            HtmlElementCollection hc = wVJ.Document.GetElementsByTagName("div");
                            for (int i = 0; i < hc.Count; i++)
                            {
                                if (hc[i].GetAttribute("classname") == "item first")
                                {
                                    if (lstDLAGS.Equals(hc[i].InnerText))
                                    {
                                        lstDLAGS.Remove(hc[i].InnerText);
                                    }
                                }
                            }
                        }

                        ThemDaiLy = lstDLAGS.Count > 0;
                        if (lstDLAGS.Count > 0)
                        {
                            wVJ.Navigate("http://ags.thanhhoang.vn/Agent.aspx?Do=SubAgent&Act=Add");
                        }
                        else
                        {
                            wVJ.Navigate("http://ags.thanhhoang.vn/Agent.aspx?Do=Ticketing");
                        }
                    }
                }//Kiểm tra tồn tại đại lý
                else if (wVJ.Url.ToString().EndsWith("Accounting.aspx?Do=Deposit&Act=Add"))// Thêm quỹ
                {
                    HtmlElementCollection hc = wVJ.Document.GetElementsByTagName("option");
                    for (int i = 4; i < hc.Count; i++)
                    {
                        lstdic.Add(hc[i].InnerText);
                    }

                    int o = lstdic.FindIndex(x => x.StartsWith("0"));
                    if (o < 0)
                    {
                        XtraMessageBox.Show("Đại lý chưa được thêm trên ags", "Thông báo");
                        Dispose();
                        Close();
                    }
                    else
                    {
                        element.text = @"function doPost() { document.getElementById('ctl08_ddlSubAgent').options.item(" + o + ").selected = true; }";
                        head.AppendChild(scriptEl);
                        wVJ.Document.InvokeScript("doPost");

                        wVJ.Document.GetElementById("ctl08_txtAmount").SetAttribute("value", "20000000");
                        wVJ.Document.GetElementById("ctl08_txtDocNo").SetAttribute("value", "1");
                        wVJ.Document.GetElementById("ctl08_txtDocDate").SetAttribute("value", DateTime.Now.ToString("dd/MM/yyyy"));
                        wVJ.Document.Window.ScrollTo(0, 170);
                        Dictionary <string, object> dic = new Dictionary <string, object>();
                        dic.Add("SoCT", 2);
                        new D_DAILY().CapNhat(dic, _lstDL.Where(w => w.MaAGS.Equals(lstDLAGS[0])).First().ID);
                    }
                }// Thêm quỹ
                else if (wVJ.Url.ToString().Contains("Accounting.aspx?Do=Deposit"))
                {
                    if (lstQAGS.Count > 0)
                    {
                        wVJ.Document.GetElementById("ctl08_btnAddNew").InvokeMember("click");
                    }
                }// Thêm quỹ
                else if (wVJ.Url.ToString().EndsWith("Agent.aspx?Do=Ticketing&Act=Add"))
                {
                    dldl      = _lstDL.Where(w => w.ID.Equals(_lstSIChinh[iVN].DaiLy)).First();
                    lstMaAGSW = lstMaAGSW.OrderByDescending(w => w).ToList();
                    HtmlElementCollection hc = wVJ.Document.GetElementsByTagName("option");
                    for (int i = 4; i < hc.Count; i++)
                    {
                        lstdic.Add(hc[i].InnerText);
                    }

                    int    o  = lstdic.FindIndex(x => x.StartsWith(dldl.MaAGS));
                    string _a = "AG" + dldl.MaAGS + "1";

                    if (lstMaAGSW.Where(w => w.Contains(dldl.MaAGS)).Count() > 0)
                    {
                        string a = lstMaAGSW.Where(w => w.Contains(dldl.MaAGS)).First();
                        _a = a.Substring(0, a.Length - 1) + (int.Parse(a.Substring(a.Length - 1, 1)) + 1);
                    }

                    wVJ.Document.GetElementById("ctl08_txtTenDangNhap").SetAttribute("value", _a);
                    wVJ.Document.GetElementById("ctl08_txtMatKhau").SetAttribute("value", _lstSIChinh[iVN].MatKhau);
                    wVJ.Document.GetElementById("ctl08_chkChangePassNextLogin").InvokeMember("click");
                    wVJ.Document.GetElementById("ctl08_txtHoTen").SetAttribute("value", dldl.Ten);

                    element.text = @"function doPost() { document.getElementById('ctl08_ddlSubAgent').options.item(" + o + ").selected = true; }";
                    head.AppendChild(scriptEl);
                    wVJ.Document.InvokeScript("doPost");

                    if (_lstSIChinh[iVN].Chinh)
                    {
                        element.text = @"function doPost() { document.getElementById('ctl08_ddlPermission').options.item(1).selected = true; }";
                        head.AppendChild(scriptEl);
                        wVJ.Document.InvokeScript("doPost");
                    }
                    Invoke(new MethodInvoker(delegate()
                    {
                        _lstSIChinh[iVN].End    = true;
                        _lstSIChinh[iVN].SignIn = _a.ToString();
                        GCSI.DataSource         = null;
                        GCSI.DataSource         = _lstSIChinh;
                        GVSI.ExpandAllGroups();
                    }));
                    iVN++;
                }
                else if (wVJ.Url.ToString().EndsWith("Agent.aspx?Do=Ticketing"))
                {
                    lstMaAGSW.Clear();

                    HtmlElementCollection hc = GetElementByClass("table", "table table-bordered").GetElementsByTagName("tr");
                    for (int i = 1; i < hc.Count; i++)
                    {
                        lstMaAGSW.Add(hc[i].GetElementsByTagName("td")[1].InnerText);
                    }

                    for (; iVN < _lstSIChinh.Count; iVN++)
                    {
                        if (_lstSIChinh[iVN].End || _lstSIChinh[iVN].HangBay != 3)
                        {
                            continue;
                        }
                        else
                        {
                            wVJ.Navigate("http://ags.thanhhoang.vn/Agent.aspx?Do=Ticketing&Act=Add");
                            break;
                        }
                    }
                }
            }
        }
        void Wb()
        {
            var chromeDriverService = ChromeDriverService.CreateDefaultService();
            var options             = new ChromeOptions();
            //chromeDriverService.HideCommandPromptWindow = true;
            O_NHACUNGCAP cCO = new D_NHACUNGCAP().DuLieu().Where(w => w.Ten.Equals("VJ")).First();

            try { driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(300)); }
            catch { options.BinaryLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe"; driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(300)); }

            js   = driver as IJavaScriptExecutor;
            wait = new WebDriverWait(driver, TimeSpan.FromMinutes(5));

            for (int i = 0; i < _lstSIChinh.Count; i++)
            {
                if (_lstSIChinh[i].End || _lstSIChinh[i].HangBay != 2)
                {
                    continue;
                }

                #region VJ
                if (!driver.Url.Contains("vietjetair"))
                {
                    driver.Navigate().GoToUrl("https://www.vietjetair.com/Sites/Web/vi-VN/Home");
                    wait.Until(d => d.PageSource.Contains("https://agents.vietjetair.com/sitelogin.aspx?lang=vi"));
                    js.ExecuteScript("location.href = 'https://agents.vietjetair.com/sitelogin.aspx?lang=vi';");
                    wait.Until(d => d.PageSource.Contains("javascript:SubmitForm();"));
                    driver.FindElement(By.CssSelector("input[name='txtAgentID']")).SendKeys(cCO.TaiKhoan); //thẻ có tên là
                    driver.FindElement(By.CssSelector("#txtAgentPswd")).SendKeys(cCO.MatKhau);             // # ID
                    driver.FindElement(By.CssSelector(".button")).Click();                                 // . Class
                    wait.Until(d => d.PageSource.Contains("button_big subAgencgyBtn"));
                    driver.FindElement(By.LinkText("Đại lý con")).Click();
                    wait.Until(d => CountElementByClassName(driver, "a", "user-icon ng-scope") == 5);
                    ChromeFindElementByClassName("a", "user-icon ng-scope", 0).Click();
                    wait.Until(d => d.FindElements(By.LinkText("New user")).Count > 0);
                    wait.Until(d => d.PageSource.Contains("base-loading-class") == false);
                }

                O_DAILY dl = _lstDL.Where(w => w.ID.Equals(_lstSIChinh[i].DaiLy)).ToList()[0];

                switch (_lstSIChinh[i].CanLam)
                {
                case 0:
                    driver.FindElement(By.LinkText("New user")).Click();
                    wait.Until(d => d.PageSource.Contains("btn btn-secondary ng-binding"));
                    Thread.Sleep(1000);
                    wait.Until(d => d.PageSource.Contains("form-control ng-pristine ng-untouched ng-valid-we-validate ng-valid-maxlength ng-valid ng-valid-required"));

                    Thread.Sleep(2000);
                    object a = ChromeFindElementByClassName("input", "form-control ng-pristine ng-untouched ng-valid-we-validate ng-valid-maxlength ng-valid ng-valid-required", 0).GetAttribute("value");
                    Invoke(new MethodInvoker(delegate()
                    {
                        _lstSIChinh[i].SignIn = a.ToString();
                        GCSI.DataSource       = null;
                        GCSI.DataSource       = _lstSIChinh;
                        GVSI.ExpandAllGroups();
                    }));

                    Actions build = new Actions(driver);
                    Thread.Sleep(1000);
                    build.Click(ChromeFindElementByClassName("div", "ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control ng-valid ng-valid-ui-select-required", 0)).Build().Perform();

                    Thread.Sleep(1000);
                    wait.Until(d => d.FindElements(By.LinkText("TA")).Count > 0);
                    driver.FindElement(By.LinkText("TA HOLD")).Click();

                    if (_lstSIChinh[i].Chinh)
                    {
                        wait.Until(d => d.PageSource.Contains("base-loading-class") == false);
                        js.ExecuteScript("document.getElementsByClassName('ui-select-search input-xs ng-pristine ng-valid ng-touched')[0].click()");
                        try
                        {
                            driver.FindElement(By.LinkText("TA")).Click();
                        }
                        catch { }
                    }

                    ChromeFindElementByClassName("input", "form-control ng-pristine ng-untouched ng-invalid ng-invalid-required", 0).SendKeys(_lstSIChinh[i].MatKhau);
                    ChromeFindElementByClassName("input", "form-control ng-pristine ng-untouched ng-valid-we-validate ng-invalid ng-invalid-required", 0).SendKeys(_lstSIChinh[i].MatKhau);

                    ChromeFindElementByClassName("input", "form-control ng-pristine ng-untouched ng-valid-we-validate ng-invalid ng-invalid-required ng-valid-maxlength ng-valid-email", 0).SendKeys((dl.EmailGiaoDich ?? "*****@*****.**").Replace("\r\n", "|").Split('|')[0]);
                    ChromeFindElementByClassName("input", "form-control ng-pristine ng-untouched ng-valid-we-validate ng-invalid ng-invalid-required ng-valid-maxlength", 0).SendKeys(dl.DiDong ?? "0919415995");
                    ChromeFindElementByClassName("input", "form-control ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength", 0).SendKeys(_lstSIChinh[i].SignIn + "-" + XuLyDuLieu.NotVietKey(dl.Ten).Replace(" ", string.Empty));

                    new SelectElement(ChromeFindElementByClassName("select", "form-control ng-pristine ng-untouched ng-invalid ng-invalid-required")).SelectByIndex(47);

                    ChromeFindElementByClassName("button", "btn btn-secondary ng-binding", 0).Submit();

                    Thread.Sleep(1000);
                    wait.Until(d => d.PageSource.Contains("base-loading-class") == false);
                    wait.Until(d => d.FindElements(By.LinkText("New user")).Count > 0);
                    _lstSIChinh[i].End = true;

                    break;
                }
                #endregion
            }
            driver.Close();
            driver.Quit();
        }