using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.EX;
using APT.Infrastructure.Api;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Core;
using APT.Infrastructure.Core.Refctor;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace APT.PF.WebApiControllers.Api.PF
{
    [APT.Infrastructure.Api.RootOrg]
    [Route("api/PF/Form")]
    public class FormController : AuthorizeApiController<T_PF_FORM>
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_PF_FORM>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_PF_FORM>> OrderEntities([FromBody] KeywordFilter filter)
        {
            return WitOrderEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_PF_FORM> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_PF_FORM> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            pageFilter.FilterGroup.Rules.Add(new FilterRule() { Field = "PLATFORM_CATEGORY", Operate = FilterOperate.Equal, Value = 0 });
            return WitOrderPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("NWOrderPaged")]
        public PagedActionResult<T_PF_FORM> NWOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            pageFilter.FilterGroup.Rules.Add(new FilterRule() { Field = "PLATFORM_CATEGORY", Operate = FilterOperate.Equal, Value = 1 });
            return WitOrderPaged(null, pageFilter);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                //var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                //formService.CreateFormConfigVersion(PFFormConfigVersionEnum.Form, id);

                var edit = this.GetEntity<T_PF_PAGE_EDIT>(i => i.PAGE_FORM_ID == new Guid(id));
                var table = this.GetEntity<T_PF_PAGE_TABLE>(i => i.PAGE_FORM_ID == new Guid(id));
                var tree = this.GetEntity<T_PF_PAGE_TREE>(i => i.PAGE_FORM_ID == new Guid(id));
                var chart = this.GetEntity<T_PF_PAGE_CHART>(i => i.PAGE_FORM_ID == new Guid(id));
                var custom = this.GetEntity<T_PF_PAGE_CUSTOM>(i => i.PAGE_FORM_ID == new Guid(id));
                var tableIds = new List<Guid>();
                if (edit != null)
                    tableIds.Add(edit.ID);
                if (table != null)
                    tableIds.Add(table.ID);
                if (tree != null)
                    tableIds.Add(tree.ID);
                if (chart != null)
                    tableIds.Add(chart.ID);
                if (custom != null)
                    tableIds.Add(custom.ID);


                this.UnifiedCommit(() =>
                {
                    this.DeleteEntityNoCommit<T_PF_COLUMN>(i => tableIds.Contains(i.PAGE_TABLE_ID ?? Guid.Empty));
                    this.DeleteEntityNoCommit<T_PF_EDIT_COLUMN>(i => tableIds.Contains(i.PAGE_EDIT_ID));
                    this.DeleteEntityNoCommit<T_PF_TREE_COLUMN>(i => tableIds.Contains(i.PAGE_TREE_ID));
                    this.DeleteEntityNoCommit<T_PF_BTN>(i => tableIds.Contains(i.PAGE_ID ?? Guid.Empty));
                    this.DeleteEntityNoCommit<T_PF_FORM_QUERY>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_QUERY>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_PAGE_EDIT>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_PAGE_TABLE>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_PAGE_TREE>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_PAGE_CHART>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_PAGE_CUSTOM>(i => i.PAGE_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_FM_ROLE_MENU_PERM>(i => i.PERMISSION_FORM_ID == new Guid(id));
                    this.TreeDeleteEntity<T_PF_MENU>(i => i.MENU_FORM_ID == new Guid(id));
                    this.DeleteEntityNoCommit<T_PF_FORM>(id);
                });

                return true;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_PF_FORM entity)
        {
            return SafeExecute<bool>(() =>
            {
                this.UpdateEntity(entity);
                //var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                //formService.CreateFormConfigVersion(PFFormConfigVersionEnum.Form, entity.ID.ToString());
                return true;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_PF_FORM entity)
        {
            return SafeExecute<bool>(() =>
            {
                var charts = entity.Nav_HomeCharts;
                var statistics = entity.Nav_HomeStatistics;
                var rankings = entity.Nav_HomeRankings;
                var hmis = entity.Nav_HomeHmis;

                entity.Nav_HomeCharts = null;
                entity.Nav_HomeStatistics = null;
                entity.Nav_HomeRankings = null;
                entity.Nav_HomeHmis = null;

                UnifiedCommit(() =>
                {
                    if (charts != null)
                        this.BantchSaveEntityNoCommit(charts);
                    if (statistics != null)
                        this.BantchSaveEntityNoCommit(statistics);
                    if (rankings != null)
                        this.BantchSaveEntityNoCommit(rankings);
                    if (hmis != null)
                        this.BantchSaveEntityNoCommit(hmis);
                    this.UpdateEntityNoCommit(entity);
                });
                return true;
            });
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("NWUpdate")]
        public JsonActionResult<bool> NWUpdate([FromBody] T_PF_FORM entity)
        {
            return SafeExecute<bool>(() =>
            {
                entity.PLATFORM_CATEGORY = 1;
                this.UpdateEntity(entity);
                //var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                //formService.CreateFormConfigVersion(PFFormConfigVersionEnum.Form, entity.ID.ToString());
                return true;
            });
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult<bool> BatchDelete(string ids)
        {
            return SafeExecute<bool>(() =>
            {
                //var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                //formService.CreateFormConfigVersion(PFFormConfigVersionEnum.Form, ids);
                var arrays = string.IsNullOrEmpty(ids) ? null :
                ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(i => new Guid(i)).ToArray();
                BaseFilter filter = new BaseFilter();
                filter.SelectField = new string[] { "ID" };
                filter.IgnoreOrgRule = true;
                if (arrays != null && arrays.Length > 0)
                {
                    var edit = this.GetEntities<T_PF_PAGE_EDIT>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty), filter)
                    .Select(i => i.ID).ToArray();
                    var table = this.GetEntities<T_PF_PAGE_TABLE>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty), filter)
                    .Select(i => i.ID).ToArray();
                    var tree = this.GetEntities<T_PF_PAGE_TREE>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty), filter)
                    .Select(i => i.ID).ToArray();
                    var chart = this.GetEntities<T_PF_PAGE_CHART>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty), filter)
                    .Select(i => i.ID).ToArray();
                    var custom = this.GetEntities<T_PF_PAGE_CUSTOM>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty), filter)
                    .Select(i => i.ID).ToArray();
                    var tableIds = new List<Guid>();
                    if (edit != null)
                        tableIds.AddRange(edit);
                    if (table != null)
                        tableIds.AddRange(table);
                    if (tree != null)
                        tableIds.AddRange(tree);
                    if (chart != null)
                        tableIds.AddRange(chart);
                    if (custom != null)
                        tableIds.AddRange(custom);
                    //自定义条件删除




                    this.UnifiedCommit(() =>
                    {
                        this.DeleteEntityNoCommit<T_PF_COLUMN>(i => tableIds.Contains(i.PAGE_TABLE_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_EDIT_COLUMN>(i => tableIds.Contains(i.PAGE_EDIT_ID));
                        this.DeleteEntityNoCommit<T_PF_TREE_COLUMN>(i => tableIds.Contains(i.PAGE_TREE_ID));
                        this.DeleteEntityNoCommit<T_PF_BTN>(i => tableIds.Contains(i.PAGE_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_FORM_QUERY>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_QUERY>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_EDIT>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_TABLE>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_TREE>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_CHART>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_CUSTOM>(i => arrays.Contains(i.PAGE_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_FM_ROLE_MENU_PERM>(i => arrays.Contains(i.PERMISSION_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_EDIT_COLUMN_FILTER>(i => tableIds.Contains(i.PAGE_EDIT_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_EDIT_PANEL>(i => tableIds.Contains(i.PAGE_EDIT_ID));
                        this.DeleteEntityNoCommit<T_PF_COLUMN_FILTER>(i => tableIds.Contains(i.Nav_Column.PAGE_TABLE_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_PAGE_TABLE_PANEL>(i => tableIds.Contains(i.PAGE_TABLE_ID));
                        this.DeleteEntityNoCommit<T_FM_ROLE_MENU_PERM>(i => arrays.Contains(i.PERMISSION_FORM_ID ?? Guid.Empty));
                        this.TreeDeleteEntityNoCommit<T_PF_MENU>(i => arrays.Contains(i.MENU_FORM_ID ?? Guid.Empty));
                        this.TreeDeleteEntityNoCommit<T_PF_APPMENU>(i => arrays.Contains(i.MENU_FORM_ID ?? Guid.Empty));
                        this.TreeDeleteEntityNoCommit<T_PF_CLIENT_MENU>(i => arrays.Contains(i.MENU_FORM_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_TABLE_PARAMS>(i => tableIds.Contains(i.PAGE_TABLE_ID));
                        this.DeleteEntityNoCommit<T_PF_FORM>(i => arrays.Contains(i.ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_TABLE>(i => tableIds.Contains(i.PAGE_TABLE_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_CUSTOM_CONFIG_H_COL>(i => tableIds.Contains(i.Nav_Column.PAGE_TABLE_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_FM_USER_CUSTOM_CONFIG_H_TAB>(i => tableIds.Contains(i.PAGE_TABLE_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_EDIT>(i => tableIds.Contains(i.PAGE_EDIT_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_EDIT_COL>(i => tableIds.Contains(i.Nav_EditColumn.PAGE_EDIT_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_EDIT_H_COL>(i => tableIds.Contains(i.Nav_EditColumn.PAGE_EDIT_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_QUERY>(i => arrays.Contains(i.PAGE_FORM_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_QUERY_FIELD>(i => arrays.Contains(i.Nav_UserCCQuery.PAGE_FORM_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_QUERY_GROUP>(i => arrays.Contains(i.Nav_UserCCQuery.PAGE_FORM_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_TABLE>(i => tableIds.Contains(i.PAGE_TABLE_ID));
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_TABLE_COL>(i => tableIds.Contains(i.Nav_UserCCTable.PAGE_TABLE_ID));
                        this.DeleteEntityNoCommit<T_PF_EDIT_COLUMN_FILL_MAP>(i => tableIds.Contains(i.PAGE_EDIT_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_EDIT_COLUMN_FILL_MAP_D>(i => tableIds.Contains(i.Nav_EditColumnFillMap.PAGE_EDIT_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_FM_ROLE_MENU_PERM_BTN>(i => tableIds.Contains(i.Nav_Btn.PAGE_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_FM_ROLE_MENU_PERM_COL>(i => tableIds.Contains(i.Nav_Column.PAGE_TABLE_ID ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_FLOW_INSTANCE>(i => arrays.Contains(i.FrmId ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_FLOW_INSTANCE_TRANS_HIS>(i => arrays.Contains(i.FlowInstance.FrmId ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_FLOW_INSTANCE_OPER_HIS>(i => arrays.Contains(i.FlowInstance.FrmId ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_FLOW_SCHEME>(i => arrays.Contains(i.FrmId ?? Guid.Empty));
                        this.DeleteEntityNoCommit<T_PF_SYS_LOG>(i => arrays.Contains(i.LOG_FORM_ID ?? Guid.Empty));


                    });
                }
                return true;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_PF_FORM> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRedis")]
        public JsonActionResult<T_PF_FORM> GetRedis([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_PF_FORM>(() =>
            {
                var file = filter.FilterGroup.Rules.FirstOrDefault(i => i.Field == "ID");
                var key = file.Value.ToString();
                return this.GetEntityByRedis<T_PF_FORM>(key, filter.OrgId ?? Guid.Empty);
            });
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet, Route("GetByRedis")]

        public async Task<JsonActionResult<T_PF_FORM>> GetByRedis(string key, Guid orgid)
        {
            return await SafeExecuteAsync<T_PF_FORM>(async () =>
           {
               //var redisManager = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<RedisManager>();
               // if (CsRedisManager.KeyExists(RedisCacheKey.HardWareCheck))
               //{
               //    var value = CsRedisManager.GetClient().Get(RedisCacheKey.HardWareCheck);
               //    if (value==null||value == "True")
               //    {
               //var filter = new BaseFilter(orgid);
               //filter.SelectField = new string[] {"ID", "CODE" , "NAME", "NAME_ACRONYM", "FORM_TYPE", "URI",
               //            "CUSTOM_PARAMS", "TABLE_NAME","IS_IGNORE_PERMISSION","" };
               //Guid id;
               //if (Guid.TryParse(key,out id))
               //{
               //    return this.GetEntity<T_PF_FORM>(i => i.ID == id, filter);
               //}
               //else
               //{
               //    return this.GetEntity<T_PF_FORM>(i => i.CODE == key, filter);
               //}
               return this.GetEntityByRedis<T_PF_FORM>(key, orgid);
               //    }
               //}
               //this.ThrowError("020000");5
               //return null;



           });
        }

        /// <summary>
        /// 依据表单ID获取更新表单配置语法
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSqlsByFormId")]
        public JsonActionResult<string> GetSqlsByFormId([FromBody] KeywordFilter filter)
        {
            return SafeExecute<string>(() =>
            {
                StringBuilder sb = new StringBuilder();
                string formIdStr = filter.Keyword;
                int databaseType = LibUtils.ToInt(filter.Parameter1);//数据库类型
                string dstOrgId = filter.Parameter2;
                decimal dstFormConfigVersion = LibUtils.ToDecimal(filter.Parameter3);
                int sqlType = LibUtils.ToInt(filter.Parameter4);//语法类型
                DateTime? startTime = LibUtils.ToDateTime(filter.Parameter5);//开始时间
                bool isInitOrg = LibUtils.ToBoolean(filter.Parameter6);//是否初始化
                PFFormConfigSqlTypeEnum formConfigSqlType = (PFFormConfigSqlTypeEnum)LibUtils.ToInt(filter.Parameter7);//结果类型 
                string databaseConnStr = LibUtils.ToString(filter.Parameter8);//外部同步数据库连接字符串
                bool isContinueExc = LibUtils.ToBoolean(filter.Parameter9);//继续执行
                var databaseTypeEnum = databaseType == 0 ? DataBaseType.SQL : (DataBaseType)databaseType;
                var fromType = LibUtils.ToInt(filter.Parameter10);//导出类型（表单|菜单|跑批导出）
                var formCodes = filter.Parameter11;
                if (formConfigSqlType == PFFormConfigSqlTypeEnum.连接数据库执行)
                {
                    if (string.IsNullOrEmpty(databaseConnStr)) throw new Exception("请设置连接字符串");
                    if (sqlType == 0) throw new Exception("不支持插入和更新的语法类型");
                }

                var formIds = string.IsNullOrEmpty(formIdStr) ? new List<Guid>() : formIdStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(t => new Guid(t)).ToList();

                #region  wyw  表单编号 采用添加到列表选择的实现方式

                if (!string.IsNullOrEmpty(formCodes))
                {
                    var listFormCodes = formCodes.Split('|', StringSplitOptions.RemoveEmptyEntries).ToList();
                    var listForms = GetEntities<T_PF_FORM>(e => listFormCodes.Contains(e.CODE), null);
                    if (listForms == null || listFormCodes.Count != listForms.Count())
                    {
                        throw new Exception("请检查表单编号（表单编号不能重复、编号必须存在）");
                    }
                    else
                    {
                        foreach (var item in listForms)
                        {
                            formIds.Add(item.ID);
                        }
                    }
                }

                #endregion

                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                var list = formService.GetSqlsByFormId(filter.OrgId.Value, formIds, dstOrgId, dstFormConfigVersion,
                    databaseType == 0 ? DataBaseType.SQL : (DataBaseType)databaseType, sqlType, startTime, isInitOrg, fromType);
                if (isInitOrg)
                {
                    List<string> tempList = new List<string>();
                    var org = this.GetEntity<T_FM_ORGANIZATION>(filter.OrgId.ToString());
                    formService.GetSqlByObject(databaseTypeEnum, org, tempList, dstOrgId, sqlType);
                    if (list != null && list.Any())
                        tempList.AddRange(list);
                    #region 添加用户角色、菜单、编码规则
                    var users = this.GetEntities<T_FM_USER>(t => t.CODE.Contains("Admin") || t.CODE.Contains("System"), new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    users.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var roles = this.GetEntities<T_FM_ROLE>(t => t.ROLE_TYPE == 99, new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    roles.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var userIds = users.Select(t => t.ID).ToList();
                    var roleIds = roles.Select(t => t.ID).ToList();
                    var userBelongRoles = this.GetEntities<T_FM_USER_BELONG_ROLE>(t => userIds.Contains(t.USER_ID) && roleIds.Contains(t.BELONG_ROLE_ID), new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    userBelongRoles.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var baseConfigs = this.GetEntities<T_FM_BASE_CONFIG>(null, new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    baseConfigs.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var menus = this.GetEntities<T_PF_MENU>(null, new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    menus.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var appMenus = this.GetEntities<T_PF_APPMENU>(null, new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    appMenus.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var clientMenus = this.GetEntities<T_PF_CLIENT_MENU>(null, new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    clientMenus.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    var codeRules = this.GetEntities<T_PF_CODE_RULE>(null, new BaseFilter(filter.OrgId, FilterOrgTypeEnum.仅本组织)).ToList();
                    codeRules.ForEach(t =>
                    {
                        formService.GetSqlByObject(databaseTypeEnum, t, tempList, dstOrgId, sqlType);
                    });
                    #endregion
                    list = tempList;
                }
                if (list != null && list.Any())
                {
                    if (formConfigSqlType == PFFormConfigSqlTypeEnum.获取语法 || formConfigSqlType == PFFormConfigSqlTypeEnum.下载语法文件)
                    {
                        var tmpDatabaseType = databaseType == 0 ? DataBaseType.SQL : (DataBaseType)databaseType;
                        if (tmpDatabaseType == DataBaseType.Oracle && sqlType == 0 && formConfigSqlType == PFFormConfigSqlTypeEnum.获取语法)
                            sb.Append("begin");
                        list.ForEach(t =>
                        {
                            sb.AppendLine(t);
                        });
                        if (tmpDatabaseType == DataBaseType.Oracle && sqlType == 0 && formConfigSqlType == PFFormConfigSqlTypeEnum.获取语法)
                            sb.Append("end;");

                        if (formConfigSqlType == PFFormConfigSqlTypeEnum.下载语法文件)
                        {
                            T_PF_FILE file = new T_PF_FILE();
                            file.FILE_NAME = "config_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".sql";
                            file.FILE_TYPE = "application/octet-stream";
                            file.FILE_DATA = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                            file.ORG_ID = filter.OrgId;
                            file.IS_TEMPORARY_FILE = true;
                            this.AddEntity(file);
                            return "PF/File/GetFile?id=" + file.ID;
                        }
                        return sb.ToString();
                    }
                    else if (formConfigSqlType == PFFormConfigSqlTypeEnum.连接数据库执行)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        bool isError = false;
                        foreach (var sql in list)
                        {
                            if (isError && !isContinueExc) break;
                            var sqls = sql.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            if (!sqls.Any()) continue;
                            try
                            {
                                this.ExecuteNonQueryByConn<T_PF_FORM>(databaseTypeEnum, databaseConnStr, System.Data.CommandType.Text, sqls[0], null);
                            }
                            catch (Exception ex)
                            {
                                stringBuilder.AppendLine("执行语法" + sql + "发生错误，详情 ：" + ex.Message);
                                isError = true;
                            }
                        }
                        if (stringBuilder.Length > 0) return stringBuilder.ToString();
                        return "执行成功";
                    }
                }
                return string.Empty;
            });
        }


        /// <summary>
        /// 依据实体名获取更新语法
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSqlsByEntityName")]
        public JsonActionResult<string> GetSqlsByEntityName([FromBody] KeywordFilter filter)
        {
            return SafeExecute<string>(() =>
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrEmpty(filter.Keyword))
                    throw new Exception("请选择实体表");
                int databaseType = string.IsNullOrEmpty(filter.Parameter1) ? 0 : LibUtils.ToInt(filter.Parameter1);//数据库类型
                string dstOrgId = filter.Parameter2;
                int sqlType = LibUtils.ToInt(filter.Parameter3);//语法类型
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                var list = formService.GetSqlByEntity(databaseType == 0 ? DataBaseType.SQL : (DataBaseType)databaseType,
                        filter.OrgId.Value, filter.Keyword, dstOrgId, sqlType);

                if (list != null && list.Any())
                {
                    var tmpDatabaseType = databaseType == 0 ? DataBaseType.SQL : (DataBaseType)databaseType;
                    if (tmpDatabaseType == DataBaseType.Oracle && sqlType == 0)
                        sb.Append("begin");
                    list.ForEach(t =>
                    {
                        sb.AppendLine(t);
                    });
                    if (tmpDatabaseType == DataBaseType.Oracle && sqlType == 0)
                        sb.Append("end;");
                }
                return sb.ToString();
            });
        }

        /// <summary>
        /// 初始化组织
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ClearFromRedis")]
        public JsonActionResult<bool> ClearFormRedis([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var keyCodeList = new List<string>() {
                "T_FM_ENUM_ITEM_","T_FM_ROLE_","T_FM_ROLE_MENU_PERM_","T_FM_ROLE_GROUP","T_FM_ROLE_GROUP_BELONG_ROLE_","T_FM_ROLE_MENU_PERM_",
                "T_PF_BTN_","T_PF_COLUMN_","T_PF_EDIT_COLUMN_","T_PF_FORM_","T_PF_MENU_","T_PF_PAGE_EDIT_","T_PF_PAGE_TABLE_","T_PF_PARAM_ITEM_",
                "T_PF_PARAM_SCHEME_","T_PF_QUERY_","opt_grouplist_","opt_list_","sort_","PAGE_EDIT_","PAGE_TABLE_","PAGE_TREE_",
                "TABLE_PAGE_TABLES_","TABLE_USER_CONFIG_","USER_CUSTOM_CONFIG_","SEARCH_CONFIG_","{T_PF_FORM}"
                };
                //过滤    //"FM201_", 待办结束时间配置 
                List<string> delKeys = new List<string>();
                CSRedis.CSRedisClient redisClient = CsRedisManager.GetClient();
                foreach (var keyCode in keyCodeList)
                {
                    var keys = redisClient.Keys("*" + keyCode + "*");
                    if (keys != null && keys.Any())
                        delKeys.AddRange(keys);
                }
                if (delKeys.Any())
                    CsRedisManager.GetClient().Del(delKeys.ToArray());

                //var redisManage = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<RedisManager>();
                //var partenKeys = CsRedisManager.GetClient().Keys("T_FM_ENUM_ITEM_*");

                //var listKeys = redisManage.GetAllCacheKeys();
                //var keyCodeList = new List<string>() {
                //"T_FM_ENUM_ITEM_","T_FM_ROLE_","T_FM_ROLE_MENU_PERM_","T_FM_ROLE_GROUP","T_FM_ROLE_GROUP_BELONG_ROLE_","T_FM_ROLE_MENU_PERM_",
                //"T_PF_BTN_","T_PF_COLUMN_","T_PF_EDIT_COLUMN_","T_PF_FORM_","T_PF_MENU_","T_PF_PAGE_EDIT_","T_PF_PAGE_TABLE_","T_PF_PARAM_ITEM_",
                //"T_PF_PARAM_SCHEME_","T_PF_QUERY_","opt_grouplist_","opt_list_","sort_","PAGE_EDIT_","PAGE_TABLE_","PAGE_TREE_",
                //"TABLE_PAGE_TABLES_","TABLE_USER_CONFIG_","USER_CUSTOM_CONFIG_","SEARCH_CONFIG_","{T_PF_FORM}"
                //};
                ////过滤    //"FM201_", 待办结束时间配置 
                //List<string> delKeys = new List<string>();
                //foreach (var keyCode in keyCodeList)
                //{
                //    var keys = listKeys.Where(i => i.StartsWith(keyCode));
                //    delKeys.AddRange(keys);
                //}
                //if (delKeys.Any())
                //    CsRedisManager.GetClient().Del(delKeys.ToArray());

                return true;
            });
        }

        /// <summary>
        /// 初始化组织
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("InitOrgBySrcOrg")]
        public JsonActionResult<bool> InitOrgBySrcOrg([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                string destOrgCode = filter.Keyword;//目标组织编号
                string destOrgName = filter.Parameter1;//目标组织名称
                var org = this.GetEntity<T_FM_ORGANIZATION>(filter.OrgId.ToString());
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.InitOrgBySrcOrg(org.CODE, destOrgCode, destOrgName);
                return true;
            });
        }

        private void DoSysBaseConfig(Guid srcOrgId, List<Guid> destOrgIds)
        {
            List<Guid> orgIds = new List<Guid>();
            orgIds.Add(srcOrgId);
            orgIds.AddRange(destOrgIds);

            var baseConfigs = this.GetEntities<T_FM_BASE_CONFIG>(t => orgIds.Contains(t.ORG_ID ?? Guid.Empty), new BaseFilter()).ToList();
            var srcBaseConfig = baseConfigs.FirstOrDefault(t => t.ORG_ID == srcOrgId);
            if (srcBaseConfig != null)
            {
                List<T_FM_BASE_CONFIG> addBaseConfigs = new List<T_FM_BASE_CONFIG>();
                destOrgIds.ForEach(t =>
                {
                    var destBaseConfig = baseConfigs.FirstOrDefault(t1 => t1.ORG_ID == t);
                    if (destBaseConfig != null)
                        return;
                    var destOrg = this.GetEntity<T_FM_ORGANIZATION>(t.ToString());
                    destBaseConfig = new T_FM_BASE_CONFIG();
                    var code = destBaseConfig.CODE;
                    var name = destBaseConfig.NAME;
                    var logo = destBaseConfig.LOGO_ID;
                    CopyUtils.CopyObject(destBaseConfig, srcBaseConfig);
                    destBaseConfig.ORG_ID = t;
                    destBaseConfig.CODE = code;
                    destBaseConfig.NAME = name;
                    destBaseConfig.LOGO_ID = logo;

                    addBaseConfigs.Add(destBaseConfig);
                });
                if (addBaseConfigs.Any())
                    this.BantchAddEntity(addBaseConfigs);
            }
        }


        /// <summary>
        /// 初始化组织
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SynchFormConfigByOrg")]
        public JsonActionResult<bool> SynchFormConfigByOrg([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                string srcOrgId = filter.Keyword;//来源组织ID
                string destOrgIdStr = filter.Parameter1;//目标组织ID列表
                DateTime? startTime = LibUtils.ToDateTime(filter.Parameter2);
                bool isInit = LibUtils.ToBoolean(filter.Parameter3);
                if (string.IsNullOrEmpty(srcOrgId))
                    throw new Exception("来源组织不允许为空");
                if (string.IsNullOrEmpty(destOrgIdStr))
                    throw new Exception("目标组织列表不允许为空");
                if (!isInit && startTime == null)
                    throw new Exception("请填写开始时间");
                var destOrgIds = destOrgIdStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(t => new Guid(t)).ToList();
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                if (isInit)
                {
                    List<T_FM_USER> users = new List<T_FM_USER>();
                    List<T_FM_ROLE> roles = new List<T_FM_ROLE>();
                    List<T_FM_USER_BELONG_ROLE> userRoles = new List<T_FM_USER_BELONG_ROLE>();
                    var destOrgs = this.GetEntities<T_FM_ORGANIZATION>(t => destOrgIds.Contains(t.ID), new BaseFilter()).ToList();
                    foreach (var destOrg in destOrgs)
                    {
                        var isExistUser = this.GetEntities<T_FM_USER>(t => t.ORG_ID == destOrg.ID, new BaseFilter()).Any();
                        if (!isExistUser)
                        {
                            T_FM_USER user = new T_FM_USER();
                            user.CODE = destOrg.CODE + "Admin";
                            user.NAME = destOrg.CODE + "Admin";
                            user.ORG_ID = destOrg.ID;
                            user.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";//默认密码为123456
                            users.Add(user);

                            T_FM_USER sysUser = new T_FM_USER();
                            sysUser.CODE = destOrg.CODE + "System";
                            sysUser.NAME = destOrg.CODE + "System";
                            sysUser.ORG_ID = destOrg.ID;
                            sysUser.PASSWORD = "E10ADC3949BA59ABBE56E057F20F883E";//默认密码为123456
                            users.Add(sysUser);

                            T_FM_ROLE role = new T_FM_ROLE();
                            role.CODE = destOrg.CODE + "Admin";
                            role.NAME = destOrg.CODE + "Admin";
                            role.ORG_ID = destOrg.ID;
                            role.ROLE_TYPE = (int)FMRoleTypeEnum.管理角色;
                            role.PLATFORM_TYPE = (int)PFPlatTypeEnum.后台;
                            roles.Add(role);

                            T_FM_ROLE clientRole = new T_FM_ROLE();
                            clientRole.CODE = destOrg.CODE + "ClientAdmin";
                            clientRole.NAME = destOrg.CODE + "ClientAdmin";
                            clientRole.ORG_ID = destOrg.ID;
                            clientRole.ROLE_TYPE = (int)FMRoleTypeEnum.管理角色;
                            clientRole.PLATFORM_TYPE = (int)PFPlatTypeEnum.客户端;
                            roles.Add(clientRole);

                            T_FM_ROLE appRole = new T_FM_ROLE();
                            appRole.CODE = destOrg.CODE + "AppAdmin";
                            appRole.NAME = destOrg.CODE + "AppAdmin";
                            appRole.ORG_ID = destOrg.ID;
                            appRole.ROLE_TYPE = (int)FMRoleTypeEnum.管理角色;
                            appRole.PLATFORM_TYPE = (int)PFPlatTypeEnum.APP;
                            roles.Add(appRole);

                            T_FM_USER_BELONG_ROLE userRole = new T_FM_USER_BELONG_ROLE();
                            userRole.USER_ID = user.ID;
                            userRole.BELONG_ROLE_ID = role.ID;
                            userRole.ORG_ID = destOrg.ID;
                            userRoles.Add(userRole);
                            userRole = new T_FM_USER_BELONG_ROLE();
                            userRole.USER_ID = user.ID;
                            userRole.BELONG_ROLE_ID = clientRole.ID;
                            userRole.ORG_ID = destOrg.ID;
                            userRoles.Add(userRole);
                            userRole = new T_FM_USER_BELONG_ROLE();
                            userRole.USER_ID = user.ID;
                            userRole.BELONG_ROLE_ID = appRole.ID;
                            userRole.ORG_ID = destOrg.ID;
                            userRoles.Add(userRole);
                        }

                    }

                    UnifiedCommit(() =>
                    {
                        if (users.Any())
                            this.BantchAddEntityNoCommit(users);
                        if (roles.Any())
                            this.BantchAddEntityNoCommit(roles);
                        if (userRoles.Any())
                            this.BantchAddEntityNoCommit(userRoles);
                    });
                    formService.InitOrgByOrg(new Guid(srcOrgId), destOrgIds, startTime);
                }
                else
                    formService.SynchFormConfigByOrg(new Guid(srcOrgId), destOrgIds, startTime);
                this.DoSysBaseConfig(new Guid(srcOrgId), destOrgIds);
                return true;
            });
        }


        /// <summary>
        /// 执行语法并且获取执行结果
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ExcuteSqlAndGetResult")]
        public JsonActionResult<ExecuteSqlResult> ExcuteSqlAndGetResult([FromBody] KeywordFilter filter)
        {
            return SafeExecute<ExecuteSqlResult>(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword))
                    throw new Exception("语法不允许为空");
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                return formService.ExcuteSqlAndGetResult(filter.Keyword);
            });
        }

        /// <summary>
        /// 依据表名称初始化表单配置
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("InitFormConfigByName")]
        public JsonActionResult<bool> InitFormConfigByName([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var tableName = filter.Keyword;
                var userId = LibUtils.ToGuid(filter.Parameter1);
                var configType = (PFInitFormConfigTypeEnum)LibUtils.ToInt(filter.Parameter2);
                var menuParentId = LibUtils.ToGuid(filter.Parameter3);
                var menuName = LibUtils.ToString(filter.Parameter4);
                string menuIcon = LibUtils.ToString(filter.Parameter5);
                bool isAddSend = false;
                if (!string.IsNullOrEmpty(filter.Parameter6))
                {
                    try
                    {
                        isAddSend = Convert.ToBoolean(filter.Parameter6);
                    }
                    catch
                    {
                        isAddSend = false;
                    }
                }
                var entityOperateService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IEntityOperateService>();
                entityOperateService.InitFormConfigByName(filter.OrgId.Value,
                    tableName, userId, configType, menuParentId, menuName, menuIcon, isAddSend);
                return true;
            });
        }



        [HttpPost, Route("ChangeNum")]
        public JsonActionResult<bool> ChangeNum([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(filter.Parameter1) || string.IsNullOrEmpty(filter.Parameter2)
                || string.IsNullOrEmpty(filter.Parameter3) || string.IsNullOrEmpty(filter.Keyword))
                    this.ThrowError("020005");
                Type type = ReflectHelper.FindTypeInCurrentDomain(filter.Keyword);
                if (type == null)
                    this.ThrowError("020006", filter.Keyword);
                string param1 = filter.Parameter1;
                string param2 = filter.Parameter2;

                var methodInfo = this.GetType().GetMethod("GetObjEntity", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);

                var entity1 = methodInfo.MakeGenericMethod(new Type[] { type }).Invoke(this, new object[] { param1 });

                var entity2 = methodInfo.MakeGenericMethod(new Type[] { type }).Invoke(this, new object[] { param2 });

                if (entity1 == null || entity2 == null)
                    this.ThrowError("020007");
                string sortField = filter.Parameter3;
                if (sortField == "ID" || sortField == "CREATE_TIME" || sortField == "MODIFY_TIME" || sortField.IndexOf('.') > 0)
                    this.ThrowError("020008", sortField);
                var prop = type.GetProperty(sortField);
                if (prop == null)
                    this.ThrowError("020009", sortField);
                var entity1Value = prop.GetValue(entity1);
                var entity2Value = prop.GetValue(entity2);
                prop.SetValue(entity1, entity2Value);
                prop.SetValue(entity2, entity1Value);

                var methodUpdate = this.GetType().GetMethod("UpdateObjEntity", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);


                methodUpdate.MakeGenericMethod(new Type[] { type }).Invoke(this, new object[] { entity1, sortField });
                methodUpdate.MakeGenericMethod(new Type[] { type }).Invoke(this, new object[] { entity2, sortField });
                return true;
            });
        }

        private T GetObjEntity<T>(string id) where T : MesEntityBase, new()
        {
            return this.GetEntity<T>(id);
        }

        private bool UpdateObjEntity<T>(T entity, string updateField) where T : MesEntityBase, new()
        {
            return this.UpdateEntity<T>(entity, updateField);
        }

    }
}
