using DevExpress.XtraBars.ToolbarForm;
using DeviceRepair.Models;
using DeviceRepair.Utils.Security;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;

namespace DeviceRepairAndOptimization.Pages.Users
{
    public partial class frmPwdModify : ToolbarForm
    {
        public frmPwdModify(bool CanClose = true)
        {
            InitializeComponent();

            if (!CanClose)
            {
                this.ControlBox = false;
                this.btn_Cancel.Visible = false;
            }
        }

        private void btn_Submit_Click(object sender, EventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            try
            {
                if (DataValid())
                {
                    APIResponseData apiResponseData = UserManager.Instance.UpdateUserPassword(GlobalInfo.CurrentUser.LoginCode, EncryptionHelper.EncryptByMD5(txt_NewPassWord.Text));

                    if (apiResponseData.Code == -1)
                        throw new Exception(apiResponseData.Message);

                    splashScreenManager1.TryCloseWait();
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }

                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ee)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ee.Message);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void frmPwdModify_Load(object sender, EventArgs e)
        {
            txt_LoginCode.Text = GlobalInfo.CurrentUser.LoginCode;
            txt_RealName.Text = GlobalInfo.CurrentUser.RealName;
            lb_Description.Text = PassWordValidata.Instance.PassWordRulesText;
        }

        /// <summary>
        /// 密码校验
        /// </summary>
        /// <returns></returns>
        bool DataValid()
        {
            try
            {
                #region 原密码 校验

                string Password = txt_OldPassWord.Text;
                if (string.IsNullOrWhiteSpace(Password))
                {
                    dxErrorProvider1.SetError(txt_OldPassWord, "密码不可以为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (EncryptionHelper.EncryptByMD5(Password).Length > 50)
                {
                    dxErrorProvider1.SetError(txt_OldPassWord, "密码长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else
                {
                    dxErrorProvider1.SetError(txt_OldPassWord, "");
                }

                #endregion

                #region 新密码校验

                string nPassword = txt_NewPassWord.Text;
                if (string.IsNullOrWhiteSpace(nPassword))
                {
                    dxErrorProvider1.SetError(txt_NewPassWord, "新密码不可以为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (EncryptionHelper.EncryptByMD5(nPassword).Length > 50)
                {
                    dxErrorProvider1.SetError(txt_NewPassWord, "新密码长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (Password.Equals(nPassword))
                {
                    dxErrorProvider1.SetError(txt_NewPassWord, "新密码不能与旧密码相同！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (PassWordValidata.Instance.PasswordMinLength != 0 && nPassword.Length < PassWordValidata.Instance.PasswordMinLength)
                {
                    dxErrorProvider1.SetError(txt_NewPassWord, PassWordValidata.Instance.PasswordMinLengthText, DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }

                int MinPasswordStrategyTypeCounts = PassWordValidata.Instance.GetTrueNumber(nPassword);
                if (MinPasswordStrategyTypeCounts < 3)
                {
                    dxErrorProvider1.SetError(txt_NewPassWord, $"密码不合符密码强度策略（大写字母/小写字母/数字/特殊字符中必须满足其中3种）！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }

                #endregion

                #region 确认密码校验

                string cPassword = txt_ConfirmPassWord.Text;
                if (string.IsNullOrWhiteSpace(cPassword))
                {
                    dxErrorProvider1.SetError(txt_ConfirmPassWord, "确认密码不可以为空！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (EncryptionHelper.EncryptByMD5(cPassword).Length > 50)
                {
                    dxErrorProvider1.SetError(txt_ConfirmPassWord, "确认密码长度超限！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }
                else if (!nPassword.Equals(cPassword))
                {
                    dxErrorProvider1.SetError(txt_ConfirmPassWord, "两次密码输入必须相同！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }

                #endregion

                #region 密码规则校验

                //if (!PassWordValidata.Instance.CheckAll(nPassword))
                //{





                //    dxErrorProvider1.SetError(txt_NewPassWord, PassWordValidata.Instance.PassWordRulesText, DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                //    return false;
                //}

                #endregion

                #region 原密码正确性校验

                APIResponseData apiResponseData = UserManager.Instance.ValidePassWord(GlobalInfo.CurrentUser.LoginCode, EncryptionHelper.EncryptByMD5(txt_OldPassWord.Text));
                if (apiResponseData.Code == -1)
                {
                    dxErrorProvider1.SetError(txt_OldPassWord, apiResponseData.Message, DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    return false;
                }

                #endregion

                #region 近3次密码不许相同

                //apiResponseData = HistoryManager.Instance.GetUserPwdHis(GlobalInfo.CurrentUser.AutoID);
                //if (apiResponseData.Code == -1)
                //{
                //    dxErrorProvider1.SetError(txt_NewPassWord, $"新密码校验失败，请重试！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                //    return false;
                //}
                //else if (apiResponseData.Code == 1)
                //{
                //    List<UserPassChangeLogInfo> lst = apiResponseData.ToDeserializeObject<List<UserPassChangeLogInfo>>();
                //    if (lst.Any(x => x.PwdNew == EncryptionHelper.EncryptByMD5(nPassword)))
                //    {
                //        dxErrorProvider1.SetError(txt_NewPassWord, $"新密码校验失败，与最近的3次密码不可重复！", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                //        return false;
                //    }
                //}

                #endregion

                dxErrorProvider1.SetError(txt_OldPassWord, "");
                dxErrorProvider1.SetError(txt_NewPassWord, "");
                dxErrorProvider1.SetError(txt_ConfirmPassWord, "");

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
