using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.Msg;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.ApiModel.FM;
using APT.BaseData.Domain.Entities.FM;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Diagnostics;
using APT.Utility;
using NPOI.SS.Formula.Functions;
using System.Threading.Tasks;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.Infrastructure.Api.Redis;
using System.Configuration;
using APT.Infrastructure.Api;

namespace APT.PF.WebApiControllers.Api.PF
{
    [Route("api/PF/PageTable")]
    [APT.Infrastructure.Api.RootOrg]
    public class PageTableController : AuthorizeTreeApiController<T_PF_PAGE_TABLE>
    {

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

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_PF_PAGE_TABLE> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_PF_PAGE_TABLE> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }

        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_PF_PAGE_TABLE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var dataBaseObj = this.GetEntity<T_PF_PAGE_TABLE>(i => i.ID == entity.ID);
                if (dataBaseObj == null)
                {
                    var editColumns = new List<T_PF_COLUMN>();
                    if (!string.IsNullOrEmpty(entity.DATA_TABLE))
                    {
                        //增加配置字段
                        var fileds = DataHelper.EntityFieldList(entity.DATA_TABLE);

                        foreach (var filed in fileds)
                        {
                            var editColum = new T_PF_COLUMN();
                            editColum.ORG_ID = entity.ORG_ID;
                            editColum.IS_DEFAULT = filed.IsDefault;
                            editColum.FIELD_NAME = filed.FileName;
                            editColum.PAGE_TABLE_ID = entity.ID;
                            editColum.LABEL = filed.Description;
                            editColum.ENUM = filed.EnumName;
                            editColum.ID = Guid.NewGuid();
                            editColum.TABLE_NAME = entity.TABLE_NAME;
                            editColum.PAGE_TABLE_ID = entity.ID;
                            editColumns.Add(editColum);
                        }
                    }

                    UnifiedCommit(() =>
                    {
                        this.AddEntityNoCommit(entity);
                        if (editColumns.Count > 0)
                        {
                            this.BantchAddEntityNoCommit(editColumns);
                        }

                    });

                }
                else
                {
                    this.UpdateEntity(entity);
                }
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.CreateFormConfigVersion(PFFormConfigVersionEnum.PageTable, entity.ID.ToString());
                return true;

            });

        }
        /// <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.PageTable, id);
                List<Guid> ids = new List<Guid>();
                ids.Add(new Guid(id));
                this.DoDelete(ids);
                return true;
            });
        }

        [HttpPost, Route("TreeData")]
        public JsonActionResult<IEnumerable<TreeNode<T_PF_PAGE_TABLE>>> TreeData([FromBody] KeywordFilter filter)
        {
            return WitTreeOrderEntities(null, filter);
        }


        private void DoDelete(List<Guid> ids)
        {
            this.DeleteEntity<T_PF_COLUMN>(t => ids.Contains(t.PAGE_TABLE_ID ?? Guid.Empty));
            this.DeleteEntity<T_PF_TABLE_PARAMS>(t => ids.Contains(t.PAGE_TABLE_ID));
            this.DeleteEntity<T_FM_USER_CUSTOM_CONFIG_H_COL>(t => ids.Contains(t.Nav_HiddenTable.PAGE_TABLE_ID));
            this.DeleteEntity<T_FM_USER_CUSTOM_CONFIG_H_TAB>(t => ids.Contains(t.PAGE_TABLE_ID));
            this.DeleteEntity<T_FM_USER_C_C_TABLE_COL>(t => ids.Contains(t.Nav_UserCCTable.PAGE_TABLE_ID));
            this.DeleteEntity<T_FM_USER_C_C_TABLE>(t => ids.Contains(t.PAGE_TABLE_ID));
            this.DeleteEntity<T_PF_PAGE_TABLE>(t => ids.Contains(t.ID));
        }

        /// <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.PageTable, ids);
                var arrays = string.IsNullOrEmpty(ids) ? null : ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(t => new Guid(t)).ToList();
                if (arrays != null && arrays.Count > 0)
                    this.DoDelete(arrays);
                return true;
            });
        }
        /// <summary>
        /// 根据ID获得实体数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_PF_PAGE_TABLE> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }

        /// <summary>
        /// 所有表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetTablePageConfigInfo")]
        public JsonActionResult<TableModel> GetTablePageConfigInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<TableModel>(() =>
            {
                string userId = filter.Parameter1;
                filter.OrgType = FilterOrgTypeEnum.仅本组织;
                var id = "";
                var idRules = filter.FilterGroup.Rules.FirstOrDefault(i => i.Field == "ID");
                if (idRules != null)
                {
                    id = idRules.Value.ToString();

                }
                var redisCode = string.Format(RedisCacheKey.PageTableRedisKey, id, filter.GetOrgId());
                bool isRedisConfig = true;
                var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
                if (!string.IsNullOrEmpty(redisConfig))
                    isRedisConfig = bool.Parse(redisConfig);
                if (isRedisConfig)
                {
                    if (CsRedisManager.KeyExists(redisCode))
                        return CsRedisManager.StringGet<TableModel>(redisCode);
                }
                var page = this.GetEntity<T_PF_PAGE_TABLE>(id);
                if (page == null)
                    this.ThrowError("020015");
                //var page = pages.FirstOrDefault(i => i.ID == new Guid(id));
                var tableModel = new TableModel();
                //列
                var baseFiler = new BaseFilter();
                baseFiler.OrgId = filter.OrgId;
                baseFiler.Sort = "NUM";
                baseFiler.Order = DbOrder.ASC;
                baseFiler.OrgType = FilterOrgTypeEnum.仅本组织;
                var colums = this.GetOrderEntities<T_PF_COLUMN>(i => i.PAGE_TABLE_ID == page.ID, baseFiler, "Nav_Filters").ToList();
                //var colums = this.GetEntitiesByRedis<T_PF_COLUMN>(null, baseFiler,
                //    page.ID.ToString()).ToList();
                ////var colums = this.GetEntities<T_PF_COLUMN>(i=>i.PAGE_TABLE_ID==page.ID, baseFiler).ToList();
                ////var columsList = this.GetEntitiesByRedis<T_PF_COLUMN>(filter.GetOrgId());
                ////var colums = columsList.Where(i => i.PAGE_TABLE_ID == page.ID).ToList();
                ////var filters = this.GetEntitiesByRedis<T_PF_COLUMN_FILTER>(filter.GetOrgId());
                //foreach (var c in colums)
                //{
                //    c.Nav_Filters = this.GetEntitiesByRedis<T_PF_COLUMN_FILTER>(null, new BaseFilter(filter.GetOrgId()), c.ID.ToString()); 
                //}
                //子表
                //Expression<Func<T_PF_PAGE_TABLE, bool>> expression = t => t.PARENT_ID == page.ID;
                //var hasChild = this.GetCount<T_PF_PAGE_TABLE>(expression, new BaseFilter());
                //filter
                //Expression<Func<T_PF_TABLE_PARAMS, bool>> paramsExpress = t => t.PAGE_TABLE_ID == page.ID;
                //var param = this.GetEntities<T_PF_TABLE_PARAMS>(paramsExpress, new BaseFilter()).ToList();

                //
                var paramss = this.GetEntitiesByRedis<T_PF_TABLE_PARAMS>(i => i.ORG_ID == filter.GetOrgId(), new BaseFilter(filter.GetOrgId()), page.ID.ToString());
                var param = paramss.ToList();

                //var btns = this.GetOrderEntities<T_PF_BTN>(t => t.PAGE_TABLE_ID == page.ID && t.BTN_FUN_TYPE == (int)PFBtnFuncTypeEnum.按钮, baseFiler).ToList();
                //
                var btnList = this.GetEntitiesByRedis<T_PF_BTN>(null, new BaseFilter(filter.OrgId), page.ID.ToString());
                var btns = btnList.Where(t => t.BTN_FUN_TYPE == (int)PFBtnFuncTypeEnum.按钮).ToList();

                //var rowBtns = this.GetOrderEntities<T_PF_BTN>(t => t.PAGE_TABLE_ID == page.ID && t.BTN_FUN_TYPE == (int)PFBtnFuncTypeEnum.行按钮, baseFiler).ToList();
                //
                var rowBtns = btnList.Where(t => t.PAGE_TABLE_ID == page.ID && t.BTN_FUN_TYPE == (int)PFBtnFuncTypeEnum.行按钮).ToList();

                //var panels = this.GetOrderEntities<T_PF_PAGE_TABLE_PANEL>(t => t.PAGE_TABLE_ID == page.ID && t.IS_DISPLAY, baseFiler).ToList();
                //
                var panels = this.GetEntitiesByRedis<T_PF_PAGE_TABLE_PANEL>(null, new BaseFilter(filter.OrgId), page.ID.ToString());
                panels = panels.Where(t => t.IS_DISPLAY).ToList();

                if (page.PARAM_SCHEME_ID != null)
                {
                    //var paramScheme = this.GetEntity<T_PF_PARAM_SCHEME>(t => t.ID == page.PARAM_SCHEME_ID && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用,
                    //        new string[] { "Nav_Details.Nav_ParamItem" });
                    //
                    var paramScheme = this.GetEntityByRedis<T_PF_PARAM_SCHEME>(page.PARAM_SCHEME_ID ?? Guid.Empty, filter.GetOrgId());
                    if (paramScheme != null && paramScheme.ENABLE_STATUS == (int)FMEnableStatusEnum.启用)
                    {
                        var details = this.GetEntitiesByRedis<T_PF_PARAM_SCHEME_DETAIL>(null, new BaseFilter(filter.OrgId), paramScheme.ID.ToString(), "Nav_ParamItem");
                        details = details.OrderBy(t => t.NUM).ToList();

                        //var items = this.GetEntitiesByRedis<T_PF_PARAM_ITEM>(filter.GetOrgId());
                        //foreach (var d in details)
                        //{
                        //    d.Nav_ParamItem = items.FirstOrDefault(i => i.ID == d.PARAM_ITEM_ID);
                        //}
                        //paramScheme.Nav_Details = details;
                    }
                    if (paramScheme != null && paramScheme.Nav_Details != null && paramScheme.Nav_Details.Any())
                    {
                        T_PF_PAGE_TABLE_PANEL tablePanel = null;
                        if (paramScheme.IS_PANEL_SHOW.HasValue && paramScheme.IS_PANEL_SHOW.Value)
                        {
                            tablePanel = new T_PF_PAGE_TABLE_PANEL()
                            {
                                ORG_ID = page.ORG_ID,
                                PAGE_TABLE_ID = page.ID,
                                LABEL = "实体参数",
                                IS_DISPLAY = true,
                                NUM = 10000,
                            };
                            panels.Add(tablePanel);
                        }
                        var sortList = paramScheme.Nav_Details.OrderBy(t => t.NUM).ToList();
                        foreach (var item in sortList)
                        {
                            if (item.Nav_ParamItem == null || !item.IS_SHOW
                                || item.Nav_ParamItem.ENABLE_STATUS == (int)FMEnableStatusEnum.禁用) continue;
                            T_PF_COLUMN column = new T_PF_COLUMN()
                            {
                                ID = item.ID,
                                ORG_ID = page.ORG_ID,
                                PAGE_TABLE_ID = page.ID,
                                FIELD_NAME = "Nav_SysParams." + item.Nav_ParamItem.FIELD_NAME,
                                LABEL = item.Nav_ParamItem.LABEL,
                                CONTROL_TYPE = item.Nav_ParamItem.TABLE_CONTROL_TYPE,
                                ENUM = item.Nav_ParamItem.ENUM,
                                NUM = 10000 + item.NUM,
                                WIDTH = item.Nav_ParamItem.WIDTH,
                            };
                            if (tablePanel != null)
                                column.PAGE_TABLE_PANEL_ID = tablePanel.ID;
                            colums.Add(column);
                        }
                    }
                }

                //自定义参数
                tableModel.PageTable = page;
                tableModel.HasChildren = this.IsAny<T_PF_PAGE_TABLE>(i => i.PARENT_ID == page.ID, new BaseFilter(filter.OrgId));
                tableModel.Nav_Columns = colums;
                tableModel.TableParams = param;
                tableModel.Btns = btns;
                tableModel.RowBtns = rowBtns;
                tableModel.Nav_Form = this.GetEntityByRedis<T_PF_FORM>(page.PAGE_FORM_ID ?? Guid.Empty, filter.GetOrgId());
                tableModel.Nav_TablePanels = panels;
                CsRedisManager.StringSet(redisCode, tableModel);
                return tableModel;
            });
        }

        /// <summary>
        /// 获取用户自定义隐藏信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetTablePageHiddenInfo")]
        public JsonActionResult<TableUserCustomInfoModel> GetTablePageHiddenInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<TableUserCustomInfoModel>(() =>
            {
                var pageId = LibUtils.ToGuid(filter.Keyword);
                var userId = LibUtils.ToGuid(filter.Parameter1);
                if (pageId == null)
                    throw new Exception("Table ID不允许为空");
                if (userId == null)
                    throw new Exception(ErrMsg.FM_NO_USER_ID);

                TableUserCustomInfoModel result = new TableUserCustomInfoModel();
                List<T_PF_COLUMN> hiddenCols = GetUserCustomHiddenCols(userId, pageId, filter);
                result.Nav_CustomHiddenCols = hiddenCols;
                return result;
            });
        }


        /// <summary>
        /// 获取用户自定义配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserCustomConfigInfo")]
        public async Task<JsonActionResult<TableUserCustomInfoModel>> GetUserCustomConfigInfo([FromBody] KeywordFilter filter)
        {

            return await SafeExecuteAsync<TableUserCustomInfoModel>(async () =>
            {

                var pageId = LibUtils.ToGuid(filter.Keyword);
                var userId = LibUtils.ToGuid(filter.Parameter1);
                if (pageId == null)
                    throw new Exception("Table ID不允许为空");
                if (userId == null)
                    throw new Exception(ErrMsg.FM_NO_USER_ID);
                var redisCode = string.Format(RedisCacheKey.UserCustomConfigRedisKey, pageId.ToString() + userId, filter.GetOrgId());
                bool isRedisConfig = true;
                var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
                if (!string.IsNullOrEmpty(redisConfig))
                    isRedisConfig = bool.Parse(redisConfig);
                if (isRedisConfig)
                {
                    if (CsRedisManager.KeyExists(redisCode))
                        return CsRedisManager.GetClient().Get<TableUserCustomInfoModel>(redisCode);
                }
                TableUserCustomInfoModel result = new TableUserCustomInfoModel();
                var hiddenCols = GetUserCustomHiddenCols(userId, pageId, filter);
                var cols = GetUserCustomCols(userId, pageId, result, filter.GetOrgId());
                result.Nav_CustomHiddenCols = hiddenCols;
                result.Nav_CustomCols = cols;
                CsRedisManager.GetClient().Set(redisCode, result);
                return result;
            });

        }



        /// <summary>
        /// 保存用户自定义配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SaveUserCustomConfigInfo")]
        public JsonActionResult<bool> SaveUserCustomConfigInfo([FromBody] SaveTableUserCustomInfoModel model)
        {
            return SafeExecute<bool>(() =>
            {
                if (model == null) return false;

                //不存在新增用户配置表
                var customConfig = this.GetEntity<T_FM_USER_CUSTOM_CONFIG>(t => t.USER_ID == model.UserId);
                if (customConfig == null)
                {
                    customConfig = new T_FM_USER_CUSTOM_CONFIG();
                    customConfig.ORG_ID = model.OrgId;
                    customConfig.USER_ID = model.UserId;
                    this.AddEntity(customConfig);
                }


                List<Guid> deleteHColIds = new List<Guid>();
                List<T_FM_USER_CUSTOM_CONFIG_H_COL> addHCols = new List<T_FM_USER_CUSTOM_CONFIG_H_COL>();

                List<Guid> deleteCustomColIds = new List<Guid>();
                List<T_FM_USER_C_C_TABLE_COL> saveCustomCols = new List<T_FM_USER_C_C_TABLE_COL>();

                #region 隐藏列

                //不存在新增隐藏表
                var customConfigHTab = this.GetEntity<T_FM_USER_CUSTOM_CONFIG_H_TAB>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_TABLE_ID == model.PageTableId);
                if (customConfigHTab == null)
                {
                    customConfigHTab = new T_FM_USER_CUSTOM_CONFIG_H_TAB();
                    customConfigHTab.ORG_ID = model.OrgId;
                    customConfigHTab.PAGE_TABLE_ID = model.PageTableId;
                    customConfigHTab.USER_CUSTOM_CONFIG_ID = customConfig.ID;
                    this.AddEntity(customConfigHTab);
                }


                //数据库已有数据
                var dbHCols = this.GetEntities<T_FM_USER_CUSTOM_CONFIG_H_COL>(t => t.USER_CUSTOM_CONFIG_H_TAB_ID == customConfigHTab.ID, new BaseFilter()).ToList();
                var hCols = model.HiddenColumnIds;
                //删除
                if (dbHCols != null && dbHCols.Any())
                {
                    foreach (var item in dbHCols)
                    {
                        if (hCols == null || !hCols.Contains(item.COLUMN_ID.ToString()))
                            deleteHColIds.Add(item.ID);
                    }
                }
                //新增
                if (hCols != null && hCols.Any())
                {
                    foreach (var item in hCols)
                    {
                        if (dbHCols == null || !dbHCols.Any(t => t.COLUMN_ID.ToString() == item))
                        {
                            T_FM_USER_CUSTOM_CONFIG_H_COL hCol = new T_FM_USER_CUSTOM_CONFIG_H_COL();
                            hCol.ORG_ID = model.OrgId;
                            hCol.USER_CUSTOM_CONFIG_H_TAB_ID = customConfigHTab.ID;
                            hCol.COLUMN_ID = new Guid(item);
                            addHCols.Add(hCol);
                        }
                    }
                }
                #endregion

                #region  自定义列信息


                //不存在新增隐藏表
                var customConfigTable = this.GetEntity<T_FM_USER_C_C_TABLE>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_TABLE_ID == model.PageTableId);
                if (customConfigTable == null)
                {
                    customConfigTable = new T_FM_USER_C_C_TABLE();
                    customConfigTable.ORG_ID = model.OrgId;
                    customConfigTable.PAGE_TABLE_ID = model.PageTableId;
                    customConfigTable.USER_CUSTOM_CONFIG_ID = customConfig.ID;
                    this.AddEntity(customConfigTable);
                }


                //数据库已有数据
                var dbCustomConfigCols = this.GetEntities<T_FM_USER_C_C_TABLE_COL>(t => t.USER_C_C_TABLE_ID == customConfigTable.ID, new BaseFilter()).ToList();
                var customConfigCols = model.Columns;
                //删除
                if (dbCustomConfigCols != null && dbCustomConfigCols.Any())
                {
                    foreach (var item in dbCustomConfigCols)
                    {
                        var col = customConfigCols == null ? null : customConfigCols.FirstOrDefault(t => t.COLUMN_ID == item.COLUMN_ID);
                        if (col == null)
                            deleteCustomColIds.Add(item.ID);
                        else
                        {
                            item.LABEL = col.LABEL;
                            item.NUM = col.NUM;
                            saveCustomCols.Add(item);
                        }
                    }
                }
                //新增
                if (customConfigCols != null && customConfigCols.Any())
                {
                    foreach (var item in customConfigCols)
                    {
                        if (dbCustomConfigCols == null || !dbCustomConfigCols.Any(t => t.COLUMN_ID == item.COLUMN_ID))
                        {
                            T_FM_USER_C_C_TABLE_COL hCol = new T_FM_USER_C_C_TABLE_COL();
                            CopyUtils.CopyObject(hCol, item);
                            hCol.ORG_ID = model.OrgId;
                            hCol.USER_C_C_TABLE_ID = customConfigTable.ID;
                            saveCustomCols.Add(hCol);
                        }
                    }
                }

                #endregion
                this.UnifiedCommit(() =>
                {
                    if (addHCols.Any())
                        this.BantchAddEntityNoCommit(addHCols);

                    if (saveCustomCols.Any())
                        this.BantchSaveEntityNoCommit(saveCustomCols);

                    if (deleteHColIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_CUSTOM_CONFIG_H_COL>(t => deleteHColIds.Contains(t.ID));
                    if (deleteCustomColIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_TABLE_COL>(t => deleteCustomColIds.Contains(t.ID));
                });
                var redisCode = string.Format(RedisCacheKey.UserCustomConfigRedisKey, model.PageTableId.ToString() + model.UserId, model.OrgId);
                CsRedisManager.KeyDelete(redisCode);
                return true;
            });
        }


        /// <summary>
        /// 保存用户自定义配置信息 默认分页条数
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SaveUserCustomConfigInfoForPageSize")]
        public JsonActionResult<bool> SaveUserCustomConfigInfoForPageSize([FromBody] SaveTableUserCustomInfoModel model)
        {
            return SafeExecute<bool>(() =>
            {
                if (model == null) return false;

                //不存在新增用户配置表
                var customConfig = this.GetEntity<T_FM_USER_CUSTOM_CONFIG>(t => t.USER_ID == model.UserId);
                if (customConfig == null)
                {
                    customConfig = new T_FM_USER_CUSTOM_CONFIG();
                    customConfig.ORG_ID = model.OrgId;
                    customConfig.USER_ID = model.UserId;
                    this.AddEntity(customConfig);
                }

                //不存在新增隐藏表
                var customConfigTable = this.GetEntity<T_FM_USER_C_C_TABLE>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_TABLE_ID == model.PageTableId);
                if (customConfigTable == null)
                {
                    customConfigTable = new T_FM_USER_C_C_TABLE();
                    customConfigTable.ORG_ID = model.OrgId;
                    customConfigTable.PAGE_TABLE_ID = model.PageTableId;
                    customConfigTable.USER_CUSTOM_CONFIG_ID = customConfig.ID;
                    customConfigTable.PAGE_SIZE = model.DefaultPageSize;
                    this.AddEntity(customConfigTable);
                }
                else
                {
                    customConfigTable.PAGE_SIZE = model.DefaultPageSize;
                    this.UpdateEntity(customConfigTable);
                }
                var redisCode = string.Format(RedisCacheKey.UserCustomConfigRedisKey, model.PageTableId.ToString() + model.UserId, model.OrgId);
                CsRedisManager.KeyDelete(redisCode);
                return true;
            });
        }



        /// <summary>
        /// 获取列表页中列表信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetTablePageTables")]
        public JsonActionResult<TablePageModel> GetTablePageTables([FromBody] KeywordFilter filter)
        {
            return SafeExecute<TablePageModel>(() =>
            {
                string parentIdStr = filter.Parameter1;
                string tableIdStr = filter.Parameter2;
                filter.OrgType = FilterOrgTypeEnum.仅本组织;
                bool isRedisConfig = true;
                var redisCode = string.Format(RedisCacheKey.TablePageTablesRedisKey, filter.Keyword, parentIdStr, tableIdStr, filter.GetOrgId());
                var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
                if (!string.IsNullOrEmpty(redisConfig))
                    isRedisConfig = bool.Parse(redisConfig);
                if (isRedisConfig)
                {
                    if (CsRedisManager.KeyExists(redisCode))
                        return CsRedisManager.StringGet<TablePageModel>(redisCode);
                }
                var form = this.GetEntity<T_PF_FORM>(i => i.CODE == filter.Keyword,new BaseFilter(filter.GetOrgId()));
                if (form == null)
                    return null;

                TablePageModel result = new TablePageModel();
                result.Nav_Form = form;
                Guid? parentId = null;
                if (!string.IsNullOrEmpty(parentIdStr))
                    parentId = new Guid(parentIdStr);
                //Expression<Func<T_PF_PAGE_TABLE, bool>> expression = t => t.PAGE_FORM_ID == form.ID && t.PARENT_ID == parentId;


                //if (!string.IsNullOrEmpty(tableIdStr))
                //    expression = expression.And(t => t.ID == new Guid(tableIdStr));
                //result.Nav_Tables = this.GetOrderEntities<T_PF_PAGE_TABLE>(expression, new BaseFilter() { Sort = "NUM" }).ToList();

                filter.Sort = "NUM";
                var redisFilter = new BaseFilter(filter.GetOrgId());
                redisFilter.Sort = "NUM";
                var pages = this.GetEntitiesByRedis<T_PF_PAGE_TABLE>(null, redisFilter, form.ID.ToString());
                var page = pages.Where(t => t.PARENT_ID == parentId).ToList();
                if (!string.IsNullOrEmpty(tableIdStr))
                {
                    page = page.Where(t => t.ID == new Guid(tableIdStr)).ToList();
                }
                result.Nav_Tables = page;
                CsRedisManager.StringSet(redisCode, result);
                return result;
            });
        }


        #region  私有函数
        /// <summary>
        /// 获取用户自定义隐藏列
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageTableId"></param>
        /// <returns></returns>
        private List<T_PF_COLUMN> GetUserCustomHiddenCols(Guid? userId, Guid? pageTableId, BaseFilter filter)
        {
            List<T_PF_COLUMN> hiddenCols = null;
            if (userId != null)
            {
                var baseFilter = new BaseFilter(filter.GetOrgId());
                //var customConfig = this.GetEntityByRedis<T_FM_USER_CUSTOM_CONFIG>(userId ?? Guid.Empty, filter.GetOrgId());
                var customConfigs = this.GetEntitiesByRedis<T_FM_USER_CUSTOM_CONFIG>(null, baseFilter, userId.ToString());
                var customConfig = customConfigs.FirstOrDefault();
                if (customConfig != null)
                {
                    //var hiddenTab = this.GetEntity<T_FM_USER_CUSTOM_CONFIG_H_TAB>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_TABLE_ID == pageTableId);
                    var hiddenTabas = this.GetEntitiesByRedis<T_FM_USER_CUSTOM_CONFIG_H_TAB>(null, baseFilter, customConfig.ID.ToString())
                        .Where(t => t.PAGE_TABLE_ID == pageTableId).ToList();
                    var hiddenTab = hiddenTabas.FirstOrDefault(t => t.PAGE_TABLE_ID == pageTableId);

                    if (hiddenTab != null)
                    {
                        //var tmpHiddenCols = this.GetEntities<T_FM_USER_CUSTOM_CONFIG_H_COL>(t => t.USER_CUSTOM_CONFIG_H_TAB_ID == hiddenTab.ID, 
                        //    new BaseFilter(), new string[] { "Nav_Column" }).ToList();
                        var tmpHiddenCols = this.GetEntitiesByRedis<T_FM_USER_CUSTOM_CONFIG_H_COL>(null, baseFilter, hiddenTab.ID.ToString())
                            .ToList();

                        if (tmpHiddenCols.Any())
                        {
                            var columns = this.GetEntitiesByRedis<T_PF_COLUMN>(null, baseFilter, hiddenTab.PAGE_TABLE_ID.ToString());
                            foreach (var hc in tmpHiddenCols)
                            {
                                var column = columns.FirstOrDefault(i => i.ID == hc.COLUMN_ID);
                                hc.Nav_Column = column;
                            }
                            if (tmpHiddenCols.Count > 0)
                            {
                                hiddenCols = new List<T_PF_COLUMN>();
                                tmpHiddenCols.ForEach(t =>
                                {
                                    if (t.Nav_Column != null)
                                        hiddenCols.Add(t.Nav_Column);
                                });
                            }
                        }
                    }
                }
            }
            return hiddenCols;
        }

        /// <summary>
        /// 获取用户自定义列
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageTableId"></param>
        /// <returns></returns>
        private List<T_FM_USER_C_C_TABLE_COL> GetUserCustomCols(Guid? userId, Guid? pageTableId, TableUserCustomInfoModel result, Guid orgid)
        {
            if (userId != null)
            {
                //var customConfig = this.GetEntity<T_FM_USER_CUSTOM_CONFIG>(t => t.USER_ID == userId);
                var baseFilter = new BaseFilter(orgid);
                baseFilter.IgnoreDataRule = true;
                var customConfigs = this.GetEntitiesByRedis<T_FM_USER_CUSTOM_CONFIG>(baseFilter);
                var customConfig = customConfigs.FirstOrDefault(t => t.USER_ID == userId);
                if (customConfig != null)
                {
                    //var table = this.GetEntity<T_FM_USER_C_C_TABLE>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_TABLE_ID == pageTableId);
                    var tables = this.GetEntitiesByRedis<T_FM_USER_C_C_TABLE>(null, new BaseFilter(orgid), pageTableId.ToString());
                    var table = tables.FirstOrDefault(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID);
                    if (table != null)
                    {
                        result.DefaultPageSize = table.PAGE_SIZE;
                        //var cols = this.GetEntities<T_FM_USER_C_C_TABLE_COL>(t => t.USER_C_C_TABLE_ID == table.ID, new BaseFilter(),
                        //                new string[] { "Nav_Column" }).ToList();

                        var cols = this.GetEntitiesByRedis<T_FM_USER_C_C_TABLE_COL>(null, new BaseFilter(orgid), table.ID.ToString());
                        //var cols = colsList.Where(t => t.USER_C_C_TABLE_ID == table.ID).ToList();
                        if (cols.Any())
                        {
                            var columns = this.GetEntitiesByRedis<T_PF_COLUMN>(null, new BaseFilter(orgid), pageTableId.ToString());

                            cols.ForEach(i => i.Nav_Column = columns.FirstOrDefault(x => x.ID == i.COLUMN_ID));
                        }
                        return cols;
                    }
                }
            }
            return null;
        }

        #endregion
    }
}
