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 APT.Utility;
using InfluxData.Net.Common.Helpers;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.Infrastructure.Api.Redis;
using System.Configuration;

namespace APT.PF.WebApiControllers.Api.PF
{
    [Route("api/PF/PageEdit")]
    [APT.Infrastructure.Api.RootOrg]
    public class PageEditController : AuthorizeApiController<T_PF_PAGE_EDIT>
    {
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_PF_PAGE_EDIT>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_PF_PAGE_EDIT>> OrderEntities([FromBody] KeywordFilter filter)
        {
            //return WitOrderEntities(null, filter);
            return SafeExecute<IEnumerable<T_PF_PAGE_EDIT>>(() =>
            {
                var data = this.GetOrderEntities<T_PF_PAGE_EDIT>(null, filter); ;
                //    data.ForEach(x =>
                //    {
                //        if (x.Nav_Columns != null) x.Nav_Columns.Where(i => !string.IsNullOrEmpty(i.ENUM))
                //.ForEach(i => i.ENUM = DataHelper.EnumToString(i.ENUM));
                //    });
                return data;
            });
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_PF_PAGE_EDIT> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_PF_PAGE_EDIT> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {

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

                        foreach (var filed in fileds)
                        {
                            var editColum = new T_PF_EDIT_COLUMN();
                            editColum.ORG_ID = entity.ORG_ID;
                            editColum.IS_CUSTOM = filed.IsCustom;
                            editColum.IS_DEFAULT = filed.IsDefault;
                            editColum.IS_TABLE_COLUMN = filed.IsDefault;
                            editColum.EDITABLE = filed.IsDefault;
                            editColum.FIELD_NAME = filed.FileName;
                            editColum.LABEL = filed.Description;
                            editColum.ENUM = filed.EnumName;
                            editColum.REQUIRED = filed.IsRequired;
                            editColum.PAGE_EDIT_ID = entity.ID;
                            editColum.ID = Guid.NewGuid();
                            editColum.CONTROL_TYPE = filed.ControlType;
                            editColum.IS_COPY = filed.IsCopy;
                            editColum.TYPE_NAME = filed.TypeName;
                            editColumns.Add(editColum);
                        }
                    }

                }
                else
                {

                }
                //操作数据库
                UnifiedCommit(() =>
               {
                   this.UpdateEntityNoCommit(entity);
                   if (editColumns.Count > 0)
                   {
                       this.BantchAddEntityNoCommit(editColumns);
                   }
               });
                var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();
                formService.CreateFormConfigVersion(PFFormConfigVersionEnum.PageEdit, 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.PageEdit, id);
                List<Guid> ids = new List<Guid>();
                ids.Add(new Guid(id));
                this.DoDelete(ids);
                return true;
            });
        }


        private void DoDelete(List<Guid> ids)
        {
            this.DeleteEntity<T_PF_EDIT_COLUMN>(t => ids.Contains(t.PAGE_EDIT_ID));
            this.DeleteEntity<T_PF_PAGE_EDIT_PANEL>(t => ids.Contains(t.PAGE_EDIT_ID));
            this.DeleteEntity<T_FM_USER_C_C_EDIT_H_COL>(t => ids.Contains(t.Nav_UserCCEdit.PAGE_EDIT_ID));
            this.DeleteEntity<T_FM_USER_C_C_EDIT_COL>(t => ids.Contains(t.Nav_UserCCEdit.PAGE_EDIT_ID));
            this.DeleteEntity<T_FM_USER_C_C_EDIT>(t => ids.Contains(t.PAGE_EDIT_ID));
            this.DeleteEntity<T_PF_PAGE_EDIT>(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.PageEdit, 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_EDIT> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }

        private void DoGetEditPageInfoByParentId(Guid formId, Guid parentId, EditPageDetailModel parentPageDetailModel, EditPageModel editPageModel, Guid orgId)
        {
            BaseFilter tmpFilter = new BaseFilter();
            tmpFilter.Sort = "NUM";
            tmpFilter.Order = DbOrder.ASC;
            tmpFilter.OrgType = FilterOrgTypeEnum.仅本组织;
            tmpFilter.OrgId = orgId;
            var pageEditList = this.GetOrderEntities<T_PF_PAGE_EDIT>(t =>
            t.PAGE_FORM_ID == formId && t.PARENT_ID == parentId, tmpFilter).ToList();
            if (pageEditList.Count > 0)
            {
                if (parentPageDetailModel != null)
                    parentPageDetailModel.HasChildren = true;
                pageEditList.ForEach(t =>
                {
                    var tmpDetail = DoGetEditPageInfo(t);
                    tmpDetail.Nav_ParentPageDetailModel = parentPageDetailModel;
                    if (parentPageDetailModel != null)
                    {
                        parentPageDetailModel.Nav_SubPageEdits.Add(tmpDetail);
                        tmpDetail.NavFields = parentPageDetailModel.NavFields;
                    }
                    if (!string.IsNullOrEmpty(tmpDetail.NavFields))
                        tmpDetail.NavFields += ".";
                    tmpDetail.NavFields += t.NAV_PROPERTY;
                    DoGetEditPageInfoByParentId(formId, t.ID, tmpDetail, editPageModel, orgId);
                    editPageModel.Nav_SubPageEdits.Add(tmpDetail);

                });
            }
        }

        /// <summary>
        /// 获取按钮、列信息
        /// </summary>
        /// <param name="pageEdit"></param>
        /// <returns></returns>
        private EditPageDetailModel DoGetEditPageInfo(T_PF_PAGE_EDIT pageEdit)
        {
            EditPageDetailModel detail = new EditPageDetailModel();
            BaseFilter tmpFilter = new BaseFilter();
            tmpFilter.Sort = "NUM";
            tmpFilter.Order = DbOrder.ASC;
            tmpFilter.OrgType = FilterOrgTypeEnum.仅本组织;
            tmpFilter.OrgId = pageEdit.ORG_ID;


            var editColumns = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN>(t => !t.IS_CUSTOM, tmpFilter,
                pageEdit.ID.ToString()).ToList();

            //var editColumns = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN>(pageEdit.ORG_ID ?? Guid.Empty);
            //editColumns = editColumns.Where(t => t.PAGE_EDIT_ID == pageEdit.ID && !t.IS_CUSTOM).ToList();

            List<T_PF_EDIT_COLUMN_FILL_MAP> fillMaps = new List<T_PF_EDIT_COLUMN_FILL_MAP>();
            var colFilters = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN_FILTER>(null, new BaseFilter(pageEdit.ORG_ID),
                        pageEdit.ID.ToString());
            var colFillMaps = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN_FILL_MAP>(null, new BaseFilter(pageEdit.ORG_ID),
                        pageEdit.ID.ToString());
            if (editColumns.Any() && (colFilters.Any() || colFillMaps.Any()))
            {
                foreach (var col in editColumns)
                {
                    col.Nav_Filters = colFilters.Where(i => i.EDIT_COLUMN_ID == col.ID).ToList();
                    col.Nav_FillMaps = colFillMaps.Where(i => i.EDIT_COLUMN_ID == col.ID).ToList();
                }
            }

            //var fillMaps = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN_FILL_MAP>(pageEdit.ORG_ID ?? Guid.Empty);

            foreach (var fill in colFillMaps)
            {
                fill.Nav_Details = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN_FILL_MAP_D>(null, new BaseFilter(pageEdit.ORG_ID), fill.ID.ToString());
            }
            //foreach (var c in editColumns)
            //{
            //    c.Nav_Filters = filters.Where(i => i.EDIT_COLUMN_ID == c.ID).ToList();
            //    c.Nav_FillMaps = fillMaps.Where(i => i.EDIT_COLUMN_ID == c.ID).ToList();
            //}


            //var btns = this.GetOrderEntities<T_PF_BTN>(t => t.PAGE_EDIT_ID == pageEdit.ID, tmpFilter).ToList();
            var baseFilter = new BaseFilter(pageEdit.ORG_ID);
            baseFilter.IgnoreDataRule = true;
            var btns = this.GetEntitiesByRedis<T_PF_BTN>(null, baseFilter, pageEdit.ID.ToString());
            btns = btns.OrderBy(t => t.NUM).ToList();
            //if (editColumns != null && editColumns.Count > 0)
            //{
            //	editColumns.Where(i => !string.IsNullOrEmpty(i.ENUM))
            //		.ForEach(i => i.ENUM = DataHelper.EnumToString(i.ENUM));
            //}

            //detail.Nav_EditPanels = this.GetOrderEntities<T_PF_PAGE_EDIT_PANEL>(t => t.PAGE_EDIT_ID == pageEdit.ID && t.IS_DISPLAY, tmpFilter).ToList();

            var editPanels = this.GetEntitiesByRedis<T_PF_PAGE_EDIT_PANEL>(null, new BaseFilter(pageEdit.ORG_ID), pageEdit.ID.ToString());
            editPanels = editPanels.OrderBy(t => t.NUM).ToList();
            detail.Nav_EditPanels = editPanels;

            if (pageEdit.PARAM_SCHEME_ID != null)
            {

                //var paramScheme = this.GetEntity<T_PF_PARAM_SCHEME>(t => t.ID == pageEdit.PARAM_SCHEME_ID 
                //&& t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用, new string[] { "Nav_Details.Nav_ParamItem" });
                var paramSchemes = this.GetEntitiesByRedis<T_PF_PARAM_SCHEME>(baseFilter);
                var paramScheme = paramSchemes.FirstOrDefault(t => t.ID == pageEdit.PARAM_SCHEME_ID
                && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用);

                var paramDetails = this.GetEntitiesByRedis<T_PF_PARAM_SCHEME_DETAIL>(baseFilter);
                paramDetails = paramDetails.Where(i => i.PARAM_SCHEME_ID == paramScheme.ID).ToList();

                var paramItems = this.GetEntitiesByRedis<T_PF_PARAM_ITEM>(baseFilter);

                foreach (var p in paramDetails)
                {
                    p.Nav_ParamItem = paramItems.FirstOrDefault(i => i.ID == p.PARAM_ITEM_ID);
                }


                if (paramScheme != null && paramScheme.Nav_Details != null && paramScheme.Nav_Details.Any())
                {
                    T_PF_PAGE_EDIT_PANEL tablePanel = null;
                    if (paramScheme.IS_PANEL_SHOW.HasValue && paramScheme.IS_PANEL_SHOW.Value)
                    {
                        tablePanel = new T_PF_PAGE_EDIT_PANEL()
                        {
                            ORG_ID = pageEdit.ORG_ID,
                            PAGE_EDIT_ID = pageEdit.ID,
                            LABEL = "实体参数",
                            IS_DISPLAY = true,
                            NUM = 10000,
                        };
                        detail.Nav_EditPanels.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.IS_SHOW
                                || item.Nav_ParamItem.ENABLE_STATUS == (int)FMEnableStatusEnum.禁用) continue;
                        T_PF_EDIT_COLUMN editColumn = new T_PF_EDIT_COLUMN()
                        {
                            ID = item.ID,
                            ORG_ID = pageEdit.ORG_ID,
                            PAGE_EDIT_ID = pageEdit.ID,
                            FIELD_NAME = "Nav_SysParams." + item.Nav_ParamItem.FIELD_NAME,
                            REQUIRED = item.REQUIRED || item.Nav_ParamItem.REQUIRED,
                            EDITABLE = item.EDITABLE && item.Nav_ParamItem.EDITABLE,
                            CASE = item.Nav_ParamItem.CASE,
                            DEFAULT_VALUE = item.Nav_ParamItem.DEFAULT_VALUE,
                            PROMPT_INFO = item.Nav_ParamItem.PROMPT_INFO,
                            CODE_RULE_TYPE = item.Nav_ParamItem.CODE_RULE_TYPE,
                            LABEL = item.Nav_ParamItem.LABEL,
                            CONTROL_TYPE = item.Nav_ParamItem.EDIT_CONTROL_TYPE,
                            ENUM = item.Nav_ParamItem.ENUM,
                            NUM = 10000 + (item.NUM > 0 ? item.NUM : item.Nav_ParamItem.NUM),
                            WIDTH = item.Nav_ParamItem.WIDTH,
                        };
                        if (tablePanel != null)
                            editColumn.PAGE_EDIT_PANEL_ID = tablePanel.ID;
                        editColumns.Add(editColumn);
                    }
                }
            }

            detail.Nav_PageEdit = pageEdit;
            detail.Nav_Btns = btns;
            detail.Nav_Columns = editColumns;
            return detail;
        }

        /// <summary>
        /// 获取编辑页配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEditPageConfigInfo")]
        public JsonActionResult<EditPageModel> GetEditPageConfigInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<EditPageModel>(() =>
            {
                var redisCode = string.Format(RedisCacheKey.PageEditRedisKey, filter.Keyword, 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<EditPageModel>(redisCode);
                }
                string code = filter.Parameter1;
                filter.OrgType = FilterOrgTypeEnum.仅本组织;
                var form = this.GetEntity<T_PF_FORM>(t=>t.CODE == filter.Keyword,new BaseFilter(filter.OrgId));
                if (form == null)
                    return null;
                EditPageModel result = new EditPageModel();
                result.Nav_Form = form;

                //Expression<Func<T_PF_PAGE_EDIT, bool>> expression = t => t.PAGE_FORM_ID == form.ID && t.PARENT_ID == null;
                //if (!string.IsNullOrEmpty(code))
                //	expression =expression.And(t => t.CODE == code);

                //var pageEdit = this.GetEntity<T_PF_PAGE_EDIT>(expression);
                var pageEditList = this.GetEntitiesByRedis<T_PF_PAGE_EDIT>(i => i.PARENT_ID == null, new BaseFilter(filter.GetOrgId()), form.ID.ToString());
                if (!string.IsNullOrEmpty(code))
                    pageEditList = pageEditList.Where(i => i.CODE == code).ToList();
                var pageEdit = pageEditList.FirstOrDefault();
                //var pageEdit = this.GetEntityByRedis<T_PF_PAGE_EDIT>(form.ID.ToString(), filter.OrgId ?? Guid.Empty);
                if (pageEdit != null)
                {

                    var detail = DoGetEditPageInfo(pageEdit);
                    result.Nav_PageEdit = detail;
                    DoGetEditPageInfoByParentId(form.ID, pageEdit.ID, null, result, filter.GetOrgId());
                }
                CsRedisManager.StringSet(redisCode, result);
                return result;

            });

        }



        /// <summary>
        /// 获取用户自定义配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserCustomConfigInfo")]
        public JsonActionResult<EditUserCustomInfoModel> GetUserCustomConfigInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<EditUserCustomInfoModel>(() =>
            {
                var pageId = LibUtils.ToGuid(filter.Keyword);
                var userId = LibUtils.ToGuid(filter.Parameter1);
                if (pageId == null)
                    return null;
                if (userId == null)
                    return null;
                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<EditUserCustomInfoModel>(redisCode);
                }
                EditUserCustomInfoModel result = new EditUserCustomInfoModel();
                var baseFilter = new BaseFilter(filter.GetOrgId());
                var customConfigs = this.GetEntitiesByRedis<T_FM_USER_CUSTOM_CONFIG>(null, baseFilter, userId.ToString());
                var customConfig = customConfigs.FirstOrDefault();
                if (customConfig != null)
                {
                    //var customEdit = this.GetEntity<T_FM_USER_C_C_EDIT>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_EDIT_ID == pageId);
                    var customEdits = this.GetEntitiesByRedis<T_FM_USER_C_C_EDIT>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID, baseFilter, pageId.ToString());
                    var customEdit = customEdits.FirstOrDefault();
                    if (customEdit != null)
                    {
                        //result.Nav_CustomHiddenEditCols = this.GetEntities<T_FM_USER_C_C_EDIT_H_COL>(t => t.USER_C_C_EDIT_ID == customEdit.ID,
                        //        new BaseFilter(), new string[] { "Nav_EditColumn" }).ToList();
                        var customHiddenEditCols = this.GetEntitiesByRedis<T_FM_USER_C_C_EDIT_H_COL>(null, baseFilter, customEdit.ID.ToString());
                        var editColumns = this.GetEntitiesByRedis<T_PF_EDIT_COLUMN>(null, baseFilter, pageId.ToString());
                        foreach (var c in customHiddenEditCols)
                        {
                            c.Nav_EditColumn = editColumns.FirstOrDefault(i => i.ID == c.EDIT_COLUMN_ID);
                        }
                        result.Nav_CustomHiddenEditCols = customHiddenEditCols;

                        //result.Nav_CustomCols = this.GetEntities<T_FM_USER_C_C_EDIT_COL>(t => t.USER_C_C_EDIT_ID == customEdit.ID,
                        //        new BaseFilter(), new string[] { "Nav_EditColumn" }).ToList();
                        filter.Sort = "NUM";
                        var customCols = this.GetEntitiesByRedis<T_FM_USER_C_C_EDIT_COL>(null, baseFilter, customEdit.ID.ToString());
                        //.Where(t => t.USER_C_C_EDIT_ID == customEdit.ID).ToList();
                        foreach (var c in customCols)
                        {
                            c.Nav_EditColumn = editColumns.FirstOrDefault(i => i.ID == c.EDIT_COLUMN_ID);
                        }
                        result.Nav_CustomCols = customCols;
                    }
                }
                CsRedisManager.GetClient().Set(redisCode, result);
                return result;
            });
        }



        /// <summary>
        /// 保存用户自定义配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SaveUserCustomConfigInfo")]
        public JsonActionResult<bool> SaveUserCustomConfigInfo([FromBody] SaveEditUserCustomInfoModel 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> deleteCustomHEditColIds = new List<Guid>();
                List<T_FM_USER_C_C_EDIT_H_COL> addHCols = new List<T_FM_USER_C_C_EDIT_H_COL>();

                List<Guid> deleteCustomEditColIds = new List<Guid>();
                List<T_FM_USER_C_C_EDIT_COL> saveCustomCols = new List<T_FM_USER_C_C_EDIT_COL>();

                var customEdit = this.GetEntity<T_FM_USER_C_C_EDIT>(t => t.USER_CUSTOM_CONFIG_ID == customConfig.ID && t.PAGE_EDIT_ID == model.PageEditId);
                if (customEdit == null)
                {
                    customEdit = new T_FM_USER_C_C_EDIT();
                    customEdit.ORG_ID = model.OrgId;
                    customEdit.PAGE_EDIT_ID = model.PageEditId;
                    customEdit.USER_CUSTOM_CONFIG_ID = customConfig.ID;
                    this.AddEntity(customEdit);
                }



                #region 隐藏列

                //数据库已有数据
                var dbHCols = this.GetEntitiesByRedis<T_FM_USER_C_C_EDIT_H_COL>(null, new BaseFilter(model.OrgId), customEdit.ID.ToString()).ToList();
                var hCols = model.HiddenEditColumnIds;
                //删除
                if (dbHCols != null && dbHCols.Any())
                {
                    foreach (var item in dbHCols)
                    {
                        if (hCols == null || !hCols.Contains(item.EDIT_COLUMN_ID.ToString()))
                            deleteCustomHEditColIds.Add(item.ID);
                    }
                }
                //新增
                if (hCols != null && hCols.Any())
                {
                    foreach (var item in hCols)
                    {
                        if (dbHCols == null || !dbHCols.Any(t => t.EDIT_COLUMN_ID.ToString() == item))
                        {
                            T_FM_USER_C_C_EDIT_H_COL hCol = new T_FM_USER_C_C_EDIT_H_COL();
                            hCol.ORG_ID = model.OrgId;
                            hCol.USER_C_C_EDIT_ID = customEdit.ID;
                            hCol.EDIT_COLUMN_ID = new Guid(item);
                            addHCols.Add(hCol);
                        }
                    }
                }
                #endregion

                #region  自定义列信息



                //数据库已有数据
                var dbCustomConfigCols = this.GetEntities<T_FM_USER_C_C_EDIT_COL>(t => t.USER_C_C_EDIT_ID == customEdit.ID, new BaseFilter()).ToList();
                var customConfigCols = model.EditColumns;
                //删除
                if (dbCustomConfigCols != null && dbCustomConfigCols.Any())
                {
                    foreach (var item in dbCustomConfigCols)
                    {
                        var col = customConfigCols == null ? null : customConfigCols.FirstOrDefault(t => t.EDIT_COLUMN_ID == item.EDIT_COLUMN_ID);
                        if (col == null)
                            deleteCustomEditColIds.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.EDIT_COLUMN_ID == item.EDIT_COLUMN_ID))
                        {
                            T_FM_USER_C_C_EDIT_COL hCol = new T_FM_USER_C_C_EDIT_COL();
                            CopyUtils.CopyObject(hCol, item);
                            hCol.ORG_ID = model.OrgId;
                            hCol.USER_C_C_EDIT_ID = customEdit.ID;
                            saveCustomCols.Add(hCol);
                        }
                    }
                }

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

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

                    if (deleteCustomHEditColIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_EDIT_H_COL>(t => deleteCustomHEditColIds.Contains(t.ID));
                    if (deleteCustomEditColIds.Any())
                        this.DeleteEntityNoCommit<T_FM_USER_C_C_EDIT_COL>(t => deleteCustomEditColIds.Contains(t.ID));
                });
                var redisCode = string.Format(RedisCacheKey.UserCustomConfigRedisKey, model.PageEditId.ToString() + model.UserId, model.OrgId);
                CsRedisManager.KeyDelete(redisCode);
                return true;
            });
        }








    }
}
