using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DeviceRepairAndOptimization.Common
{
    public class PassWordValidata
    {
        /// <summary>
        /// 验证对象合集
        /// </summary>
        List<Predicate<string>> ValidCollect;

        private static PassWordValidata manager;
        public static PassWordValidata Instance
        {
            get
            {
                if (manager == null)
                    manager = new PassWordValidata();
                return manager; ;
            }
        }

        /// <summary>
        /// 规则数量
        /// </summary>
        public int RulesCount
        {
            get
            {
                int count = 0;
                if (ValidCollect == null)
                    return count;
                return ValidCollect.Count;
            }
        }

        StringBuilder build = new StringBuilder();
        /// <summary>
        /// 当前密码设定规则
        /// </summary>
        public string PassWordRulesText { get { return "大写字母/小写字母/数字/特殊字符 必须满足3种"; } }

        /// <summary>
        /// 默认的特殊字符集
        /// </summary>
        private char[] DefaultSpecialCharacters = new char[]
        {
            '~','`','!','@','#','$','%','^','&','*','(',')','-','_','+','-','[',']','{','}','|','\\',':',';','"','\'','<','>','.','/','?'
        };

        public int PasswordMinLength = 8;
        public string PasswordMinLengthText = string.Empty;

        /// <summary>
        /// 规则初始化
        /// </summary>
        public PassWordValidata()
        {
            if (ValidCollect == null)
            {
                ValidCollect = new List<Predicate<string>>();
                APIResponseData apiResponseData = CommonManager.Instance.GetAllConfigs();//List<SysConfigInfo> rules
                if (!apiResponseData.IsSuccess)
                {
                    build.AppendLine("出错：未能获取服务器配置信息！");
                    return;
                }

                List<SysConfigInfo> rules = apiResponseData.ToDeserializeObject<List<SysConfigInfo>>();
                if (rules.Any(x => x.Code.Contains("PWD_")))
                {
                    rules = rules.Where(x => x.Code.Contains("PWD_")).ToList();

                    foreach (SysConfigInfo item in rules)
                    {
                        // 最小密码长度
                        if (item.Code.Equals("PWD_MIN_LENGTH", StringComparison.OrdinalIgnoreCase))
                        {
                            int.TryParse(item.Value, out PasswordMinLength);
                            PasswordMinLengthText = $"最小密码长度不能小于{PasswordMinLength}！";
                            //if (StrLength > 0)
                            //{
                            //    build.Append($"{item.Name}为{item.Value}");
                            //    ValidCollect.Add((s) =>
                            //    {
                            //        return !string.IsNullOrWhiteSpace(s) && s.Length >= StrLength;
                            //    });
                            //}
                        }

                        // 必须存在小写字母
                        else if (item.Code.Equals("PWD_HAS_LETTER", StringComparison.OrdinalIgnoreCase) && item.Status)
                        {
                            build.Append($",{item.Name}");
                            ValidCollect.Add((s) =>
                            {
                                return Regex.IsMatch(s, "[a-z]");
                            });
                        }
                        // 必须存在大写字母
                        else if (item.Code.Equals("PWD_HAS_CAPITAL", StringComparison.OrdinalIgnoreCase) && item.Status)
                        {
                            build.Append($",{item.Name}");
                            ValidCollect.Add((s) =>
                            {
                                return Regex.IsMatch(s, "[A-Z]");
                            });
                        }
                        // 必须存在数字
                        else if (item.Code.Equals("PWD_HAS_NUMBER", StringComparison.OrdinalIgnoreCase) && item.Status)
                        {
                            build.Append($",{item.Name}");
                            ValidCollect.Add((s) =>
                            {
                                return Regex.IsMatch(s, "\\d");
                            });
                        }
                        // 必须存在特殊字符
                        else if (item.Code.Equals("PWD_HAS_SPECIALCHAR", StringComparison.OrdinalIgnoreCase) && item.Status)
                        {
                            build.Append($",{item.Name}");
                            ValidCollect.Add((s) =>
                            {
                                return (s.Where(A => { return DefaultSpecialCharacters.Contains(A); })?.Count() ?? 0) > 0;
                            });
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取匹配的规则数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int GetTrueNumber(string value)
        {
            int number = 0;

            if (ValidCollect != null && ValidCollect.Count > 0)
            {
                foreach (var item in ValidCollect)
                {
                    if (item(value))
                        number++;
                }
            }

            return number;
        }

        /// <summary>
        /// 确定序列中的所有元素是否满足条件
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool CheckAll(string value)
        {
            return ValidCollect.All(p => p(value)) && value.Length > PasswordMinLength;
        }
    }
}
