using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Attributes;
using WIDESEA_Core.CodeConfigEnum;
using WIDESEA_Core.DB;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Seed;
using WIDESEA_Core.Utilities;
namespace WIDESEA_Core.Helper
{
    public class CodeAnalysisHelper
    {
        /// 
        /// 解析编码成对象集
        /// 
        /// 泛型
        /// 规则编号
        /// 需解析的字符串
        /// 
        public static T CodeAnalysis(AnalysisCodeEnum analysisCode, string code)
        {
            Type type = typeof(T);
            object? obj = Activator.CreateInstance(type);
            if (obj == null)
                throw new Exception("实例化对象错误");
            T result = (T)obj;
            try
            {
                AnalysisRuleAttribute? analysisRule = type.GetCustomAttribute();
                if (analysisRule != null)
                {
                    SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig
                    {
                        ConfigId = MainDb.CurrentDbConnId,
                        ConnectionString = DBContext.GetMainConnectionDb().Connection,
                        IsAutoCloseConnection = true,
                        DbType = MainDb.DbType,
                    });
                    dynamic ruleConfig = sugarClient.Queryable(MainDb.AnalysisRuleConfig, "x").Where(MainDb.AnalysisCode, "=", analysisCode.ToString()).First();
                    if (ruleConfig != null)
                    {
                        string format = ruleConfig.Format;
                        string splitStr = ruleConfig.SplitStr;
                        List items = format.Split(splitStr).ToList();
                        List codes = code.Split(splitStr).ToList();
                        if (items.Count == codes.Count)
                        {
                            PropertyInfo[] propertyInfos = type.GetProperties();
                            if (AnalysisRuleEnum.Split == analysisRule.AnalysisRule)
                            {
                                for (int i = 0; i < propertyInfos.Length; i++)
                                {
                                    PropertyInfo propertyInfo = propertyInfos[i];
                                    AnalysisItemRuleAttribute? analysisItemRule = propertyInfo.GetCustomAttribute();
                                    if (analysisItemRule != null)
                                    {
                                        if (analysisItemRule.AnalysisFormaType == AnalysisFormatTypeEnum.BD)
                                        {
                                            propertyInfo.SetValue(result, code.ChangeType(propertyInfo.PropertyType));
                                        }
                                        else
                                        {
                                            int index = items.IndexOf($"[{analysisItemRule.AnalysisFormaType}]");
                                            if (index != -1)
                                            {
                                                propertyInfo.SetValue(result, codes[index]);
                                            }
                                            else
                                            {
                                                string? codeItem = items.FirstOrDefault(x => x.Contains($"[{analysisItemRule.AnalysisFormaType}]"));
                                                if (!string.IsNullOrEmpty(codeItem))
                                                {
                                                    index = items.IndexOf(codeItem);
                                                    if (index != -1)
                                                    {
                                                        string value = codes[index];
                                                        string replaceStr = codeItem.Replace($"[{analysisItemRule.AnalysisFormaType}]", "");
                                                        propertyInfo.SetValue(result, value.Replace(replaceStr, "").ChangeType(propertyInfo.PropertyType));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"解析错误,{ex.Message}");
            }
            (bool, string, object?) validateResult = ModelValidate.ValidateModelData(result, type);
            if (!validateResult.Item1)
            {
                throw new Exception($"解析错误,{validateResult.Item2}");
            }
            return result;
        }
        /// 
        /// 解析编码成对象集合
        /// 
        /// 泛型
        /// 规则编号
        /// 需解析的字符串集合
        /// 
        public static List CodeAnalysis(AnalysisCodeEnum analysisCode, List codeList)
        {
            Type type = typeof(T);
            List list = new List();
            try
            {
                AnalysisRuleAttribute? analysisRule = type.GetCustomAttribute();
                if (analysisRule != null)
                {
                    SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig
                    {
                        ConfigId = MainDb.CurrentDbConnId,
                        ConnectionString = DBContext.GetMainConnectionDb().Connection,
                        IsAutoCloseConnection = true,
                        DbType = MainDb.DbType,
                    });
                    dynamic ruleConfig = sugarClient.Queryable(MainDb.AnalysisRuleConfig, "x").Where(MainDb.AnalysisCode, "=", analysisCode.ToString()).First();
                    if (ruleConfig != null)
                    {
                        for (int j = 0; j < codeList.Count; j++)
                        {
                            T result = (T)Activator.CreateInstance(type);
                            string code = codeList[j];
                            string format = ruleConfig.Format;
                            string splitStr = ruleConfig.SplitStr;
                            List items = format.Split(splitStr).ToList();
                            List codes = code.Split(splitStr).ToList();
                            if (items.Count == codes.Count)
                            {
                                PropertyInfo[] propertyInfos = type.GetProperties();
                                if (AnalysisRuleEnum.Split == analysisRule.AnalysisRule)
                                {
                                    for (int i = 0; i < propertyInfos.Length; i++)
                                    {
                                        PropertyInfo propertyInfo = propertyInfos[i];
                                        AnalysisItemRuleAttribute? analysisItemRule = propertyInfo.GetCustomAttribute();
                                        if (analysisItemRule != null)
                                        {
                                            if (analysisItemRule.AnalysisFormaType == AnalysisFormatTypeEnum.BD)
                                            {
                                                propertyInfo.SetValue(result, code.ChangeType(propertyInfo.PropertyType));
                                            }
                                            else
                                            {
                                                int index = items.IndexOf($"[{analysisItemRule.AnalysisFormaType}]");
                                                if (index != -1)
                                                {
                                                    propertyInfo.SetValue(result, codes[index]);
                                                }
                                                else
                                                {
                                                    string? codeItem = items.FirstOrDefault(x => x.Contains($"[{analysisItemRule.AnalysisFormaType}]"));
                                                    if (!string.IsNullOrEmpty(codeItem))
                                                    {
                                                        index = items.IndexOf(codeItem);
                                                        if (index != -1)
                                                        {
                                                            string value = codes[index];
                                                            string replaceStr = codeItem.Replace($"[{analysisItemRule.AnalysisFormaType}]", "");
                                                            propertyInfo.SetValue(result, value.Replace(replaceStr, "").ChangeType(propertyInfo.PropertyType));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                list.Add(result);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return list;
        }
    }
}