using CloudBuilder.Core.DependencyInjection.Request;
using CloudBuilder.Core.Service;
using CloudBuilder.Gui;
using CloudBuilder.Gui.DependencyInjection;
using CloudBuilder.Request.Security;
using CloudBuilder.Security.Data;
using CloudBuilder.Security.Entity;
using CloudBuilder.Security.Policy;
using DocumentFormat.OpenXml.Bibliography;
using Krypton.Toolkit;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices; // 請加在 using 區
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudBuilder.Security.Gui
{
    public partial class LoginForm : AbstractForm
    {
        // Win32 API 设置可能拖动界面功能
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        private const int WM_NCLBUTTONDOWN = 0xA1;
        private const int HTCAPTION = 0x2;

        private IContext loginContext;
        private GuiOperateHelper guiOperateHelper;
        protected GuiBindingContext guiBindingContext;

        private SecurityMessagePolicy securityMessagePolicy;
        private LoginData loginData;
        private bool complete = false;
        private bool completeValidatedException = false;

        private BackgroundWorker _worker;
        public LoginForm()
        {
            InitializeComponent();

            // 允許整個表單拖動
            this.MouseDown += LoginForm_MouseDown;
            this.mainPanel.MouseDown += LoginForm_MouseDown;
            //设置居中对齐
            this.SetBounds((Screen.GetBounds(this).Width / 2) - (this.Width / 2),
            (Screen.GetBounds(this).Height / 2) - (this.Height / 2),
            this.Width, this.Height, BoundsSpecified.Location);

            InitializeBackgroundWorker();
        }

        private void InitializeBackgroundWorker()
        {
            _worker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

            _worker.DoWork += Worker_DoWork;
        }

        public void InitForm()
        {
            try
            {
                //语言本地化-------------------------------------
                InitGuiComposeMessage();

                //初始化容器-------------------------------------
                loginContext = ServiceHelper.GetInterfaceService<IContext>()!;

                securityMessagePolicy = ServiceHelper.GetTypeService<SecurityMessagePolicy>()!;

                //创建“数据双向绑定”实例
                guiBindingContext = new GuiBindingContext();
                //创建“控件统一管理”实例
                guiOperateHelper = new GuiOperateHelper();

                //初始化自定义属性，由数据双向绑定、控件统一管理------
                userNameTxt.Set(SecurityUserEntity.USER_MOBILE, userLabel.Text,EnumEditModeColor.Required);
                passwordTxt.Set(SecurityUserEntity.USER_PASSWORD, passwordLabel.Text, EnumEditModeColor.Required);

                loginData = new LoginData();
                //控件绑定数据对象-------------------------------------
                guiBindingContext.DataBind(loginData, this);

                //设置控件状态-------------------------------------
                guiOperateHelper.EnableControls(true, this.mainPanel);

                //设置回车和Esc按钮
                this.AcceptButton = this.loginBut;

                this.CancelButton = this.cancelBut;
                //设置初始化焦点
                userNameTxt.Focus();
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void InitGuiComposeMessage()
        {
            //cultureComboBox绑定数据源
            cultureComboBox.SetDataSource(CulturePolicy.GetInstance().GetComposeMessages(), false);
            //设置当前文化显示名称
            InitResourceManager();
            //userLabel.Text变了，绑定的也要变
            userNameTxt.Set(SecurityUserEntity.USER_MOBILE, userLabel.Text, EnumEditModeColor.Required);
            passwordTxt.Set(SecurityUserEntity.USER_PASSWORD, passwordLabel.Text, EnumEditModeColor.Required);
        }

        private void Login()
        {
            complete = false;
            completeValidatedException = false;

            Task.Run(() =>
            {
                for (int i = 1; i <= 90; i++)
                {
                    if (completeValidatedException)
                    {
                        _worker.ReportProgress(100);
                        break;
                    }
                    if (complete)
                    {
                        _worker.ReportProgress(90);
                        break;
                    }
                    Thread.Sleep(50);
                    _worker.ReportProgress(i);
                }
            });

            //从容器获取请求对象
            AuthRequest authRequest = ServiceHelper.GetTypeService<AuthRequest>();
            //获取RSA公钥
            string pubKey = authRequest.GetRsaPublicKey();
            //加密用户密码
            string guid = Guid.NewGuid().ToString();
            string psw = guid + EncryptHelper.GetMd5(loginData.UserPassword);
            loginData.UserPassword = null;
            var rsa = new RSA(pubKey, true);
            loginData.Guid = guid;
            loginData.RsaUserPassword = rsa.Encode(psw);
            //设置当前文化
            loginData.Culture = loginContext.GetCulture();

            LoginProfile loginProfile;

            loginProfile = authRequest.Login(loginData);
            complete = true;

            //登录成功后设置登录上下文
            loginContext.Requestor = loginProfile.Username;
            loginContext.SetPermissionInfo(loginProfile.PermissionInfo);
            loginContext.SetToken(loginProfile.Token.AccessToken);
            loginContext.LoginDate = DateTime.Now;

            //成功后关闭登录窗口
            for (int i = 91; i <= 100; i++)
            {
                Thread.Sleep(10);
                _worker.ReportProgress(i);
            }

            this.DialogResult = DialogResult.OK;
        }

        private bool SaveValidate()
        {
            if (!guiOperateHelper.CheckValidate(this.mainPanel)) return false;

            return true;
        }

        public void loginBut_Click(object sender, EventArgs e)
        {
            try
            {
                //将控件绑定到数据对象
                guiBindingContext.DataPack();
                //登录前验证
                if (!SaveValidate()) return;
                //调用登录方法
                if (!_worker.IsBusy)
                {
                    // 顯示進度條表單
                    ProgressForm progressForm = new ProgressForm(_worker);
                    progressForm.Show(this); // this 表示主表單是擁有者

                    // 開始後台工作
                    _worker.RunWorkerAsync();
                }
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Login();
            }
            catch (ValidatedException ex)
            {
                completeValidatedException = true;
                _worker.ReportProgress(100);
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                completeValidatedException = true;
                _worker.ReportProgress(100);
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                completeValidatedException = true;
                _worker.ReportProgress(100);
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void cancelBut_Click(object sender, EventArgs e)
        {
            //关闭登录窗口
            this.DialogResult = DialogResult.Cancel;
        }

        private void cultureComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (cultureComboBox.GetValue() == null || string.IsNullOrEmpty((string)cultureComboBox.GetValue())) return;
            //设置全局文化变量
            loginContext.SetCulture((string)cultureComboBox.GetValue());
            //重新初始化，值会发生变化
            InitGuiComposeMessage();
            //重新设置当前文化
            cultureComboBox.SetValue(loginContext.GetCulture());
        }

        /// <summary>
        /// 拖动窗口事件处理
        /// </summary>
        private void LoginForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(this.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
            }
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var provider = ServiceHelper.GetService<BindingContextAttributeProvider>();
            provider.RemoveControlBinding(this.Controls);
        }
    }
}
