using OpenAuth.App.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using Infrastructure;
using OpenAuth.Repository.Core;
using System.Data;
using System.Text.RegularExpressions;
using OpenAuth.App.FormScheme.Response;
using OpenAuth.App.FormScheme.FormHelpers;
using Autofac.Core;
using Infrastructure.Helpers;
using System.Collections;
using Newtonsoft.Json.Linq;
using OpenAuth.App.FormScheme.Request;
using System.Collections.Concurrent;
using ce.autofac.extension;
using OpenAuth.App.DataCodeRule;
using Infrastructure.Extensions;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Permission;
using NPOI.SS.Formula.Functions;
using OpenAuth.App.DataSource;
using System.Data.SqlTypes;
using DocumentFormat.OpenXml.Spreadsheet;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using OpenAuth.App.FormModule;
using Microsoft.Extensions.Logging;
using OpenAuth.App.BaseApp.Base;
using Castle.Core.Internal;
using OpenAuth.App.BaseApp.FormScheme.Request;
using OpenAuth.App.BaseApp.FormScheme.Response;
using System.Dynamic;
using System.Security.Cryptography.Xml;

namespace OpenAuth.App.FormScheme
{
    public class FormSchemeApp : SqlSugarBaseApp<Repository.Domain.FormSchemeInfo, SugarDbContext>
    {
        private ConcurrentDictionary<string, object> codeDic;
        private readonly BaseDataAuthorizeApp _dataAuthorizeApp;
        private ILogger<FormSchemeApp> _logger;
        ISqlSugarClient client;
        CommonDataManager commonDataManager;

        public FormSchemeApp(ISugarUnitOfWork<SugarDbContext> unitWork,
            ISqlSugarClient sqlSugarClient,
             ILogger<FormSchemeApp> logger,
             CommonDataManager dataManager,
            ISimpleClient<Repository.Domain.FormSchemeInfo> repository,
            BaseDataAuthorizeApp dataAuthorizeApp)
            : base(unitWork, repository, null)
        {
            _logger = logger;
            _dataAuthorizeApp = dataAuthorizeApp;
            client = sqlSugarClient;
            this.commonDataManager = dataManager;
        }

        /// <summary>
        /// 查询表单分页信息 custmerform/scheme/page
        /// </summary>
        /// <param name="keyWord">关键字</param>
        /// <param name="category">分类</param>
        /// <param name="isEnabled">状态1启用0未启用2草稿3全部</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<FormSchemeInfo>>>> LoadFormPage(string keyword, string category,
            int pageIndex, int pageSize, int isEnabled = 3)
        {
            RefAsync<int> totalCount = 0;
            var info = await base.Repository.AsQueryable()
                .LeftJoin<Repository.Domain.FormScheme>((a, b) => a.SchemeId == b.Id)
                .WhereIF(!string.IsNullOrEmpty(keyword), (a, b) => a.Name.Contains(keyword))
                .WhereIF(!string.IsNullOrEmpty(category), (a, b) => a.Category == category)
                //.WhereIF(isEnabled, (a, b) => a.EnabledMark == 1 && b.Type == 1)
                .WhereIF(isEnabled != 3, (a, b) => a.EnabledMark == isEnabled)
                .OrderByDescending((a, b) => b.CreateDate)
                //.WhereIF(type != 0, (a, b) => b.Type == type)
                .Select((a, b) => new FormSchemeInfo()
                {
                    Id = a.Id,
                    Name = a.Name,
                    Category = a.Category,
                    SchemeId = a.SchemeId,
                    EnabledMark = a.EnabledMark,
                    FormType = a.FormType,
                    Description = a.Description,
                    Type = b.Type,
                    CreateDate = b.CreateDate,
                    CreateUserId = b.CreateUserId,
                    CreateUserName = b.CreateUserName
                })
                .ToPageListAsync(pageIndex, pageSize, totalCount);
            return new Response<PageInfo<List<FormSchemeInfo>>>
            {
                Result = new PageInfo<List<FormSchemeInfo>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }

        #region 添加表单信息

        /// <summary>
        /// 保存模板信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="schemeInfo">模板基础信息</param>
        /// <param name="formScheme">模板信息</param>
        public async Task<Response<bool>> AddForm(string keyValue, FormSchemeInfo schemeInfo,
            Repository.Domain.FormScheme formScheme)
        {
            try
            {
                if (!string.IsNullOrEmpty(schemeInfo.SchemeId))
                {
                    var schemeOldEntity = await GetScheme(schemeInfo.SchemeId);
                    if (schemeOldEntity == null || schemeOldEntity.Type != formScheme.Type ||
                        schemeOldEntity.Scheme != formScheme.Scheme)
                    {
                        await SaveEntity(keyValue, schemeInfo, formScheme);
                    }
                    else
                    {
                        await SaveEntity(keyValue, schemeInfo, null);
                    }
                }
                else
                {
                    await SaveEntity(keyValue, schemeInfo, formScheme);
                }

                return new Response<bool> { Result = true };
            }
            catch (Exception ex)
            {
                return new Response<bool> { Result = false };
            }
        }

        /// <summary>
        /// 获取模板的实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public Task<Repository.Domain.FormScheme> GetScheme(string keyValue)
        {
            return base.Repository.ChangeRepository<SugarRepositiry<Repository.Domain.FormScheme>>()
                .GetFirstAsync(r => r.Id == keyValue);
        }

        /// <summary>
        /// 获取模板基础信息的实体
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        public Task<FormSchemeInfo> GetSchemeInfo(string keyValue)
        {
            return base.Repository.GetFirstAsync(r => r.Id == keyValue);
        }

        /// <summary>
        /// 保存模板信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="schemeInfoEntity">模板基础信息</param>
        /// <param name="schemeEntity">模板信息</param>
        public async Task SaveSchEntity(string keyValue, FormSchemeInfo schemeInfoEntity,
            Repository.Domain.FormScheme schemeEntity)
        {
            if (!string.IsNullOrEmpty(schemeInfoEntity.SchemeId))
            {
                var schemeOldEntity = await GetScheme(schemeInfoEntity.SchemeId);
                if (schemeOldEntity == null || schemeOldEntity.Type != schemeEntity.Type ||
                    schemeOldEntity.Scheme != schemeEntity.Scheme)
                {
                    await SaveEntity(keyValue, schemeInfoEntity, schemeEntity);
                }
                else
                {
                    await SaveEntity(keyValue, schemeInfoEntity, null);
                }
            }
            else
            {
                await SaveEntity(keyValue, schemeInfoEntity, schemeEntity);
            }
        }

        /// <summary>
        /// 保存模板信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        /// <param name="schemeInfoEntity">模板基础信息</param>
        /// <param name="schemeEntity">模板信息</param>
        public async Task<Response<string>> SaveEntity(string keyValue, FormSchemeInfo schemeInfo,
            Repository.Domain.FormScheme formScheme)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                if (string.IsNullOrEmpty(keyValue))
                {
                    schemeInfo.Id = Guid.NewGuid().ToString();
                }
                else
                {
                    schemeInfo.Id = keyValue;
                }

                #region 模板信息

                //FormSchemeNewModel formSchemeModel = formScheme.Scheme.ToObject<FormSchemeNewModel>();
                //formSchemeModel.FormType = schemeInfo.FormType;
                if (formScheme != null)
                {
                    //formScheme.Scheme = Json.ToJson(formSchemeModel);
                    formScheme.SchemeInfoId = schemeInfo.Id;
                    formScheme.Id = Guid.NewGuid().ToString();
                    formScheme.CreateDate = DateTime.Now;
                    formScheme.CreateUserId = schemeInfo.CreateUserId;
                    formScheme.CreateUserName = schemeInfo.CreateUserName;
                    await db.Scheme.InsertAsync(formScheme);
                    schemeInfo.SchemeId = formScheme.Id;
                }

                #endregion

                #region 模板基础信息

                if (!string.IsNullOrEmpty(keyValue))
                {
                    await db.SchemeInfo.UpdateAsync(schemeInfo);
                }
                else
                {
                    await db.SchemeInfo.InsertAsync(schemeInfo);
                }

                #endregion

                var flag = db.Commit();
                return new Response<string>
                {
                    Result = schemeInfo.Id,
                    Message = flag == true ? "添加成功" : "添加失败"
                };
            }
        }

        /// <summary>
        /// 更新表单模板版本
        /// </summary>
        /// <param name="schemeInfoId">模板信息主键</param>
        /// <param name="schemeId">模板主键</param>
        public async Task<Response<bool>> UpdateScheme(string schemeInfoId, string schemeId)
        {
            Repository.Domain.FormScheme formSchemeEntity = await GetScheme(schemeId);
            FormSchemeInfo entity = await base.Repository.GetFirstAsync(r => r.Id == schemeInfoId);
            if (formSchemeEntity.Type != 1)
            {
                entity.EnabledMark = 0;
            }

            //忽略为空的数据
            var flag = true;
            if (entity != null)
            {
                entity.SchemeId = schemeId;
                flag = await base.Repository.UpdateAsync(entity);
            }

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "更新成功" : "更新失败"
            };
        }

        #endregion

        /// <summary>
        /// 更新自定义表单模板状态
        /// </summary>
        /// <param name="schemeInfoId">模板信息主键</param>
        /// <param name="state">状态1启用0禁用</param>
        public async Task<Response<bool>> UpdateState(string schemeInfoId, int state)
        {
            FormSchemeInfo entity = await base.Repository.GetFirstAsync(r => r.Id == schemeInfoId);
            entity.EnabledMark = state;
            var flag = await base.Repository.UpdateAsync(entity);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "更新成功" : "更新失败"
            };
        }

        /// <summary>
        /// 删除模板信息
        /// </summary>
        /// <param name="keyValue">主键</param>
        public async Task<Response<bool>> Delete(string keyValue)
        {
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                await db.SchemeInfo.DeleteAsync(t => t.Id == keyValue);
                await db.Scheme.DeleteAsync(t => t.SchemeInfoId == keyValue);
                var flag = db.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "删除成功" : "删除失败"
                };
            }
        }

        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="schemeInfoId">模板信息主键</param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<Repository.Domain.FormScheme>>>> GetSchemePageList(PageReq pagination,
            string schemeInfoId)
        {
            RefAsync<int> totalCount = 0;
            var info = await base.Repository.ChangeRepository<SugarRepositiry<Repository.Domain.FormScheme>>()
                .AsQueryable()
                .Where(t => t.SchemeInfoId == schemeInfoId)
                .OrderByDescending(t => t.CreateDate)
                .ToPageListAsync(pagination.page, pagination.limit, totalCount);

            return new Response<PageInfo<List<Repository.Domain.FormScheme>>>
            {
                Result = new PageInfo<List<Repository.Domain.FormScheme>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }

        #region 扩展方法

        /// <summary>
        /// 获取sql列
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<List<string>> GetDataColName(string dbCode, string sql, string whereStr = null)
        {
            sql = this.SqlFilters(sql);
            sql = sql.Replace("=@param", " is not null");
            sql = sql.Replace("= @param", " is not null");
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                DataTable dt = await db.Db.SqlQueryable<object>(sql).Where(whereStr).ToDataTablePageAsync(1, 1);
                List<string> res = new List<string>();
                foreach (DataColumn item in dt.Columns)
                {
                    res.Add(item.ColumnName.ToLower());
                }

                return res;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public string SqlFilters(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return source;
            }

            //去除执行SQL语句的命令关键字
            // source = Regex.Replace(source, "select", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " insert ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " update ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " delete ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " drop ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " truncate ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " declare ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " xp_cmdshell ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " /add ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " net user ", "", RegexOptions.IgnoreCase);
            //去除执行存储过程的命令关键字 
            source = Regex.Replace(source, " exec ", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, " execute ", "", RegexOptions.IgnoreCase);
            //去除系统存储过程或扩展存储过程关键字
            source = Regex.Replace(source, "xp_", "x p_", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "sp_", "s p_", RegexOptions.IgnoreCase);
            //防止16进制注入
            source = Regex.Replace(source, "0x", "0 x", RegexOptions.IgnoreCase);
            return source;
        }

        ///// <summary>
        ///// 获取自定义表单数据权限查询条件
        ///// </summary>
        ///// <param name="code">自定义表单功能主键</param>
        ///// <returns></returns>
        //public async Task<string> GetWhereSql(string code)
        //{ 
        //    var numIndex = new string[26] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
        //    "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };


        //    // 获取数据权限配置信息
        //    List<string> objectIds = new List<string>();
        //    objectIds.Add(userInfo.F_UserId);
        //    objectIds.AddRange(roleIds);
        //    var list = await service.GetList(code, objectIds.ToArray());

        //    var strRes = new StringBuilder();
        //    int sqlNum = 0;
        //    foreach (var item in list)
        //    {

        //        if (sqlNum > 0)
        //        {
        //            strRes.Append(" OR ( ");
        //        }
        //        else
        //        {
        //            strRes.Append(" ( ");
        //        }

        //        string strSql = "";
        //        var itemFormula = item.F_Formula.ToObject<Formula>();
        //        if (!string.IsNullOrEmpty(itemFormula.formula))
        //        {
        //            strSql = itemFormula.formula;
        //            for (int i = 1; i < itemFormula.Conditions.Count + 1; i++)
        //            {
        //                var conditionItem = itemFormula.Conditions[i - 1];
        //                conditionItem.index = i;

        //                strSql = strSql.Replace("" + i, "{@learun" + i + "learun@}");
        //            }

        //            if (itemFormula.Formulas != null && itemFormula.Formulas.Count > 0)
        //            {
        //                for (int i = 0; i < itemFormula.Formulas.Count; i++)
        //                {
        //                    strSql = strSql.Replace(numIndex[i], "{@learun" + numIndex[i] + "learun@}");
        //                }
        //            }
        //        }
        //        else
        //        {
        //            // 默认公式
        //            for (int i = 1; i < itemFormula.Conditions.Count + 1; i++)
        //            {

        //                var conditionItem = itemFormula.Conditions[i - 1];
        //                conditionItem.index = i;

        //                if (string.IsNullOrEmpty(conditionItem.Group))
        //                {
        //                    if (strSql != "")
        //                    {
        //                        strSql += " AND ";
        //                    }
        //                    strSql += " {@learun" + i + "learun@} ";
        //                }
        //            }

        //            if (itemFormula.Formulas != null && itemFormula.Formulas.Count > 0)
        //            {
        //                for (int i = 0; i < itemFormula.Formulas.Count; i++)
        //                {

        //                    if (itemFormula.Conditions.FindIndex(t => t.Group == numIndex[i]) != -1)
        //                    {
        //                        if (strSql != "")
        //                        {
        //                            strSql += " AND ";
        //                        }
        //                        strSql += " {@learun" + numIndex[i] + "learun@} ";
        //                    }
        //                }
        //            }

        //        }


        //        // 分组公式处理
        //        if (itemFormula.Formulas != null && itemFormula.Formulas.Count > 0)
        //        {


        //            for (int i = 0; i < itemFormula.Formulas.Count; i++)
        //            {
        //                var groupSql = new StringBuilder();

        //                var groupList = itemFormula.Conditions.FindAll(t => t.Group == numIndex[i]);
        //                if (groupList.Count > 0)
        //                {

        //                    groupSql.Append($" {groupList[0].RelationField} in ( SELECT {groupList[0].Field} FROM {groupList[0].Table} WHERE ");

        //                    // 初始化分组公式
        //                    var groupSqlWhere = "";
        //                    if (string.IsNullOrEmpty(itemFormula.Formulas[i].Value))
        //                    {
        //                        foreach (var groupItem in groupList)
        //                        {
        //                            if (groupSqlWhere != "")
        //                            {
        //                                groupSqlWhere += " AND ";
        //                            }
        //                            groupSqlWhere += " {@learun" + groupItem.index + "learun@} ";
        //                        }
        //                    }
        //                    else
        //                    {
        //                        groupSqlWhere = itemFormula.Formulas[i].Value;
        //                        foreach (var groupItem in groupList)
        //                        {
        //                            groupSqlWhere = groupSqlWhere.Replace("" + groupItem.index, "{@learun" + groupItem.index + "learun@}");
        //                        }
        //                    }


        //                    foreach (var groupItem in groupList)
        //                    {
        //                        var strone = new StringBuilder();


        //                        if (groupItem.F_Symbol == 8)
        //                        {
        //                            strone.Append($" ({groupItem.Cfield} ");
        //                        }
        //                        else
        //                        {
        //                            strone.Append($" {groupItem.Cfield} ");
        //                        }


        //                        string value = await GetValue(groupItem.F_FiledValueType, groupItem.F_FiledValue);

        //                        switch (groupItem.F_Symbol)
        //                        {
        //                            case 1:// 等于
        //                                strone.Append($" = {value}");
        //                                break;
        //                            case 2:// 大于
        //                                strone.Append($" > {value}");
        //                                break;
        //                            case 3:// 大于等于
        //                                strone.Append($" >= {value}");
        //                                break;
        //                            case 4:// 小于
        //                                strone.Append($" < {value}");
        //                                break;
        //                            case 5:// 小于等于
        //                                strone.Append($" <= {value}");
        //                                break;
        //                            case 6:// 包含
        //                                value = value.Replace("'", "");
        //                                strone.Append($" like '%{value}%'");
        //                                break;
        //                            case 7:// 包含于
        //                                value = value.Replace(",", "','");
        //                                strone.Append($" in ({value})");
        //                                break;
        //                            case 8:// 不等于
        //                                strone.Append($" != {value} or {groupItem.Cfield} is null ) ");
        //                                break;
        //                            case 9:// 不包含
        //                                value = value.Replace("'", "");
        //                                strone.Append($" not like '%{value}%'");
        //                                break;
        //                            case 10:// 不包含于
        //                                value = value.Replace(",", "','");
        //                                strone.Append($" not in ({value})");
        //                                break;
        //                            default:
        //                                break;
        //                        }

        //                        groupSqlWhere = groupSqlWhere.Replace("{@learun" + groupItem.index + "learun@}", strone.ToString());
        //                    }
        //                    groupSql.Append(groupSqlWhere);
        //                    groupSql.Append(" ) ");


        //                    strSql = strSql.Replace("{@learun" + numIndex[i] + "learun@}", groupSql.ToString());
        //                }
        //            }
        //        }


        //        int num = 1;
        //        foreach (var conditionItem in itemFormula.Conditions)
        //        {
        //            if (string.IsNullOrEmpty(conditionItem.Group))
        //            {
        //                var strone = new StringBuilder();
        //                if (conditionItem.Type == "glbd")
        //                {
        //                    strone.Append($" {conditionItem.RelationField} in ( SELECT {conditionItem.Field} FROM {conditionItem.Table} WHERE {conditionItem.Cfield}  ");
        //                }
        //                else
        //                {
        //                    if (conditionItem.F_Symbol == 8)
        //                    {
        //                        strone.Append($" ( {conditionItem.F_FieldId}");
        //                    }
        //                    else
        //                    {
        //                        strone.Append($" {conditionItem.F_FieldId}");
        //                    }

        //                }


        //                string value = await GetValue(conditionItem.F_FiledValueType, conditionItem.F_FiledValue);

        //                switch (conditionItem.F_Symbol)
        //                {
        //                    case 1:// 等于
        //                        strone.Append($" = {value}");
        //                        break;
        //                    case 2:// 大于
        //                        strone.Append($" > {value}");
        //                        break;
        //                    case 3:// 大于等于
        //                        strone.Append($" >= {value}");
        //                        break;
        //                    case 4:// 小于
        //                        strone.Append($" < {value}");
        //                        break;
        //                    case 5:// 小于等于
        //                        strone.Append($" <= {value}");
        //                        break;
        //                    case 6:// 包含
        //                        value = value.Replace("'", "");
        //                        strone.Append($" like '%{value}%'");
        //                        break;
        //                    case 7:// 包含于
        //                        value = value.Replace(",", "','");
        //                        strone.Append($" in ({value})");
        //                        break;
        //                    case 8:// 不等于
        //                        strone.Append($" != {value}");

        //                        if (conditionItem.Type == "glbd")
        //                        {
        //                            strone.Append($" or {conditionItem.Cfield} is null  ");
        //                        }
        //                        else
        //                        {
        //                            strone.Append($" or {conditionItem.F_FieldId} is null ) ");
        //                        }


        //                        break;
        //                    case 9:// 不包含
        //                        value = value.Replace("'", "");
        //                        strone.Append($" not like '%{value}%'");
        //                        break;
        //                    case 10:// 不包含于
        //                        value = value.Replace(",", "','");
        //                        strone.Append($" not in ({value})");
        //                        break;
        //                    default:
        //                        break;
        //                }
        //                if (conditionItem.Type == "glbd")
        //                {
        //                    strone.Append(" ) ");
        //                }
        //                else
        //                {
        //                    strone.Append(" ");
        //                }

        //                strSql = strSql.Replace("{@learun" + num + "learun@}", strone.ToString());
        //            }


        //            num++;
        //        }
        //        strRes.Append(strSql);
        //        strRes.Append(" ) ");

        //        sqlNum++;
        //    }

        //    return strRes.ToString();
        //}

        /// <summary>
        /// 分页查询方法，返回datatable
        /// </summary>
        /// <param name="sqlStr">sql语句</param>
        /// <param name="sqlparam">sql参数</param>
        /// <param name="whereStr">查询条件</param>
        /// <param name="whereParam">查询参数</param>
        /// <param name="pagination">分页参数</param>
        /// <returns></returns>
        public async Task<DataTable> FindTable(string sqlStr, object sqlparam, PaginationInputDto pagination,
            string whereStr = null, object whereParam = null)
        {
            var (list, total) = await FindTableByPage(sqlStr, sqlparam, whereStr, whereParam, "", pagination.rows,
                pagination.page);
            pagination.rows = (int)total;
            return DBCommonHelper.DtColToLow(list);
        }

        /// <summary>
        /// 分页查询方法，返回datatable
        /// </summary>
        /// <returns>datatable数据</returns>
        /// <param name="sqlStr">sql语句</param>
        /// <param name="sqlparam">sql参数</param>
        /// <param name="whereStr">查询条件</param>
        /// <param name="whereParam">查询参数</param>
        /// <param name="orderSql">排序字段</param>
        /// <param name="pageSize">每页数据条数</param>
        /// <param name="pageIndex">页码</param>
        /// <returns>list数据,total 总共条数</returns>
        private async Task<(DataTable list, long total)> FindTableByPage(string sqlStr, object sqlparam,
            string whereStr, object whereParam, string orderSql, int pageSize, int pageIndex)
        {
            try
            {
                using (SugarDbContext db = base.UnitWork.CreateContext())
                {
                    RefAsync<int> total = 0;
                    var sqlQueryable = db.Db.SqlQueryable<object>(sqlStr);
                    if (sqlparam != null)
                    {
                        sqlQueryable = sqlQueryable.AddParameters(sqlparam);
                    }

                    if (!string.IsNullOrEmpty(whereStr))
                    {
                        sqlQueryable = sqlQueryable.Where(whereStr, whereParam);
                    }

                    if (!string.IsNullOrEmpty(orderSql))
                    {
                        sqlQueryable = sqlQueryable.OrderBy(orderSql);
                    }

                    var dt = await sqlQueryable.ToDataTablePageAsync(pageIndex, pageSize, total);
                    return (dt, total);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 查询方法，返回datatable
        /// </summary>
        /// <returns>datatable数据</returns>
        /// <param name="sql">sql语句</param>
        /// <param name="sqlparam">参数</param>
        public async Task<DataTable> FindTable(string sql, object sqlparam = null)
        {
            try
            {
                using (SugarDbContext db = base.UnitWork.CreateContext())
                {
                    var sqlQueryable = db.Db.SqlQueryable<object>(sql);
                    if (sqlparam != null)
                    {
                        sqlQueryable = sqlQueryable.AddParameters(sqlparam);
                    }
                    var dt = await sqlQueryable.ToDataTableAsync();
                    return DBCommonHelper.DtColToLow(dt);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 查询方法，返回datatable
        /// </summary>
        /// <returns>datatable数据</returns>
        /// <param name="sql">sql语句</param>
        /// <param name="sqlparam">参数</param>
        public async Task<List<dynamic>> FindTableNew(string sql, object sqlparam = null)
        {
            try
            {
                List<dynamic> list = new List<dynamic>();
                using (SugarDbContext db = base.UnitWork.CreateContext())
                {
                    var sqlQueryable = db.Db.SqlQueryable<object>(sql);
                    if (sqlparam != null)
                    {
                        sqlQueryable = sqlQueryable.AddParameters(sqlparam);
                    }

                    var dt = await sqlQueryable.ToDataTableAsync();
                    // 遍历每一行
                    foreach (DataRow row in dt.Rows)
                    {
                        // 遍历每一列
                        foreach (DataColumn col in dt.Columns)
                        {
                            // 获取当前列的值
                            var value = row[col];

                            var colvalue = new { col.ColumnName, value };
                            list.Add(colvalue);
                        }
                    }
                    //foreach (DataColumn item in dt.Columns)
                    //{
                    //    item.ColumnName = item.ColumnName.ToLower();
                    //    foreach (DataColumn column in dataTable.Columns)
                    //    {
                    //        var colvalue = new { item.ColumnName, dt.Rows.DefaultValue };
                    //    }

                    //    list.Add(colvalue);
                    //} 
                    return list;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取编码
        /// </summary>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public async Task<object> GetRuleCodeEx(object value)
        {
            var code = value;
            if (value != null && value.ToString().IndexOf("code_") != -1)
            {
                if (codeDic == null)
                {
                    codeDic = new ConcurrentDictionary<string, object>();
                }

                var codeList = value.ToString().Replace("code_", "").Split("|");
                if (codeDic.ContainsKey(codeList[1]))
                {
                    codeDic.TryGetValue(codeList[1], out code);
                }
                else
                {
                    code = await this.GetRuleCode(codeList[0]);
                    codeDic.TryAdd(codeList[1], code);
                }
            }

            return code;
        }

        /// <summary>
        /// 获取编码
        /// </summary>
        /// <param name="code">编码规则编码</param>
        /// <returns></returns>
        public Task<string> GetRuleCode(string code)
        {
            var codeRuleApp = IocManager.Instance.GetService<CodeRuleApp>();
            return codeRuleApp.GetBillCode(code);
        }

        #endregion

        #region 代码发布表单

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="mid">功能id</param>
        /// <param name="desktopParam">桌面参数</param>
        /// <param name="schemeId">模板信息主键</param>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        public async Task<Response<PageInfo<DataTable>>> GetFormDataPage(string mid, string desktopParam,
            string schemeId, PaginationInputDto pagination, string queryJson)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(schemeId);
            if (schemeEntity == null)
            {
                return new Response<PageInfo<DataTable>>
                {
                    Result = new PageInfo<DataTable>
                    {
                    }
                };
            }

            FormSchemeModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeModel>();


            var query = FormHelper.GetQuerySql(formSchemeModel, queryJson);
            query.Sql = query.Sql.Replace("{LEARUN_SASSID}", "");
            string sql = "";
            if (!string.IsNullOrEmpty(mid))
            {
                sql = await _dataAuthorizeApp.GetWhereSql(mid);
                if (!string.IsNullOrEmpty(sql))
                {
                    query.Sql = $" select * from ({query.Sql})t where {sql} ";
                }
            }

            //if (!string.IsNullOrEmpty(desktopParam))
            //{
            //    var desktopSql = await _iDesktopBLL.GetSql(desktopParam);

            //    if (string.IsNullOrEmpty(sql))
            //    {
            //        query.Sql = $" select * from ({query.Sql})t where {desktopSql} ";
            //    }
            //    else
            //    {
            //        query.Sql = $" {query.Sql} AND ( {desktopSql} ) ";
            //    }
            //}
            var dt = await FindTable(query.Sql, query.DbParameter, pagination);
            return new Response<PageInfo<DataTable>>
            {
                Result = new PageInfo<DataTable>
                {
                    Items = dt,
                    Total = pagination.rows
                }
            };
        }

        //去掉tablist
        public async Task<Response<PageInfo<DataTable>>> GetFormDataNewPage(string mid, string desktopParam,
            string schemeId, PaginationInputDto pagination, string queryJson)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(schemeId);
            if (schemeEntity == null)
            {
                return new Response<PageInfo<DataTable>>
                {
                    Result = new PageInfo<DataTable>
                    {
                    }
                };
            }

            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();


            var query = FormHelper.GetQuerySqlNew(formSchemeModel, queryJson);
            query.Sql = query.Sql.Replace("{LEARUN_SASSID}", "");
            string sql = "";
            if (!string.IsNullOrEmpty(mid))
            {
                sql = await _dataAuthorizeApp.GetWhereSql(mid);
                if (!string.IsNullOrEmpty(sql))
                {
                    query.Sql = $" select * from ({query.Sql})t where {sql} ";
                }
            }

            //if (!string.IsNullOrEmpty(desktopParam))
            //{
            //    var desktopSql = await _iDesktopBLL.GetSql(desktopParam);

            //    if (string.IsNullOrEmpty(sql))
            //    {
            //        query.Sql = $" select * from ({query.Sql})t where {desktopSql} ";
            //    }
            //    else
            //    {
            //        query.Sql = $" {query.Sql} AND ( {desktopSql} ) ";
            //    }
            //}
            var dt = new DataTable();
            if (pagination != null)
            {
                dt = await FindTable(query.Sql, query.DbParameter, pagination);
                return new Response<PageInfo<DataTable>>
                {
                    Result = new PageInfo<DataTable>
                    {
                        Items = dt,
                        Total = pagination.rows
                    }
                };
            }
            else
            {
                dt = await FindTable(query.Sql, query.DbParameter);
                return new Response<PageInfo<DataTable>>
                {
                    Result = new PageInfo<DataTable>
                    {
                        Items = dt,
                    }
                };
            }
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="mid">功能id</param>
        /// <param name="desktopParam">桌面参数</param>
        /// <param name="schemeId">模板信息主键</param>
        /// <param name="queryJson">查询条件</param>
        /// <param name="sidx">排序字段</param>
        /// <returns></returns>
        public async Task<DataTable> GetFormDataList(string mid, string schemeId, string queryJson, string sidx)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(schemeId);
            FormSchemeModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeModel>();
            var query = FormHelper.GetQuerySql(formSchemeModel, queryJson);

            query.Sql = query.Sql.Replace("{LEARUN_SASSID}", "");
            string sql = "";
            if (!string.IsNullOrEmpty(mid))
            {
                //sql = await this.GetDataAuthoritySql(mid);
                if (!string.IsNullOrEmpty(sql))
                {
                    query.Sql = $" select * from ({query.Sql})t where {sql} ";
                }
            }

            //if (!string.IsNullOrEmpty(desktopParam))
            //{
            //    var desktopSql = await _iDesktopBLL.GetSql(desktopParam);

            //    if (string.IsNullOrEmpty(sql))
            //    {
            //        query.Sql = $" select * from ({query.Sql})t where {desktopSql} ";
            //    }
            //    else
            //    {
            //        query.Sql = $" {query.Sql} AND ( {desktopSql} ) ";
            //    }
            //}

            // 排序字段
            if (!string.IsNullOrEmpty(sidx))
            {
                query.Sql += $" order by {sidx}";
            }


            if (formSchemeModel.FormType == 1)
            {
                Dictionary<string, object> DbParameter = new Dictionary<string, object>();
                foreach (var param in query.DbParameter)
                {
                    DbParameter.Add(param.ParameterName, param.Value);
                }

                return await FindTable(query.Sql, DbParameter);
            }

            return await FindTable(query.Sql, query.DbParameter);
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="schemeId">模板信息主键</param>
        /// <param name="key">主键名</param>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public async Task<Dictionary<string, DataTable>> GetFormData(string schemeId, string key, string keyValue)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(schemeId);
            FormSchemeModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeModel>();
            var list = FormHelper.GetQuery(formSchemeModel, key);
            var res = new Dictionary<string, DataTable>();
            foreach (var item in list)
            {
                item.Sql = item.Sql.Replace("{LEARUN_SASSID}", "");
                if (string.IsNullOrEmpty(item.RelationName))
                {
                    var dt = await FindTable(item.Sql, new { keyValue });
                    res.Add(item.TableName, dt);
                }
                else
                {
                    var dt = await FindTable(item.Sql,
                        new { keyValue = res[item.RelationName].Rows[0][item.RelationField.ToLower()] });
                    res.Add(item.TableName, dt);
                }
            }

            return res;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="schemeId">模板信息主键</param>
        /// <param name="key">主键名</param>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public async Task<Dictionary<string, DataTable>> GetFormDataNew(string schemeId, string key, string keyValue)
        {
            // 表单
            Repository.Domain.FormScheme schemeEntity = await GetScheme(schemeId);
            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
            var list = FormHelper.GetQueryNew(formSchemeModel, key);
            var res = new Dictionary<string, DataTable>();
            foreach (var item in list)
            {
                item.Sql = item.Sql.Replace("{LEARUN_SASSID}", "");
                if (string.IsNullOrEmpty(item.RelationName))
                {
                    var dt = await FindTable(item.Sql, new { keyValue });
                    res.Add(item.TableName, dt);
                }
                else
                {
                    //var dt = await FindTable(item.Sql, new { keyValue = res[item.RelationName].Rows[0][item.RelationField.ToLower()] });
                    var dt = await FindTable(item.Sql, new { keyValue });
                    res.Add(item.TableName, dt);
                }
            }

            return res;
        }

        /// <summary>
        /// 保存表单数据
        /// </summary>
        /// <param name="dto">参数</param>
        /// <returns></returns>
        public async Task<Response<JObject>> SaveFormData(FormDataReq dto)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(dto.SchemeId);
            FormSchemeModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeModel>();
            var dataJson = dto.Data.ToJObject();
            var list = FormHelper.GetSaveSql(formSchemeModel, dataJson, dto.Pkey, dto.PkeyValue, dto.IsUpdate);
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                foreach (var item in list)
                {
                    // 遍历参数
                    foreach (var p in item.DbParameter)
                    {
                        p.Value = await GetRuleCodeEx(p.Value);
                    }

                    var properties = dataJson.Properties();
                    foreach (var item2 in properties)
                    {
                        if (item2.Value.ToString() != null && item2.Value.ToString().IndexOf("code_") != -1)
                        {
                            dataJson[item2.Name] = (await GetRuleCodeEx(item2.Value.ToString())).ToString();
                        }
                    }

                    switch (item.ExecuteType)
                    {
                        case ExecuteType.Insert:
                            await db.Db.Ado.ExecuteCommandAsync(ExecuteInsert(item.TableName, item.DbParameter),
                                item.DbParameter);
                            break;
                        case ExecuteType.Update:
                            await db.Db.Ado.ExecuteCommandAsync(
                                ExecuteUpdate(item.TableName, item.DbParameter, item.Pkey), item.DbParameter);
                            break;
                        case ExecuteType.Delete:
                            await db.Db.Ado.ExecuteCommandAsync(ExecuteDelete(item.TableName, item.DbParameter),
                                item.DbParameter);
                            break;
                    }
                }


                if (dto.DiffFormData != null)
                {
                    //获取表单更改历史记录信息 add by torres 
                    var difflist = GetSaveHistoryList(dto.DiffFormData, dto.Pkey, dto.PkeyValue, dto.SchemeId,
                        schemeEntity.SchemeInfoId);
                    if (difflist.Count > 0)
                    {
                        if (formSchemeModel.FormInfo.HistoryType == "2")
                        {
                            await db.FormDataHistory.InsertRangeAsync(difflist);
                        }
                        else if (formSchemeModel.FormInfo.HistoryType == "1")
                        {
                            //await formSchemeService.BaseRepository().Inserts(difflist);
                            await db.FormDataHistory.InsertRangeAsync(difflist); //待定
                        }
                    }
                }

                var flag = db.Commit();
                return new Response<JObject>
                {
                    Result = dataJson,
                    Message = flag == true ? "提交成功" : "提交失败"
                };
            }
        }

        /// <summary>
        /// 保存表单数据
        /// </summary>
        /// <param name="dto">参数</param>
        /// <returns></returns>
        public async Task<Response<JObject>> SaveFormDataNew(FormDataReq dto)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(dto.SchemeId);
            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
            //数据为空时，不执行保存
            if (string.IsNullOrEmpty(dto.Data) || dto.Data == "{}")
            {
                throw new Exception("数据不能为空");
            }
            var dataJson = dto.Data.ToJObject();
            _logger.LogError("保存表单数据接收: " + Newtonsoft.Json.JsonConvert.SerializeObject(dto));
            var list = FormHelper.GetSaveSqlNew(formSchemeModel, dataJson, dto.Pkey, dto.PkeyValue, dto.IsUpdate);
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                foreach (var item in list)
                {
                    // 遍历参数
                    foreach (var p in item.DbParameter)
                    {
                        p.Value = await GetRuleCodeEx(p.Value);
                    }

                    var properties = dataJson.Properties();
                    foreach (var item2 in properties)
                    {
                        if (item2.Value.ToString() != null && item2.Value.ToString().IndexOf("code_") != -1)
                        {
                            dataJson[item2.Name] = (await GetRuleCodeEx(item2.Value.ToString())).ToString();
                        }
                    }

                    switch (item.ExecuteType)
                    {
                        case ExecuteType.Insert:
                            //await db.Db.Ado.ExecuteCommandAsync(ExecuteInsert(item.TableName, item.DbParameter),
                            //    item.DbParameter);
                            var sql = ExecuteInsert(item.TableName, item.DbParameter);
                            if (!string.IsNullOrWhiteSpace(sql))
                            {
                                await db.Db.Ado.ExecuteCommandAsync(sql, item.DbParameter);
                            }
                            break;
                        case ExecuteType.Update:
                            await db.Db.Ado.ExecuteCommandAsync(
                                ExecuteUpdate(item.TableName, item.DbParameter, item.Pkey), item.DbParameter);
                            break;
                        case ExecuteType.Delete:
                            await db.Db.Ado.ExecuteCommandAsync(ExecuteDelete(item.TableName, item.DbParameter),
                                item.DbParameter);
                            break;
                    }
                }


                if (dto.DiffFormData != null)
                {
                    //获取表单更改历史记录信息 add by torres 
                    var difflist = GetSaveHistoryList(dto.DiffFormData, dto.Pkey, dto.PkeyValue, dto.SchemeId,
                        schemeEntity.SchemeInfoId);
                    if (difflist.Count > 0)
                    {
                        await db.FormDataHistory.InsertRangeAsync(difflist);
                        //if (formSchemeModel.FormInfo.HistoryType == "2")
                        //{
                        //    await db.FormDataHistory.InsertRangeAsync(difflist);
                        //}
                        //else if (formSchemeModel.FormInfo.HistoryType == "1")
                        //{
                        //    //await formSchemeService.BaseRepository().Inserts(difflist);
                        //    await db.FormDataHistory.InsertRangeAsync(difflist);//待定
                        //}
                    }
                }

                var flag = db.Commit();
                return new Response<JObject>
                {
                    Result = dataJson,
                    Message = flag == true ? "提交成功" : "提交失败"
                };
            }
        }

        #region 历史记录实体列表

        /// <summary>
        /// 获取历史记录实体列表
        /// </summary>
        /// <param name="historyInfo">更新的字段信息</param>
        /// <param name="pkey">主键字段</param>
        /// <param name="pkeyValue">主键值</param>
        /// <param name="schemeId">表单配置id</param>
        /// <param name="f_schemeInfoId">表单信息id</param>
        /// <returns></returns>
        public List<FormDataHistory> GetSaveHistoryList(List<FormDataHistory> historyInfo, string pkey,
            string pkeyValue, string schemeId, string f_schemeInfoId)
        {
            if (historyInfo != null && historyInfo.Count > 0)
            {
                foreach (var item in historyInfo)
                {
                    item.Id = Guid.NewGuid().ToString();
                    item.TablePKey = pkey;
                    item.TablePKeyValue = pkeyValue;
                    item.SchemeId = schemeId;
                    item.SchemeInfoId = f_schemeInfoId;
                    item.CreaterTime = DateTime.Now;
                }
            }

            return historyInfo;
        }

        #endregion

        #region 拼接字符串

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="dbParameters">参数</param>
        /// <returns></returns>
        public string ExecuteInsert(string tableName, List<SugarParameter> dbParameters)
        {
            if (dbParameters == null || dbParameters.Count == 0)
            {
                return string.Empty;
            }
            var sql = new StringBuilder();
            var sqlValue = new StringBuilder();

            sql.Append($" INSERT INTO {tableName} ( \"");
            sqlValue.Append($" ( ");
            bool isfirt = true;
            foreach (var item in dbParameters)
            {
                if (!isfirt)
                {
                    sql.Append(",\"");
                    sqlValue.Append(",");
                }

                sql.Append($"{item.ParameterName}\"");
                sqlValue.Append($"@{item.ParameterName}");
                isfirt = false;
            }

            sql.Append($" ) VALUES {sqlValue} )");

            //var strSql = DBCommonHelper.SqlFormat(sql.ToString(), _dataType);

            return sql.ToString();
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="dbParameters">参数</param>
        /// <param name="pkey">主键名</param>
        /// <returns></returns>
        public string ExecuteUpdate(string tableName, List<SugarParameter> dbParameters, string pkey)
        {
            var sql = new StringBuilder();
            sql.Append($" UPDATE {tableName} SET ");

            bool isfirt = true;
            foreach (var item in dbParameters)
            {
                if (item.Value == null)
                {
                    if (!isfirt)
                    {
                        sql.Append(",");
                    }

                    sql.Append($"\"{item.ParameterName}\" = null ");
                    isfirt = false;
                }
                else
                {
                    if (!isfirt)
                    {
                        sql.Append(",");
                    }

                    sql.Append($"\"{item.ParameterName}\" = @{item.ParameterName} ");
                    isfirt = false;
                }
            }

            sql.Append($" WHERE \"{pkey}\" = @{pkey} ");

            return sql.ToString();
        }

        /// <summary>
        /// 删除表数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="dbParameters">参数</param>
        /// <returns></returns>
        public string ExecuteDelete(string tableName, List<SugarParameter> dbParameters)
        {
            var sql = new StringBuilder();
            sql.Append($" DELETE FROM {tableName} WHERE 1=1 ");

            foreach (var item in dbParameters)
            {
                sql.Append($" AND \"{item.ParameterName}\" = @{item.ParameterName} ");
            }

            return sql.ToString();
        }

        #endregion

        /// <summary>
        /// 删除表单数据
        /// </summary>
        /// <param name="schemeId">模板信息主键</param>
        /// <param name="key">主键名</param>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public async Task<Response<string>> DeleteFormData(string schemeId, string key, string keyValue)
        {
            Repository.Domain.FormScheme schemeEntity = await GetScheme(schemeId);
            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();

            var list = FormHelper.GetQueryNew(formSchemeModel, key);
            var res = new Dictionary<string, DataTable>();
            foreach (var item in list)
            {
                if (string.IsNullOrEmpty(item.RelationName))
                {
                    var dt = await FindTable(item.Sql, new { keyValue });
                    res.Add(item.TableName, dt);
                }
                else
                {
                    var dt = await FindTable(item.Sql, new { keyValue });
                    res.Add(item.TableName, dt);
                }
            }

            var deleteList = FormHelper.GetDeleteSqlNew(formSchemeModel, key);
            var flag = false;
            using (SugarDbContext db = base.UnitWork.CreateContext())
            {
                try
                {
                    foreach (var item in deleteList)
                    {
                        if (string.IsNullOrEmpty(item.RelationName))
                        {
                            await db.Db.Ado.ExecuteCommandAsync(item.Sql, new { keyValue });
                        }
                        else
                        {
                            await db.Db.Ado.ExecuteCommandAsync(item.Sql, new { keyValue });
                        }
                    }

                    flag = db.Commit();
                }
                catch
                {
                    flag = false;
                }

                return new Response<string>
                {
                    Result = flag == true ? "success" : "fail",
                    Message = flag == true ? "删除成功" : "删除失败"
                };
            }
        }

        #endregion

        #region 获取矢量切片

        /// <summary>
        /// 根据表名获取矢量切片
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public byte[] QueryVectorTileByTable(QueryVectorTileByTableReq req)
        {
            VectorTileSearchModel searchModel = new VectorTileSearchModel
            {
                x = req.x,
                y = req.y,
                z = req.z,
                field = req.field,
                table = req.table,
                filter = req.filter,
            };
            var result = commonDataManager.VectorTile(searchModel);
            return result;
        }

        #endregion

        #region 导入

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">表单设计id</param>
        /// <param name="dt">数据</param>
        /// <returns></returns>
        public async Task<(DataTable elist, int snum, int fnum)> ImportTable(string id, DataTable dt, string pkey)
        {
            int snum = 0;
            int fnum = 0;
            //解析表单
            List<ExcelImportFileds> list = new List<ExcelImportFileds>();
            Repository.Domain.FormScheme schemeEntity = await GetScheme(id);
            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
            FormDbTableInfo mainTable = formSchemeModel.Db.Find(t => t.Type == "main");
            foreach (var tab in formSchemeModel.FormInfo.TabList)
            {
                foreach (var component in tab.Schemas)
                {
                    if (component == null || component.ComponentProps == null ||
                        string.IsNullOrEmpty(component.ComponentProps.DataTable))
                    {
                        continue;
                    }

                    ExcelImportFileds excelImportFileds = new ExcelImportFileds();
                    excelImportFileds.ColName = component.Label;
                    excelImportFileds.Name = component.ComponentProps.FieldName;
                    excelImportFileds.CsType = component.CsType;
                    excelImportFileds.RelationType = component.ComponentProps.FieldName == pkey ? 1 : 0;
                    list.Add(excelImportFileds);
                }
            }

            DataTable failDt = new DataTable();
            dt.Columns.Add("导入错误", typeof(string));
            foreach (DataColumn dc in dt.Columns)
            {
                failDt.Columns.Add(dc.ColumnName, dc.DataType);
            }

            if (dt.Rows.Count > 0)
            {
                using (SugarDbContext db = base.UnitWork.CreateContext())
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        // 行数据循环
                        try
                        {
                            List<SugarParameter> dbParameters = new List<SugarParameter>();
                            foreach (var col in list)
                            {
                                object paramValue = null;

                                switch (col.RelationType)
                                {
                                    case 0: //无关联
                                        paramValue = dr[col.ColName].ToString();
                                        break;
                                    case 1: //GUID
                                        paramValue = Guid.NewGuid().ToString();
                                        break;
                                    case 2: //数据字典

                                        break;
                                    case 3: //数据表

                                        break;
                                    case 4: //固定值
                                        paramValue = col.Value;
                                        break;
                                    case 5: //操作人ID
                                        paramValue = "";
                                        break;
                                    case 6: //操作人名字
                                        paramValue = "";
                                        break;
                                    case 7: //操作时间
                                        paramValue = DateTime.Now;
                                        break;
                                }

                                dbParameters.Add(FormHelper.GetMyDbParameter(col.Name, paramValue.ToString(),
                                    col.CsType));
                            }

                            await db.Db.Ado.ExecuteCommandAsync(ExecuteInsert(mainTable.Name, dbParameters),
                                dbParameters);
                            db.Commit();
                            snum++;
                        }
                        catch (Exception ex)
                        {
                            fnum++;

                            dr["导入错误"] = ex.Message;
                            failDt.Rows.Add(dr.ItemArray);
                        }
                    }
                }
            }

            return (failDt, snum, fnum);
        }

        //导出模板
        public async Task<Response<MemoryStream>> ExportTemplate(string id, DataTable dt, string pkey)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                //解析表单
                List<ExcelImportFileds> list = new List<ExcelImportFileds>();
                Repository.Domain.FormScheme schemeEntity = await GetScheme(id);
                FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
                FormDbTableInfo mainTable = formSchemeModel.Db.Find(t => t.Type == "main");
                foreach (var tab in formSchemeModel.FormInfo.TabList)
                {
                    foreach (var component in tab.Schemas)
                    {
                        if (component == null || component.ComponentProps == null ||
                            string.IsNullOrEmpty(component.ComponentProps.DataTable))
                        {
                            continue;
                        }

                        ExcelImportFileds excelImportFileds = new ExcelImportFileds();
                        excelImportFileds.ColName = component.Label;
                        excelImportFileds.Name = component.ComponentProps.FieldName;
                        excelImportFileds.CsType = component.CsType;
                        excelImportFileds.RelationType = component.ComponentProps.FieldName == pkey ? 1 : 0;
                        list.Add(excelImportFileds);
                    }
                }

                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();

                #region 内容样式

                IFont font1 = workbook.CreateFont(); //创建一个字体样式对象
                font1.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                //font1.Boldweight = short.MaxValue;//字体加粗
                font1.FontHeightInPoints = 12; //字体大小
                ICellStyle style = workbook.CreateCellStyle(); //创建样式对象
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                style.SetFont(font1); //将字体样式赋给样式对象 
                style.WrapText = true;

                #endregion

                #region 标题样式

                IFont font = workbook.CreateFont(); //创建一个字体样式对象
                font.FontName = "Microsoft YaHei"; //和excel里面的字体对应
                font.Boldweight = (short)FontBoldWeight.Bold; //字体加粗
                font.FontHeightInPoints = 12; //字体大小
                ICellStyle style1 = workbook.CreateCellStyle(); //创建样式对象
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.SetFont(font); //将字体样式赋给样式对象 

                #endregion

                #region 创建表头

                IRow rowHeader = sheet.CreateRow(0);
                rowHeader.Height = 20 * 30;
                int j = 0;
                foreach (var i in list)
                {
                    rowHeader.CreateCell(j);
                    rowHeader.Cells[j].CellStyle = style1;
                    rowHeader.Cells[j].SetCellValue(i.ColName);
                    sheet.SetColumnWidth(j, 20 * 350);
                    j++;
                }

                #endregion

                response.Result = new MemoryStream();
                workbook.Write(response.Result);
                workbook = null;
                response.Result.Close();
                response.Result.Dispose();
                response.Code = 200;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }

            return response;
        }

        public async Task<Response<MemoryStream>> ExportTemplateNew(string id, DataTable dt, string pkey)
        {
            Response<MemoryStream> response = new Response<MemoryStream>();
            try
            {
                //解析表单
                List<ExcelImportFileds> list = new List<ExcelImportFileds>();
                Repository.Domain.FormScheme schemeEntity = await GetScheme(id);
                FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
                FormDbTableInfo mainTable = formSchemeModel.Db.Find(t => t.Type == "main");
                foreach (var tab in formSchemeModel.FormInfo.TabList)
                {
                    foreach (var component in tab.Schemas)
                    {
                        if (component == null || component.ComponentProps == null ||
                            string.IsNullOrEmpty(component.ComponentProps.DataTable))
                        {
                            continue;
                        }

                        ExcelImportFileds excelImportFileds = new ExcelImportFileds();
                        excelImportFileds.ColName = component.Label;
                        excelImportFileds.Name = component.ComponentProps.FieldName;
                        excelImportFileds.CsType = component.CsType;
                        excelImportFileds.RelationType = component.ComponentProps.FieldName == pkey ? 1 : 0;
                        list.Add(excelImportFileds);
                    }
                }

                response.Code = 200;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Code = 500;
                response.Message = ex.Message;
            }

            return response;
        }

        #endregion

        #region 获取历史数据
        //public (List<string> Headers, List<dynamic> Data) GetFormDataHistory(FormDataHistoryReq req)
        //{
        //    // 获取字段说明
        //    var tableDec = GetTableColumnsWithDescriptions(req.table);
        //    //获取表单信息
        //    // 表单
        //    Repository.Domain.FormScheme schemeEntity =   GetScheme(req.schemeId).Result;
        //    FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
        //    var chilTable = formSchemeModel.Db.Find(t => t.Type == "chlid");
        //    var reqkey = chilTable.Field;
        //    // 构建字段 SQL
        //    string fieldSql = string.Join(",", req.field);

        //    // 构建 SQL 查询语句（参数化，防注入）
        //    var sql = $"SELECT {fieldSql} FROM {req.table} WHERE {reqkey} = @p0";

        //    DataTable dt;
        //    using (var db = UnitWork.CreateContext())
        //    {
        //        dt = db.Db.Ado.GetDataTable(sql, new List<SugarParameter>{
        //            new SugarParameter("@p0", req.pkeyValue)
        //        });
        //    }
        //    // 字段中文表头
        //    var headers = req.field.Select(f =>
        //    {
        //        var desc = tableDec.FirstOrDefault(t => t.FieldName == f).Description;
        //        return string.IsNullOrEmpty(desc) ? f : desc;
        //    }).ToList();

        //    // 转换 DataTable 为 List<dynamic>
        //    var data = dt.AsEnumerable()
        //        .Select(row =>
        //        {
        //            dynamic obj = new ExpandoObject();
        //            var dict = (IDictionary<string, object>)obj;
        //            foreach (DataColumn col in dt.Columns)
        //            {
        //                dict[col.ColumnName] = row[col];
        //            }
        //            return obj;
        //        }).ToList();

        //    return (headers, data);
        //}
        public (List<object> Headers, List<dynamic> Data) GetFormDataHistory(
        FormDataHistoryReq req)
        {
            // 取到整张表的列名+中文描述
            var allColumns = GetTableColumnsWithDescriptions(req.table);   // [(FieldName,Description)]
            // 表单
            Repository.Domain.FormScheme schemeEntity = GetScheme(req.schemeId).Result;
            FormSchemeNewModel formSchemeModel = schemeEntity.Scheme.ToObject<FormSchemeNewModel>();
            var chilTable = formSchemeModel.Db.Find(t => t.Type == "chlid");
            var reqkey = chilTable.Field;

            // 先执行查询，拿到数据
            string fieldSql = string.Join(",", req.field.Select(f => $"\"{f}\""));
            string sql = $"SELECT {fieldSql} FROM \"{req.table}\" WHERE \"{reqkey}\" = @p0";

            DataTable dt;
            using (var db = UnitWork.CreateContext())
            {
                dt = db.Db.Ado.GetDataTable(sql, new List<SugarParameter>
                {
                    new SugarParameter("@p0",req.pkeyValue)
                });
            }

            // 生成 item1：{title , dataIndex}
            var item1 = req.field
                .Select(f =>
                {
                    var desc = allColumns.FirstOrDefault(c => c.FieldName == f).Description ?? f;
                    // 返回匿名对象，也可以建 DTO
                    return new { title = desc, dataIndex = f };
                })
                .ToList<object>();

            // DataTable → List<dynamic>  (item2)
            var item2 = dt.AsEnumerable()
                .Select(r =>
                {
                    dynamic obj = new ExpandoObject();
                    var dict = (IDictionary<string, object>)obj;
                    foreach (DataColumn col in dt.Columns)
                    {
                        dict[col.ColumnName] = r[col];
                    }
                    return obj;
                })
                .ToList<dynamic>();

            return (item1, item2);
        }
        public List<(string FieldName, string Description)> GetTableColumnsWithDescriptions(string tableName)
        {
            var list = new List<(string FieldName, string Description)>();
            using (var db = UnitWork.CreateContext())
            {
                var columns = db.Db.DbMaintenance.GetColumnInfosByTableName(tableName, false);
                foreach (var col in columns)
                {
                    list.Add((col.DbColumnName, col.ColumnDescription));
                }
                return list;
            }
        }
        #endregion
    }
}