using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.Service.DTO;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Configuration;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Service
{

    public class CodeTemplateService(IRepository<Dictionary> _dicRepository,IMapper _mapper, IConfiguration _configuration) : ServiceBase
    {

        static string GetCSharpType(Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                var underlyingType = Nullable.GetUnderlyingType(type);
                return $"{GetCSharpType(underlyingType)}?";
            }

            return type switch
            {
                _ when type == typeof(int) => "int",
                _ when type == typeof(long) => "long",
                _ when type == typeof(short) => "short",
                _ when type == typeof(byte) => "byte",
                _ when type == typeof(bool) => "bool",
                _ when type == typeof(decimal) => "decimal",
                _ when type == typeof(double) => "double",
                _ when type == typeof(float) => "float",
                _ when type == typeof(Guid) => "Guid",
                _ when type == typeof(DateTime) => "DateTime",
                _ when type == typeof(string) => "string",
                _ => type.Name // 非常见类型,返回 .NET 类型名称
            };
        }

        /// <summary>
        /// 获取数据库的表信息 以及字段信息
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        public List<TemplateTable> GetDataBaseTableList(string tableName, string comment)
        {
            var contextOptions = new DbContextOptionsBuilder<IRaCISDBContext>().UseSqlServer(_configuration.GetSection("ConnectionStrings:RemoteNew").Value).Options;

            using var dbContext = new IRaCISDBContext(contextOptions);
            var dbModel = dbContext.Model;

            var list = dbModel.GetEntityTypes().Where(t => t.GetTableName().IsNotNullOrEmpty())
                   .WhereIf(tableName.IsNotNullOrEmpty(), t => t.GetTableName()!.Contains(tableName))
                   .WhereIf(comment.IsNotNullOrEmpty(), t => t.GetComment().Contains(comment))
                   .Select(t => new TemplateTable()
                   {
                       TableName = t.GetTableName()!,
                       TablePropertyList = t.GetProperties().Select(property => new TemplateTableProperty()
                       {
                           PropertyName = property.Name,
                           ColumnName = property.GetColumnName(),
                           IsNullable = property.IsNullable,
                           IsPrimarykey = property.IsKey(),
                           CSharpType = GetCSharpType(property.ClrType),
                           Comment = property.GetComment() ?? string.Empty
                       }).ToList()
                   }).ToList();


            return list;
        }

        /// <summary>
        /// 根据字典名 code  生成枚举定义
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GenerateEnumDefine(string code)
        {
            var searchList = await _dicRepository.Where(t => t.Parent.Code == code && t.ParentId != null && t.IsEnable).ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).ToListAsync();

            // StringBuilder 用于构建枚举代码字符串
            var enumCode = new StringBuilder();

            // 生成枚举定义
            enumCode.AppendLine($"public enum {code}");
            enumCode.AppendLine("{");

            foreach (var item in searchList)
            {
                // 添加 XML 注释作为枚举描述
                enumCode.AppendLine($"    /// <summary>");
                enumCode.AppendLine($"    /// {item.ValueCN}"); // 假设你有一个描述字段
                enumCode.AppendLine($"    /// </summary>");
                // 每个枚举值生成
                enumCode.AppendLine($"    {item.Value.Trim().Replace(" ", "")} = {item.Code},");

            }

            enumCode.AppendLine("}");

            // 返回生成的枚举代码
            var enumStr = enumCode.ToString();

            return ResponseOutput.Ok(enumStr);

        }



    }
}