using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.IServices.EX;
using APT.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core.Refctor;

namespace APT.BaseData.Services.Services.EX
{
    public class EntityOperateService : CommonService, IEntityOperateService
    {
        public EntityOperateService(IRepository repository)
               : base(repository)
        {

        }

        /// <summary>
        /// 获取实体字段信息
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="isOnlyBaseType">仅获取基础类型</param>
        /// <returns></returns>
        public List<EntityFieldModel> GetEntityFields(string entityName, bool isOnlyBaseType)
        {
            if (string.IsNullOrEmpty(entityName)) return null;
            var type = DataHelper.GetTypeByEntityName(entityName);
            if (type == null)
                return null;

            List<EntityFieldModel> result = new List<EntityFieldModel>();
            foreach (var property in type.GetProperties())
            {
                string fullTypeName = property.PropertyType.FullName;
                if (fullTypeName.IndexOf("List", StringComparison.OrdinalIgnoreCase) >= 0) continue;
                if (isOnlyBaseType && property.PropertyType.IsClass) continue;

                EntityFieldModel entityField = new EntityFieldModel();
                string propertyTypeName = property.PropertyType.Name;
                if (string.Compare(propertyTypeName, "GUID", true) == 0 || fullTypeName.IndexOf("Guid", StringComparison.OrdinalIgnoreCase) > -1)
                    entityField.TypeName = "Guid";
                else if (string.Compare(propertyTypeName, "DateTime", true) == 0 || fullTypeName.IndexOf("DateTime", StringComparison.OrdinalIgnoreCase) > -1)
                    entityField.TypeName = "DateTime";
                else if (string.Compare(propertyTypeName, "bool", true) == 0 || string.Compare(propertyTypeName, "boolean", true) == 0 || fullTypeName.IndexOf("bool", StringComparison.OrdinalIgnoreCase) > -1)
                    entityField.TypeName = "bool";
                else if (string.Compare(propertyTypeName, "int", true) == 0 || fullTypeName.IndexOf("int", StringComparison.OrdinalIgnoreCase) > -1)
                    entityField.TypeName = "int";
                else if (string.Compare(propertyTypeName, "decimal", true) == 0 || fullTypeName.IndexOf("decimal", StringComparison.OrdinalIgnoreCase) > -1)
                    entityField.TypeName = "decimal";
                else if (string.Compare(propertyTypeName, "string", true) == 0 || fullTypeName.IndexOf("string", StringComparison.OrdinalIgnoreCase) > -1)
                    entityField.TypeName = "string";
                else
                    entityField.TypeName = propertyTypeName;

                entityField.FieldName = property.Name;

                EnumNameAttribute enumNameAttr = null;
                object[] attrs = property.GetCustomAttributes(typeof(EnumNameAttribute), true);
                if (attrs.Length == 1)
                    enumNameAttr = (EnumNameAttribute)attrs[0];

                if (enumNameAttr != null)
                    entityField.EnumName = enumNameAttr.EnumName;

                DescriptionAttribute descriptAttr = null;
                object[] descAttrs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (descAttrs.Length == 1)
                    descriptAttr = (DescriptionAttribute)descAttrs[0];

                if (descriptAttr != null)
                    entityField.Label = descriptAttr.Description;

                if (string.IsNullOrEmpty(entityField.Label))
                    entityField.Label = entityField.FieldName;
                result.Add(entityField);
            }
            return result;
        }


        /// <summary>
        /// 根据表名获取实体查询字段信息
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="fieldNamePrefix">字段前缀</param>
        /// <param name="lablePrefix">显示名称前缀</param>
        /// <param name="expandFields">展开字段列表</param>
        /// <returns></returns>
        public List<EntityFieldByQueryFieldModel> GetEntityFieldsByTableName(string tableName, string fieldNamePrefix, string lablePrefix, List<string> expandFields)
        {
            Dictionary<string, byte> existFields = new Dictionary<string, byte>();
            return this.DoGetQueryFieldsByTableName(tableName, fieldNamePrefix, lablePrefix, existFields, expandFields);
        }

        /// <summary>
        /// 根据查询表ID获取实体查询字段信息
        /// </summary>
        /// <param name="formId">查询表单ID</param>
        /// <param name="code">查询字段CODE</param>
        /// <param name="fieldNamePrefix">字段前缀</param>
        /// <param name="lablePrefix">显示名称前缀</param>
        /// <param name="expandFields">展开字段列表</param>
        /// <returns></returns>
        public List<EntityFieldByQueryFieldModel> GetEntityFieldsByQueryFormId(Guid formId, string code, string fieldNamePrefix, string lablePrefix, List<string> expandFields, BaseFilter filter)
        {
            T_PF_FORM form = this.GetEntityByRedis<T_PF_FORM>(formId, filter.GetOrgId());
            if (form == null)
                throw new Exception("无效表单");
            List<EntityFieldByQueryFieldModel> result = new List<EntityFieldByQueryFieldModel>();
            Dictionary<string, byte> existFields = new Dictionary<string, byte>();
            string tableName = form.TABLE_NAME;
            filter.Sort = "NUM";
            //Expression<Func<T_PF_FORM_QUERY, bool>> queryExpression = t => t.PAGE_FORM_ID == form.ID;
            var formQuerys = this.GetEntitiesByRedis<T_PF_FORM_QUERY>(i => i.ORG_ID == filter.GetOrgId(), new BaseFilter(filter.GetOrgId()), form.ID.ToString());
            var formQuery = formQuerys.FirstOrDefault();
            if (formQuery != null)
            {
                if (!string.IsNullOrEmpty(formQuery.TABLE_NAME))
                    tableName = formQuery.TABLE_NAME;
                var querys = this.GetEntitiesByRedis<T_PF_QUERY>(i => i.ORG_ID == filter.GetOrgId(), new BaseFilter(filter.GetOrgId()), formQuery.ID.ToString());
                if (!string.IsNullOrEmpty(code))
                    querys = querys.Where(i => i.CODE == code).ToList();

                if (querys != null && querys.Any())
                {
                    querys.ForEach(t =>
                    {
                        if (existFields.ContainsKey(t.QUERY_NAME)) return;
                        EntityFieldByQueryFieldModel field = new EntityFieldByQueryFieldModel();
                        field.DataType = t.DATA_TYPE;
                        field.FieldName = t.QUERY_NAME;
                        field.Label = t.LABEL;
                        field.ShowLabel = t.LABEL;
                        field.EnumName = t.ENUM_NAME;
                        field.OpDefault = t.OP_DEFAULT;
                        field.Num = t.NUM;
                        field.IsSysField = true;
                        field.IsCustom = t.IS_CUSTOM;
                        field.IsSysParam = t.IS_SYS_PARAM == null ? false : t.IS_SYS_PARAM.Value;
                        field.CaseType = t.CASE.Value;
                        field.IsRequire = t.IS_REQUIRE ?? false;
                        existFields.Add(t.QUERY_NAME, 0);
                        result.Add(field);
                    });
                }
            }
            var temps = this.DoGetQueryFieldsByTableName(tableName, fieldNamePrefix, lablePrefix, existFields, expandFields);
            if (temps != null && temps.Any())
                result.AddRange(temps);
            return result;
        }


        /// <summary>
        /// 根据表名实际获取查询字段
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="fieldNamePrefix"></param>
        /// <param name="lablePrefix"></param>
        /// <param name="existFields"></param>
        /// <param name="expandFields"></param>
        /// <param name="entityOperateService"></param>
        /// <returns></returns>
        private List<EntityFieldByQueryFieldModel> DoGetQueryFieldsByTableName(string tableName, string fieldNamePrefix, string lablePrefix,
                Dictionary<string, byte> existFields, List<string> expandFields)
        {
            if (string.IsNullOrEmpty(tableName))
                return null;
            List<EntityFieldByQueryFieldModel> result = new List<EntityFieldByQueryFieldModel>();
            var tmpFields = this.GetEntityFields(tableName, false);
            if (tmpFields != null && tmpFields.Any())
            {
                int i = 1;
                tmpFields.ForEach(t =>
                {
                    if (string.Compare(t.FieldName, "FLOW_STATUS", true) == 0
                    || string.Compare(t.FieldName, "FLOW_SEND_STATUS", true) == 0
                        || string.Compare(t.FieldName, "IS_DELETED", true) == 0
                        || string.Compare(t.FieldName, "TEXT", true) == 0
                        || string.Compare(t.FieldName, "IS_LEAF", true) == 0
                        || string.Compare(t.FieldName, "SysParams", true) == 0
                        || string.Compare(t.FieldName, "FLOW_ID", true) == 0)
                        return;
                    if (string.Compare(t.TypeName, "GUID", true) == 0)
                        return;
                    string fieldName = (!string.IsNullOrEmpty(fieldNamePrefix) ? (fieldNamePrefix + ".") : string.Empty) + t.FieldName;
                    if (existFields.ContainsKey(fieldName)) return;
                    existFields.Add(fieldName, 0);
                    int dataType = 100;
                    if (string.Compare(t.TypeName, "DateTime", true) == 0)
                        dataType = (int)PFDataTypeEnum.日期区间;
                    else if (string.Compare(t.TypeName, "bool", true) == 0)
                        dataType = (int)PFDataTypeEnum.布尔;
                    else if (string.Compare(t.TypeName, "int", true) == 0)
                    {
                        if (string.IsNullOrEmpty(t.EnumName))
                            dataType = (int)PFDataTypeEnum.数值;
                        else
                            dataType = (int)PFDataTypeEnum.下拉多选;
                    }
                    else if (string.Compare(t.TypeName, "decimal", true) == 0)
                        dataType = (int)PFDataTypeEnum.数值;
                    else if (string.Compare(t.TypeName, "string", true) == 0)
                        dataType = (int)PFDataTypeEnum.字符;

                    EntityFieldByQueryFieldModel field = new EntityFieldByQueryFieldModel();
                    field.FieldName = fieldName;
                    field.Label = t.Label;
                    field.ShowLabel = !string.IsNullOrEmpty(lablePrefix) && dataType != 100 ? lablePrefix + t.Label : t.Label;
                    field.EnumName = t.EnumName;
                    field.IsLeaf = dataType != 100;
                    if (dataType == (int)PFDataTypeEnum.字符)
                        field.OpDefault = "9";
                    else if (dataType != 0)
                        field.OpDefault = "1";
                    field.DataType = dataType;
                    field.TypeName = t.TypeName;
                    field.Num = i;
                    if (fieldName.EndsWith("CODE", StringComparison.OrdinalIgnoreCase))
                        field.CaseType = (int)FMCaseProcEnum.转大写;
                    if (!field.IsLeaf && expandFields != null && expandFields.Any())
                    {
                        if (expandFields.Any(t1 => string.Compare(t1, field.FieldName, true) == 0))
                        {
                            var children = DoGetQueryFieldsByTableName(t.TypeName, field.FieldName, field.Label, existFields, expandFields);
                            if (children != null && children.Any())
                                field.Children = children;
                        }
                    }
                    result.Add(field);
                    i++;
                });
            }
            return result;
        }

        /// <summary>
        /// 根据表名初始化表单配置
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="tableName"></param>
        /// <param name="userId"></param>
        /// <param name="configType"></param>
        public void InitFormConfigByName(Guid orgId, string tableName,
                Guid? userId, PFInitFormConfigTypeEnum configType,
                Guid? menuParentId, string menuName, string menuIcon, bool isAddSend = false)
        {
            var formService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFFormService>();

            tableName = string.IsNullOrEmpty(tableName) ? tableName : tableName.Trim();
            if (string.IsNullOrEmpty(tableName)) return;
            var newName = tableName.ToLower();
            var newNameAry = newName.Split(new char[] { '_' });
            string moduleName = string.Empty;
            if (newNameAry.Any() && newNameAry.Length >= 2)
                moduleName = newNameAry[1].ToUpper();
            var tableType = DataHelper.GetTypeByEntityName(tableName);
            if (string.IsNullOrEmpty(moduleName) || tableType == null) throw new Exception("无效表名");

            FormConfigDbModel dbModel = new FormConfigDbModel();
            var moduleType = formService.GetModelTypeByName(tableName);
            var intModelType = (int)moduleType;
            int codeIndex = 0;
            T_PF_FORM editForm = null;
            T_PF_FORM tableForm = null;
            T_PF_FORM treeForm = null;

            //获取当前模块最大表单编号
            var lastForm = this.GetEntity<T_PF_FORM>(t => t.PLATFORM_TYPE == (int)PFPlatTypeEnum.后台 && t.CODE.StartsWith(moduleName) && !t.CODE.Contains("_"), new BaseFilter(orgId)
            {
                Sort = "CODE",
                Order = DbOrder.DESC
            });
            if (lastForm != null)
            {
                var index = lastForm.CODE.IndexOf(moduleName);
                if (index == -1) throw new Exception("数据异常");
                codeIndex = LibUtils.ToInt(lastForm.CODE.Substring(index + moduleName.Length));
            }
            var typeDescriptionAttr = GetAttributeByType<DescriptionAttribute>(tableType);

            //如果表是MesTreeEntityBase的派生类，则按照树页面生成，否则按列表页，编辑页生成
            if (configType == PFInitFormConfigTypeEnum.默认 && tableType.IsSubclassOf(typeof(MesTreeEntityBase)) ||
                configType == PFInitFormConfigTypeEnum.树页面)
            {
                //treeForm = this.GetEntity<T_PF_FORM>(t => t.PLATFORM_TYPE == (int)PFPlatTypeEnum.后台 &&
                //    t.FORM_TYPE == (int)PFFormTypeEnum.树形编辑页 && t.TABLE_NAME == tableName, new BaseFilter(orgId));
                if (treeForm == null)
                {
                    codeIndex++;
                    treeForm = new T_PF_FORM();
                    treeForm.ORG_ID = orgId;
                    treeForm.CODE = moduleName + codeIndex.PadLeft(3, '0');
                    treeForm.PLATFORM_TYPE = (int)PFPlatTypeEnum.后台;
                    treeForm.FORM_TYPE = (int)PFFormTypeEnum.树形编辑页;
                    treeForm.MODULE_TYPE = (int)moduleType;
                    treeForm.TABLE_NAME = tableName;
                    dbModel.AddForms.Add(treeForm);
                }
                else
                {
                    if (treeForm == null) return;
                    if (!dbModel.UpdateForms.Any(t => t.ID == treeForm.ID)) dbModel.UpdateForms.Add(treeForm);
                }
                var typeClassTreeAttr = this.GetAttributeByType<FormClassTreeAttribute>(tableType);
                if (typeClassTreeAttr != null && !string.IsNullOrEmpty(typeClassTreeAttr.DisplayName))
                    treeForm.NAME = typeClassTreeAttr.DisplayName;
                else if (typeDescriptionAttr != null)
                    treeForm.NAME = typeDescriptionAttr.Description;
                else
                    treeForm.NAME = tableName;

                DoInitFormConfigByName(tableType, treeForm, null, treeForm,
                        null, null, null, 0, string.Empty, string.Empty, dbModel);

            }
            else
            {
                if (configType == PFInitFormConfigTypeEnum.默认 ||
                    configType == PFInitFormConfigTypeEnum.列表_编辑页 ||
                    configType == PFInitFormConfigTypeEnum.仅列表页)
                {
                    //列表表单
                    //tableForm = this.GetEntity<T_PF_FORM>(t => t.PLATFORM_TYPE == (int)PFPlatTypeEnum.后台 &&
                    //    t.FORM_TYPE == (int)PFFormTypeEnum.列表表单 && t.TABLE_NAME == tableName, new BaseFilter(orgId));
                    if (tableForm == null)
                    {
                        codeIndex++;
                        tableForm = new T_PF_FORM();
                        tableForm.ORG_ID = orgId;
                        tableForm.CODE = moduleName + codeIndex.PadLeft(3, '0');
                        tableForm.PLATFORM_TYPE = (int)PFPlatTypeEnum.后台;
                        tableForm.FORM_TYPE = (int)PFFormTypeEnum.列表表单;
                        tableForm.MODULE_TYPE = (int)moduleType;
                        tableForm.TABLE_NAME = tableName;
                        dbModel.AddForms.Add(tableForm);
                    }
                    else
                    {
                        if (tableForm != null && !dbModel.UpdateForms.Any(t => t.ID == tableForm.ID)) dbModel.UpdateForms.Add(tableForm);
                    }
                    var typeClassTableAttr = this.GetAttributeByType<FormClassTableAttribute>(tableType);
                    if (typeClassTableAttr != null && !string.IsNullOrEmpty(typeClassTableAttr.DisplayName))
                        tableForm.NAME = typeClassTableAttr.DisplayName;
                    else if (typeDescriptionAttr != null)
                        tableForm.NAME = typeDescriptionAttr.Description + "列表";
                    else
                        tableForm.NAME = tableName + "列表";
                }
                if (configType == PFInitFormConfigTypeEnum.默认 ||
                    configType == PFInitFormConfigTypeEnum.列表_编辑页 ||
                    configType == PFInitFormConfigTypeEnum.仅编辑页)
                {
                    //编辑表单
                    //editForm = this.GetEntity<T_PF_FORM>(t => t.PLATFORM_TYPE == (int)PFPlatTypeEnum.后台 &&
                    //      t.FORM_TYPE == (int)PFFormTypeEnum.编辑表单 && t.TABLE_NAME == tableName, new BaseFilter(orgId));
                    if (editForm == null)
                    {
                        codeIndex++;
                        editForm = new T_PF_FORM();
                        editForm.ORG_ID = orgId;
                        editForm.CODE = moduleName + codeIndex.PadLeft(3, '0');
                        editForm.PLATFORM_TYPE = (int)PFPlatTypeEnum.后台;
                        editForm.FORM_TYPE = (int)PFFormTypeEnum.编辑表单;
                        editForm.MODULE_TYPE = (int)moduleType;
                        editForm.TABLE_NAME = tableName;
                        if (isAddSend)
                        {
                            editForm.JS_FILES = editForm.CODE + ".js";
                        }
                        dbModel.AddForms.Add(editForm);
                    }
                    else
                    {
                        if (editForm != null && !dbModel.UpdateForms.Any(t => t.ID == editForm.ID)) dbModel.UpdateForms.Add(editForm);
                    }
                    var typeClassEditAttr = this.GetAttributeByType<FormClassEditAttribute>(tableType);
                    if (typeClassEditAttr != null && !string.IsNullOrEmpty(typeClassEditAttr.DisplayName))
                        editForm.NAME = typeClassEditAttr.DisplayName;
                    else if (typeDescriptionAttr != null)
                        editForm.NAME = typeDescriptionAttr.Description + "编辑";
                    else
                        editForm.NAME = tableName + "编辑";
                }
                DoInitFormConfigByName(tableType, editForm, tableForm, null,
                           null, null, null, 0, string.Empty, string.Empty, dbModel, isAddSend, moduleName);

            }

            #region 列表页查询
            if (tableForm != null)
            {
                T_PF_FORM_QUERY formQuery = null;
                //this.GetEntity<T_PF_FORM_QUERY>(t => t.PAGE_FORM_ID == tableForm.ID);
                List<T_PF_QUERY> querys = null;
                if (formQuery == null)
                {
                    formQuery = new T_PF_FORM_QUERY();
                    formQuery.ORG_ID = tableForm.ORG_ID;
                    formQuery.PAGE_FORM_ID = tableForm.ID;
                    dbModel.AddFormQuerys.Add(formQuery);
                }
                else
                {
                    if (!dbModel.UpdateFormQuerys.Any(t => t.ID == formQuery.ID)) dbModel.UpdateFormQuerys.Add(formQuery);
                    querys = this.GetEntities<T_PF_QUERY>(t => t.PAGE_FORM_QUERY_ID == formQuery.ID).ToList();
                }
                formQuery.LABEL = "默认";
                formQuery.TABLE_NAME = tableName;

                int queryNum = querys != null && querys.Any() ? querys.Max(t => t.NUM) + 1 : 1;
                foreach (var property in tableType.GetProperties())
                {
                    int dataType = (int)PFDataTypeEnum.字符;
                    string enumName = string.Empty;
                    string queryName = property.Name;
                    string label = string.Empty;
                    int queryCase = 0;
                    string otherQueryName = string.Empty;
                    string otherLabel = string.Empty;
                    int otherQueryCase = 0;

                    var queryAttr = this.GetAttributeByProperty<FormFieldQueryAttribute>(property);
                    var queryDescAttr = this.GetAttributeByProperty<DescriptionAttribute>(property);
                    if (queryAttr != null && !string.IsNullOrEmpty(queryAttr.DisplayName))
                        label = queryAttr.DisplayName;
                    else if (queryDescAttr != null)
                        label = queryDescAttr.Description;
                    else
                        label = queryName;

                    var realPropertyType = property.PropertyType.GetNonNummableType();
                    if (queryAttr == null && (string.Compare(property.Name, "CODE", true) == 0 ||
                        string.Compare(property.Name, "NAME", true) == 0))
                        queryAttr = new FormFieldQueryAttribute();
                    if (queryAttr != null)
                    {
                        if (string.Compare(property.Name, "CODE", true) == 0)
                            queryCase = (int)FMCaseProcEnum.转大写;
                        if (realPropertyType == typeof(int) || realPropertyType.IsEnum)
                        {
                            EnumNameAttribute enumNameAttr = this.GetAttributeByProperty<EnumNameAttribute>(property);
                            string tempEnumName = enumNameAttr != null ? enumNameAttr.EnumName : ((realPropertyType.IsEnum) ? realPropertyType.Name : string.Empty);
                            if (string.IsNullOrEmpty(tempEnumName))
                                dataType = (int)PFDataTypeEnum.数值;
                            else
                            {
                                enumName = tempEnumName;
                                dataType = (int)PFDataTypeEnum.枚举;
                            }
                        }
                        else if (realPropertyType == typeof(decimal))
                        {
                            dataType = (int)PFDataTypeEnum.数值;
                        }
                        else if (realPropertyType == typeof(bool))
                        {
                            dataType = (int)PFDataTypeEnum.布尔;
                        }
                        else if (realPropertyType == typeof(DateTime))
                        {
                            dataType = (int)PFDataTypeEnum.日期区间;
                        }
                        else if (realPropertyType == typeof(Guid) ||
                            realPropertyType != typeof(string) && realPropertyType.IsClass)
                        {
                            string navTableName = string.Empty;
                            string idName = string.Empty;
                            string navFieldName = string.Empty;
                            GetNavInfoByProperty(tableType, tableName, property, property.Name, realPropertyType, ref navTableName,
                                ref idName, ref navFieldName);
                            if (!string.IsNullOrEmpty(navTableName))
                            {
                                var navType = DataHelper.GetTypeByEntityName(navTableName);
                                var navCodeP = navType.GetProperty("CODE");
                                var navNameP = navType.GetProperty("NAME");
                                if (navCodeP == null)
                                    navCodeP = navType.GetProperty("PDT_CODE");
                                if (navCodeP != null && navNameP != null)
                                {
                                    queryName = navFieldName + "." + navNameP.Name;
                                    otherQueryName = navFieldName + "." + navCodeP.Name;
                                    otherLabel = label + "编号";
                                    otherQueryCase = (int)FMCaseProcEnum.转大写;
                                    label += "名称";
                                }
                                else if (navCodeP == null && navNameP != null)
                                {
                                    queryName = navFieldName + "." + navNameP.Name;
                                    label += "名称";
                                }
                                else if (navCodeP != null && navNameP == null)
                                {
                                    queryName = navFieldName + "." + navCodeP.Name;
                                    label += "编号";
                                    queryCase = (int)FMCaseProcEnum.转大写;
                                }
                            }
                        }

                        var query = querys == null ? null : querys.FirstOrDefault(t => t.QUERY_NAME == queryName);
                        if (query == null)
                        {
                            query = new T_PF_QUERY();
                            query.ORG_ID = formQuery.ORG_ID;
                            query.PAGE_FORM_ID = formQuery.PAGE_FORM_ID;
                            query.PAGE_FORM_QUERY_ID = formQuery.ID;
                            query.QUERY_NAME = queryName;
                            query.DATA_TYPE = dataType;
                            if (queryAttr != null && queryAttr.Num != 0)
                                query.NUM = queryAttr.Num;
                            else
                            {
                                query.NUM = queryNum;
                                queryNum += 5;
                            }
                            dbModel.AddQuerys.Add(query);
                        }
                        else
                        {
                            if (!dbModel.UpdateQuerys.Any(t => t.ID == query.ID)) dbModel.UpdateQuerys.Add(query);
                        }

                        query.LABEL = label;
                        query.ENUM_NAME = enumName;
                        query.CASE = queryCase;

                        if (!string.IsNullOrEmpty(otherQueryName))
                        {
                            var codeQuery = querys == null ? null : querys.FirstOrDefault(t => t.QUERY_NAME == otherQueryName);
                            if (codeQuery == null)
                            {
                                codeQuery = new T_PF_QUERY();
                                codeQuery.ORG_ID = query.ORG_ID;
                                CopyUtils.CopyObject(codeQuery, query);
                                if (queryAttr != null && queryAttr.Num != 0)
                                    codeQuery.NUM = queryAttr.Num + 1;
                                else
                                {
                                    codeQuery.NUM = queryNum;
                                    queryNum += 5;
                                }
                                codeQuery.QUERY_NAME = otherQueryName;
                                codeQuery.CASE = otherQueryCase;
                                dbModel.AddQuerys.Add(codeQuery);
                            }
                            else
                            {
                                if (!dbModel.UpdateQuerys.Any(t => t.ID == codeQuery.ID)) dbModel.UpdateQuerys.Add(codeQuery);
                            }

                            codeQuery.LABEL = otherLabel;
                            codeQuery.DATA_TYPE = (int)PFDataTypeEnum.字符;
                        }
                    }
                }

            }
            #endregion

            #region 添加表单按钮
            //列表页
            if (dbModel.AddTables.Any())
            {
                int btnNum = 0;
                dbModel.AddTables.ForEach(t =>
                {
                    if (t.PARENT_ID != null) return;

                    //新增
                    var addBtn = new T_PF_BTN();
                    addBtn.ORG_ID = t.ORG_ID;
                    addBtn.PAGE_TABLE_ID = t.ID;
                    addBtn.PAGE_ID = t.ID;
                    addBtn.LABEL = "新增";
                    addBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                    addBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                    addBtn.BTN_TYPE = (int)PFBtnTypeEnum.新增;
                    addBtn.CSS = "primary";
                    addBtn.ICON = "plus";
                    addBtn.IS_RULE = true;
                    if (editForm != null)
                        addBtn.FORM_CODE = editForm.CODE;
                    btnNum++;
                    addBtn.NUM = btnNum;
                    dbModel.AddBtns.Add(addBtn);

                    //编辑
                    var rowEditBtn = new T_PF_BTN();
                    rowEditBtn.ORG_ID = t.ORG_ID;
                    rowEditBtn.PAGE_TABLE_ID = t.ID;
                    rowEditBtn.PAGE_ID = t.ID;
                    rowEditBtn.LABEL = "编辑";
                    rowEditBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                    rowEditBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.行按钮;
                    rowEditBtn.BTN_TYPE = (int)PFBtnTypeEnum.编辑;
                    rowEditBtn.CSS = "primary";
                    rowEditBtn.ICON = "edit";
                    rowEditBtn.IS_RULE = true;
                    if (editForm != null)
                        rowEditBtn.FORM_CODE = editForm.CODE;
                    btnNum++;
                    rowEditBtn.NUM = btnNum;
                    dbModel.AddBtns.Add(rowEditBtn);

                    //删除
                    var deleteBtn = new T_PF_BTN();
                    deleteBtn.ORG_ID = t.ORG_ID;
                    deleteBtn.PAGE_TABLE_ID = t.ID;
                    deleteBtn.PAGE_ID = t.ID;
                    deleteBtn.LABEL = "删除";
                    deleteBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                    deleteBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                    deleteBtn.BTN_TYPE = (int)PFBtnTypeEnum.删除;
                    deleteBtn.CSS = "danger";
                    deleteBtn.ICON = "delete";
                    deleteBtn.IS_RULE = true;
                    btnNum++;
                    deleteBtn.NUM = btnNum;
                    dbModel.AddBtns.Add(deleteBtn);

                    //行项删除
                    var rowDeleteBtn = new T_PF_BTN();
                    rowDeleteBtn.ORG_ID = t.ORG_ID;
                    rowDeleteBtn.PAGE_TABLE_ID = t.ID;
                    rowDeleteBtn.PAGE_ID = t.ID;
                    rowDeleteBtn.LABEL = "删除";
                    rowDeleteBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                    rowDeleteBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.行按钮;
                    rowDeleteBtn.BTN_TYPE = (int)PFBtnTypeEnum.删除;
                    rowDeleteBtn.CSS = "danger";
                    rowDeleteBtn.ICON = "delete";
                    rowEditBtn.IS_RULE = true;
                    btnNum++;
                    rowDeleteBtn.NUM = btnNum;
                    dbModel.AddBtns.Add(rowDeleteBtn);


                    //导出
                    var outportBtn = new T_PF_BTN();
                    outportBtn.ORG_ID = t.ORG_ID;
                    outportBtn.PAGE_TABLE_ID = t.ID;
                    outportBtn.PAGE_ID = t.ID;
                    outportBtn.LABEL = "导出";
                    outportBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                    outportBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                    outportBtn.BTN_TYPE = (int)PFBtnTypeEnum.导出;
                    outportBtn.CSS = "default";
                    outportBtn.ICON = "export2";
                    outportBtn.IS_RULE = true;
                    btnNum++;
                    outportBtn.NUM = btnNum;
                    dbModel.AddBtns.Add(outportBtn);

                });
            }

            //树页面
            if (dbModel.AddTrees.Any())
            {
                int btnNum = 0;
                dbModel.AddTrees.ForEach(t =>
                {
                    //新增
                    var addBtn = new T_PF_BTN();
                    addBtn.ORG_ID = t.ORG_ID;
                    addBtn.PAGE_EDIT_ID = t.ID;
                    addBtn.PAGE_ID = t.ID;
                    addBtn.LABEL = "新增";
                    addBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.编辑页;
                    addBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                    addBtn.BTN_TYPE = (int)PFBtnTypeEnum.新增;
                    addBtn.CSS = "primary";
                    addBtn.ICON = "plus";
                    btnNum++;
                    addBtn.NUM = btnNum;
                    addBtn.IS_RULE = true;
                    dbModel.AddBtns.Add(addBtn);

                    //删除
                    var deleteBtn = new T_PF_BTN();
                    deleteBtn.ORG_ID = t.ORG_ID;
                    deleteBtn.PAGE_EDIT_ID = t.ID;
                    deleteBtn.PAGE_ID = t.ID;
                    deleteBtn.LABEL = "删除";
                    deleteBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                    deleteBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                    deleteBtn.BTN_TYPE = (int)PFBtnTypeEnum.删除;
                    deleteBtn.CSS = "danger";
                    deleteBtn.ICON = "delete";
                    deleteBtn.IS_RULE = true;
                    btnNum++;
                    deleteBtn.NUM = btnNum;
                    dbModel.AddBtns.Add(deleteBtn);
                });
            }

            //编辑页
            if (dbModel.AddEdits.Any())
            {
                int btnNum = 0;
                dbModel.AddEdits.ForEach(t =>
                {
                    if (t.PARENT_ID == null)
                    {
                        if (!isAddSend)
                        {
                            //保存
                            var saveBtn = new T_PF_BTN();
                            saveBtn.ORG_ID = t.ORG_ID;
                            saveBtn.PAGE_EDIT_ID = t.ID;
                            saveBtn.PAGE_ID = t.ID;
                            saveBtn.LABEL = "保存";
                            saveBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.编辑页;
                            saveBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                            saveBtn.BTN_TYPE = (int)PFBtnTypeEnum.保存;
                            saveBtn.CSS = "primary";
                            saveBtn.ICON = "save";
                            saveBtn.IS_RULE = true;
                            btnNum++;
                            saveBtn.NUM = btnNum;
                            dbModel.AddBtns.Add(saveBtn);
                        }
                        else
                        {
                            //保存
                            var saveBtn = new T_PF_BTN();
                            saveBtn.ORG_ID = t.ORG_ID;
                            saveBtn.PAGE_EDIT_ID = t.ID;
                            saveBtn.PAGE_ID = t.ID;
                            saveBtn.LABEL = "保存";
                            saveBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.编辑页;
                            saveBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                            saveBtn.BTN_TYPE = (int)PFBtnTypeEnum.保存;
                            saveBtn.CSS = "primary";
                            saveBtn.ICON = "save";
                            saveBtn.IS_RULE = true;
                            saveBtn.CUSTOM_PARAMS = "0";
                            btnNum++;
                            saveBtn.NUM = btnNum;
                            dbModel.AddBtns.Add(saveBtn);

                            //保存并发送
                            var saveBtnSnd = new T_PF_BTN();
                            saveBtnSnd.ORG_ID = t.ORG_ID;
                            saveBtnSnd.PAGE_EDIT_ID = t.ID;
                            saveBtnSnd.PAGE_ID = t.ID;
                            saveBtnSnd.LABEL = "保存并发送";
                            saveBtnSnd.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.编辑页;
                            saveBtnSnd.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                            saveBtnSnd.BTN_TYPE = (int)PFBtnTypeEnum.保存;
                            saveBtnSnd.CSS = "primary";
                            saveBtnSnd.ICON = "save";
                            saveBtnSnd.IS_RULE = true;
                            saveBtnSnd.CUSTOM_PARAMS = "10";
                            btnNum++;
                            saveBtnSnd.NUM = btnNum;
                            dbModel.AddBtns.Add(saveBtnSnd);
                        }
                    }
                    else
                    {
                        //新增
                        var addBtn = new T_PF_BTN();
                        addBtn.ORG_ID = t.ORG_ID;
                        addBtn.PAGE_EDIT_ID = t.ID;
                        addBtn.PAGE_ID = t.ID;
                        addBtn.LABEL = "新增";
                        addBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.编辑页;
                        addBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                        addBtn.BTN_TYPE = (int)PFBtnTypeEnum.新增;
                        addBtn.CSS = "primary";
                        addBtn.ICON = "plus";
                        addBtn.IS_RULE = true;
                        btnNum++;
                        addBtn.NUM = btnNum;
                        dbModel.AddBtns.Add(addBtn);

                        //删除
                        var deleteBtn = new T_PF_BTN();
                        deleteBtn.ORG_ID = t.ORG_ID;
                        deleteBtn.PAGE_EDIT_ID = t.ID;
                        deleteBtn.PAGE_ID = t.ID;
                        deleteBtn.LABEL = "删除";
                        deleteBtn.BTN_PAGE_TYPE = (int)PFBtnPageTypeEnum.列表页;
                        deleteBtn.BTN_FUN_TYPE = (int)PFBtnFuncTypeEnum.按钮;
                        deleteBtn.BTN_TYPE = (int)PFBtnTypeEnum.删除;
                        deleteBtn.CSS = "danger";
                        deleteBtn.ICON = "delete";
                        deleteBtn.IS_RULE = true;
                        btnNum++;
                        deleteBtn.NUM = btnNum;
                        dbModel.AddBtns.Add(deleteBtn);

                    }
                });
            }

            #endregion
            #region 菜单
            if (dbModel.AddForms.Any() && menuParentId != null)
            {
                var maxMenu = this.GetEntity<T_PF_MENU>(t => t.PARENT_ID == menuParentId, new BaseFilter(orgId)
                {
                    Sort = "NUM",
                    Order = DbOrder.DESC
                });
                dbModel.AddForms.ForEach(t =>
                            {
                                if (t.FORM_TYPE == (int)PFFormTypeEnum.编辑表单) return;
                                T_PF_MENU menu = new T_PF_MENU();
                                menu.ORG_ID = t.ORG_ID;
                                menu.PARENT_ID = menuParentId;
                                menu.IS_PERMISSION_MENU = true;
                                menu.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                                if (string.IsNullOrEmpty(menuName))
                                    menu.NAME = t.NAME;
                                else
                                    menu.NAME = menuName;
                                menu.MENU_FORM_ID = t.ID;
                                menu.ICON = menuIcon;
                                if (maxMenu != null)
                                    menu.NUM = maxMenu.NUM + 1;
                                menu.REMARK = "一键生成菜单";
                                dbModel.AddMenus.Add(menu);

                            });
            }

            #endregion

            #region 保存
            UnifiedCommit(() =>
            {
                this.BantchAddEntityNoCommit(dbModel.AddForms);
                this.BantchAddEntityNoCommit(dbModel.AddParamItems);
                this.BantchAddEntityNoCommit(dbModel.AddParamSchemes);
                this.BantchAddEntityNoCommit(dbModel.AddParamSchemeDetails);
                this.TreeBantchAddEntityNoCommit(dbModel.AddEdits);
                this.BantchAddEntityNoCommit(dbModel.AddEditPanels);
                this.BantchAddEntityNoCommit(dbModel.AddTablePanels);
                this.BantchAddEntityNoCommit(dbModel.AddEditColumns);
                this.BantchAddEntityNoCommit(dbModel.AddEditColumnFilters);
                this.BantchAddEntityNoCommit(dbModel.AddEditColumnFillMaps);
                this.BantchAddEntityNoCommit(dbModel.AddEditColumnFillMapDs);
                this.BantchAddEntityNoCommit(dbModel.AddCustoms);
                this.BantchAddEntityNoCommit(dbModel.AddCharts);
                this.BantchAddEntityNoCommit(dbModel.AddChartParams);
                this.TreeBantchAddEntityNoCommit(dbModel.AddTables);
                this.BantchAddEntityNoCommit(dbModel.AddColums);
                this.BantchAddEntityNoCommit(dbModel.AddColumFilters);
                this.BantchAddEntityNoCommit(dbModel.AddTableParams);
                this.BantchAddEntityNoCommit(dbModel.AddFormQuerys);
                this.BantchAddEntityNoCommit(dbModel.AddQuerys);
                this.BantchAddEntityNoCommit(dbModel.AddTrees);
                this.BantchAddEntityNoCommit(dbModel.AddTreeColumns);
                this.BantchAddEntityNoCommit(dbModel.AddBtns);
                this.BantchAddEntityNoCommit(dbModel.AddMenus);



                this.BantchUpdateEntityNoCommit(dbModel.UpdateForms);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateParamItems);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateParamSchemes);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateParamSchemeDetails);
                this.TreeBantchUpdateEntityNoCommit(dbModel.UpdateEdits);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateEditPanels);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateTablePanels);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateEditColumns);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateEditColumnFilters);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateEditColumnFillMaps);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateEditColumnFillMapDs);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateCustoms);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateCharts);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateChartParams);
                this.TreeBantchUpdateEntityNoCommit(dbModel.UpdateTables);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateColums);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateColumFilters);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateTableParams);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateFormQuerys);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateQuerys);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateTrees);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateTreeColumns);
                this.BantchUpdateEntityNoCommit(dbModel.UpdateBtns);


            });
            #endregion

            #region 表单版本升级
            List<Guid> versionFormIds = new List<Guid>();
            List<T_PF_PAGE_TABLE> versionPageTables = new List<T_PF_PAGE_TABLE>();
            List<T_PF_COLUMN> versionColumns = new List<T_PF_COLUMN>();
            List<T_PF_PAGE_TABLE_PANEL> versionPageTablePanels = new List<T_PF_PAGE_TABLE_PANEL>();

            if (treeForm != null) versionFormIds.Add(treeForm.ID);
            if (editForm != null) versionFormIds.Add(editForm.ID);
            if (tableForm != null) versionFormIds.Add(tableForm.ID);
            if (dbModel.AddTables.Any()) versionPageTables.AddRange(dbModel.AddTables);
            if (dbModel.UpdateTables.Any()) versionPageTables.AddRange(dbModel.UpdateTables);
            if (dbModel.AddColums.Any()) versionColumns.AddRange(dbModel.AddColums);
            if (dbModel.UpdateColums.Any()) versionColumns.AddRange(dbModel.UpdateColums);
            if (dbModel.AddTablePanels.Any()) versionPageTablePanels.AddRange(dbModel.AddTablePanels);
            if (dbModel.UpdateTablePanels.Any()) versionPageTablePanels.AddRange(dbModel.UpdateTablePanels);

            formService.AddFormConfigVersion(versionFormIds, versionPageTables, versionColumns,
                    versionPageTablePanels, null);
            #endregion
        }

        private string GetApiPrefixByName(string tableName)
        {
            var newName = tableName.ToLower();
            var newNameAry = newName.Split(new char[] { '_' });
            var fixName = "";
            string moduleName = string.Empty;
            if (newNameAry.Any() && newNameAry.Length >= 2)
            {
                moduleName = newNameAry[1].ToUpper();
                for (var n = 2; n < newNameAry.Length; n++)
                    fixName += System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(newNameAry[n]);
            }
            if (string.IsNullOrEmpty(moduleName) || string.IsNullOrEmpty(fixName)) return string.Empty;
            return moduleName + "/" + fixName + "/";
        }

        private T GetAttributeByType<T>(Type type) where T : Attribute
        {
            T attr = null;
            object[] attrs = type.GetCustomAttributes(typeof(T), true);
            if (attrs.Length == 1)
                attr = (T)attrs[0];
            return attr;
        }

        private T GetAttributeByProperty<T>(PropertyInfo property) where T : Attribute
        {
            T attr = null;
            object[] attrs = property.GetCustomAttributes(typeof(T), true);
            if (attrs.Length == 1)
                attr = (T)attrs[0];
            return attr;
        }

        /// <summary>
        /// 初始化表单配置
        /// </summary>
        /// <param name="type"></param>
        /// <param name="editForm"></param>
        /// <param name="tableForm"></param>
        /// <param name="treeForm"></param>
        /// <param name="parentPageEdit"></param>
        /// <param name="parentPageTable"></param>
        /// <param name="parentPageTree"></param>
        /// <param name="num"></param>
        /// <param name="relationFieldName"></param>
        /// <param name="navPropertyName"></param>
        /// <param name="dbModel"></param>
        private void DoInitFormConfigByName(Type type, T_PF_FORM editForm,
            T_PF_FORM tableForm, T_PF_FORM treeForm, T_PF_PAGE_EDIT parentPageEdit, T_PF_PAGE_TABLE parentPageTable,
            T_PF_PAGE_TREE parentPageTree,
                int num, string relationFieldName, string navPropertyName, FormConfigDbModel dbModel, bool isAddSend = false, string FormCode = "")
        {
            if (type == null ||
                tableForm == null && treeForm == null && editForm == null) return;
            string tableName = type.Name;
            string apiPrefix = GetApiPrefixByName(tableName);
            var typeDescriptionAttr = GetAttributeByType<DescriptionAttribute>(type);
            int listNum = 0;

            num++;

            //编辑
            T_PF_PAGE_EDIT pageEdit = null;
            List<T_PF_EDIT_COLUMN> pageEditColumns = null;
            if (editForm != null)
            {
                if (parentPageEdit == null && string.IsNullOrEmpty(apiPrefix)) return;

                pageEdit = this.GetEntity<T_PF_PAGE_EDIT>(t => t.PAGE_FORM_ID == editForm.ID
                   && t.EDIT_NAME == tableName);
                if (pageEdit == null)
                {
                    pageEdit = new T_PF_PAGE_EDIT();
                    pageEdit.ORG_ID = editForm.ORG_ID;
                    pageEdit.PAGE_FORM_ID = editForm.ID;
                    pageEdit.CODE = tableName;
                    pageEdit.EDIT_NAME = tableName;
                    pageEdit.NUM = num;
                    if (parentPageEdit == null)
                    {
                        if (isAddSend)
                        {
                            string TempApi = apiPrefix.Replace(FormCode + "/", FormCode + "/" + FormCode);
                            pageEdit.API_URL = TempApi + "FullUpdate";
                        }
                        else
                            pageEdit.API_URL = apiPrefix + "Update";

                        pageEdit.QUERY_API_URL = apiPrefix + "Get";
                    }
                    dbModel.AddEdits.Add(pageEdit);
                    //子表处理
                }
                else
                {
                    if (!dbModel.UpdateEdits.Any(t => t.ID == pageEdit.ID)) dbModel.UpdateEdits.Add(pageEdit);
                    pageEditColumns = this.GetEntities<T_PF_EDIT_COLUMN>(t => t.PAGE_EDIT_ID == pageEdit.ID).ToList();
                }

                var typeClassEditAttr = this.GetAttributeByType<FormClassEditAttribute>(type);
                if (typeClassEditAttr != null && !string.IsNullOrEmpty(typeClassEditAttr.DisplayName))
                    pageEdit.LABEL_NAME = typeClassEditAttr.DisplayName;
                else if (typeDescriptionAttr != null)
                    pageEdit.LABEL_NAME = typeDescriptionAttr.Description;
                else
                    pageEdit.LABEL_NAME = tableName;

                if (parentPageEdit != null)
                {
                    pageEdit.PARENT_ID = parentPageEdit.ID;
                    pageEdit.RELATION_FIELD = relationFieldName;
                    pageEdit.NAV_PROPERTY = navPropertyName;
                }

            }

            //列表
            T_PF_PAGE_TABLE pageTable = null;
            List<T_PF_COLUMN> pageColumns = null;
            if (tableForm != null)
            {
                if (string.IsNullOrEmpty(apiPrefix)) return;
                pageTable = this.GetEntity<T_PF_PAGE_TABLE>(t => t.PAGE_FORM_ID == tableForm.ID
                            && t.DATA_TABLE == tableName);
                if (pageTable == null)
                {
                    pageTable = new T_PF_PAGE_TABLE();
                    pageTable.ORG_ID = tableForm.ORG_ID;
                    pageTable.PAGE_FORM_ID = tableForm.ID;
                    pageTable.CODE = tableName;
                    pageTable.TABLE_NAME = tableName;
                    pageTable.DATA_TABLE = tableName;
                    pageTable.SHOW_CHECK = true;
                    pageTable.API_URL = apiPrefix + "OrderPaged";
                    pageTable.DEL_API_URL = apiPrefix + "Delete";
                    pageTable.BATCH_DEL_API_URL = apiPrefix + "BatchDelete";
                    pageTable.NUM = num;
                    pageTable.IS_SHOW_ROW_NO = true;
                    dbModel.AddTables.Add(pageTable);
                }
                else
                {
                    if (!dbModel.UpdateTables.Any(t => t.ID == pageTable.ID)) dbModel.UpdateTables.Add(pageTable);
                    pageColumns = this.GetEntities<T_PF_COLUMN>(t => t.PAGE_TABLE_ID == pageTable.ID).ToList();
                }

                var typeClassTableAttr = this.GetAttributeByType<FormClassTableAttribute>(type);
                if (typeClassTableAttr != null && !string.IsNullOrEmpty(typeClassTableAttr.DisplayName))
                    pageTable.LABEL_NAME = typeClassTableAttr.DisplayName;
                else if (typeDescriptionAttr != null)
                    pageTable.LABEL_NAME = typeDescriptionAttr.Description;
                else
                    pageTable.LABEL_NAME = tableName;

                if (parentPageTable != null)
                    pageTable.PARENT_ID = parentPageTable.ID;
                pageTable.RELATION_FIELD = relationFieldName;
            }


            //树
            T_PF_PAGE_TREE pageTree = null;
            List<T_PF_TREE_COLUMN> pageTreeColumns = null;
            if (treeForm != null)
            {
                if (string.IsNullOrEmpty(apiPrefix)) return;
                pageTree = this.GetEntity<T_PF_PAGE_TREE>(t => t.PAGE_FORM_ID == treeForm.ID);
                if (pageTree == null)
                {
                    pageTree = new T_PF_PAGE_TREE();
                    pageTree.ORG_ID = treeForm.ORG_ID;
                    pageTree.PAGE_FORM_ID = treeForm.ID;
                    pageTree.QUERY_API_URL = apiPrefix + "OrderEntities";
                    pageTree.BATCH_DEL_API_URL = apiPrefix + "BatchDelete";
                    pageTree.NUM = num;
                    dbModel.AddTrees.Add(pageTree);
                }
                else
                {
                    if (!dbModel.UpdateTrees.Any(t => t.ID == pageTree.ID)) dbModel.UpdateTrees.Add(pageTree);
                    pageTreeColumns = this.GetEntities<T_PF_TREE_COLUMN>(t => t.PAGE_TREE_ID == pageTree.ID).ToList();
                }
                var typeClassTreeAttr = this.GetAttributeByType<FormClassTreeAttribute>(type);
                if (typeClassTreeAttr != null && !string.IsNullOrEmpty(typeClassTreeAttr.DisplayName))
                    pageTree.LABEL_NAME = typeClassTreeAttr.DisplayName;
                else if (typeDescriptionAttr != null)
                    pageTree.LABEL_NAME = typeDescriptionAttr.Description;
                else
                    pageTree.LABEL_NAME = tableName;
            }


            int editFieldNum = pageEditColumns != null && pageEditColumns.Any() ? (pageEditColumns.Max(t => t.NUM) + 1) : 1;
            int tableFieldNum = pageColumns != null && pageColumns.Any() ? (pageColumns.Max(t => t.NUM) + 1) : 1;
            int treeFieldNum = pageTreeColumns != null && pageTreeColumns.Any() ? (pageTreeColumns.Max(t => t.NUM) + 1) : 1;

            //循环获取字段配置数据
            foreach (var property in type.GetProperties())
            {
                var tableAttr = this.GetAttributeByProperty<FormFieldTableAttribute>(property);
                var editAttr = this.GetAttributeByProperty<FormFieldEditAttribute>(property);
                var treeAttr = this.GetAttributeByProperty<FormFieldTreeAttribute>(property);
                var requireAttr = this.GetAttributeByProperty<DataFieldRequireAttribute>(property);

                var propertyType = property.PropertyType;
                var propertyDescAttr = this.GetAttributeByProperty<DescriptionAttribute>(property);
                string fieldName = property.Name;
                if (string.Compare(fieldName, "CODE", true) == 0)
                {
                    if (tableAttr == null)
                        tableAttr = new FormFieldTableAttribute();
                    if (editAttr == null)
                        editAttr = new FormFieldEditAttribute();
                }
                else if (string.Compare(fieldName, "NAME", true) == 0)
                {
                    if (tableAttr == null)
                        tableAttr = new FormFieldTableAttribute();
                    if (editAttr == null)
                        editAttr = new FormFieldEditAttribute();
                    if (treeAttr == null)
                        treeAttr = new FormFieldTreeAttribute();
                }
                else if (string.Compare(fieldName, "REMARK", true) == 0)
                {
                    if (editAttr == null)
                        editAttr = new FormFieldEditAttribute();
                }
                else if (string.Compare(fieldName, "ENABLE_STATUS", true) == 0)
                {
                    if (tableAttr == null)
                        tableAttr = new FormFieldTableAttribute();
                    if (editAttr == null)
                        editAttr = new FormFieldEditAttribute();
                }
                else if (string.Compare(fieldName, "ORDER_STATUS", true) == 0)
                {
                    if (tableAttr == null)
                        tableAttr = new FormFieldTableAttribute();
                }


                //列表
                if (propertyType.IsGenericType && typeof(System.Collections.IEnumerable).IsAssignableFrom(propertyType))
                {
                    var tempTableForm = tableAttr != null ? tableForm : null;
                    var tempEditForm = editAttr != null ? editForm : null;
                    if (tempTableForm != null || tempEditForm != null)
                    {
                        var genArgs = propertyType.GetGenericArguments();
                        if (genArgs != null && genArgs.Any())
                        {
                            string idName = string.Empty;
                            var foreignForMasterAttr = this.GetAttributeByProperty<DataFieldForeignKeyForMasterAttribute>(property);
                            if (foreignForMasterAttr != null)
                                idName = foreignForMasterAttr.IdFieldName;
                            else
                            {
                                var fkeyP = this.UnitOfWork.GetModelForeignKey(tableName, property.Name);
                                if (fkeyP != null)
                                    idName = fkeyP.ForeignFieldName;
                            }
                            DoInitFormConfigByName(genArgs[0], tempEditForm, tempTableForm, null, pageEdit, pageTable, pageTree,
                                listNum, idName, property.Name, dbModel);
                            listNum++;
                        }
                    }
                }
                else
                {

                    var realPropertyType = property.PropertyType.GetNonNummableType();
                    #region 编辑属性
                    if (editAttr != null && pageEdit != null)
                    {
                        bool required = requireAttr != null ? requireAttr.IsRequire : false;
                        int codeRuleType = 0, controlType = (int)PFControlTypeEnum.文本输入, editColCase = 0;
                        bool editable = true;
                        string enumName = null, inputIdField = null, inputDataApi = null, inputFilterField = null,
                            inputLableFiled = null, inputShowField = null, inputNavFiled = null, inputSaveField = null,
                            showFormCode = null, showIdField = null;
                        string colFieldName = fieldName;
                        bool isAddEnableStatusFilter = false;
                        int dataFileLen = 500;
                        if (realPropertyType == typeof(string))
                        {
                            var codeRuleAttr = this.GetAttributeByProperty<CodeRuleAttribute>(property);
                            if (codeRuleAttr != null && codeRuleAttr.CodeRuleTypes != null && codeRuleAttr.CodeRuleTypes.Any())
                            {
                                required = true;
                                editable = false;
                                codeRuleType = codeRuleAttr.CodeRuleTypes[0];
                                controlType = (int)PFControlTypeEnum.系统序列号控件;
                                editColCase = (int)FMCaseProcEnum.转大写;
                            }
                            else
                            {
                                if (string.Compare(fieldName, "REMARK", true) == 0)
                                {
                                    if (parentPageEdit == null)
                                        controlType = (int)PFControlTypeEnum.长文本域;
                                }
                                else
                                {
                                    if (string.Compare(fieldName, "NAME", true) == 0)
                                        required = true;
                                    else if (string.Compare(fieldName, "CODE", true) == 0)
                                    {
                                        editColCase = (int)FMCaseProcEnum.转大写;
                                        required = true;
                                    }
                                }
                            }

                            var dataFileLength = this.GetAttributeByProperty<DataFieldLengthAttribute>(property);
                            if (dataFileLength != null)
                            {
                                dataFileLen = dataFileLength.Length;
                            }
                        }
                        else if (realPropertyType == typeof(int) || realPropertyType.IsEnum)
                        {
                            EnumNameAttribute enumNameAttr = this.GetAttributeByProperty<EnumNameAttribute>(property);
                            string tempEnumName = enumNameAttr != null ? enumNameAttr.EnumName : ((realPropertyType.IsEnum) ? realPropertyType.Name : string.Empty);
                            if (string.IsNullOrEmpty(tempEnumName))
                                controlType = (int)PFControlTypeEnum.数值类型;
                            else
                            {
                                enumName = tempEnumName;
                                controlType = (int)PFControlTypeEnum.下拉选择;
                            }
                        }
                        else if (realPropertyType == typeof(decimal))
                        {
                            controlType = (int)PFControlTypeEnum.数值类型;
                        }
                        else if (realPropertyType == typeof(bool))
                        {
                            controlType = (int)PFControlTypeEnum.单项选框;
                        }
                        else if (realPropertyType == typeof(DateTime))
                        {
                            controlType = (int)PFControlTypeEnum.日期选择;
                        }
                        else if (realPropertyType == typeof(Guid) ||
                            realPropertyType != typeof(string) && realPropertyType.IsClass)
                        {
                            string navTableName = string.Empty;
                            string idName = string.Empty;
                            string navFieldName = string.Empty;
                            GetNavInfoByProperty(type, tableName, property, fieldName, realPropertyType, ref navTableName,
                                ref idName, ref navFieldName);

                            if (!string.IsNullOrEmpty(navTableName))
                            {
                                var navType = DataHelper.GetTypeByEntityName(navTableName);
                                inputDataApi = GetApiPrefixByName(navTableName) + "OrderPaged";
                                var navCodeP = navType.GetProperty("CODE");
                                var navNameP = navType.GetProperty("NAME");
                                if (navCodeP == null)
                                    navCodeP = navType.GetProperty("PDT_CODE");
                                if (navCodeP != null && navNameP != null)
                                {
                                    colFieldName = navFieldName + "." + navNameP.Name;
                                    inputNavFiled = "ID," + navNameP.Name;
                                    inputSaveField = idName + "," + colFieldName;
                                }
                                else if (navCodeP == null && navNameP != null)
                                {
                                    colFieldName = navFieldName + "." + navNameP.Name;
                                    inputFilterField = navNameP.Name;
                                    inputLableFiled = navNameP.Name;
                                    inputShowField = navNameP.Name;
                                    inputNavFiled = "ID," + navNameP.Name;
                                    inputSaveField = idName + "," + colFieldName;
                                }
                                else if (navCodeP != null && navNameP == null)
                                {
                                    colFieldName = navFieldName + "." + navCodeP.Name;
                                    inputFilterField = navCodeP.Name;
                                    inputLableFiled = navCodeP.Name;
                                    inputShowField = navCodeP.Name;
                                    inputNavFiled = "ID," + navCodeP.Name;
                                    inputSaveField = idName + "," + colFieldName;
                                }

                                isAddEnableStatusFilter = navType.GetProperty("ENABLE_STATUS") != null;

                                var f = this.GetEntity<T_PF_FORM>(t => t.TABLE_NAME == navTableName &&
                                    t.ENABLE_STATUS == 0 && t.FORM_TYPE != (int)PFFormTypeEnum.列表表单 &&
                                        t.FORM_TYPE != (int)PFFormTypeEnum.图表表单);
                                if (f != null)
                                {
                                    showFormCode = f.CODE;
                                    showIdField = idName;
                                }
                            }
                            inputIdField = idName;
                            controlType = (int)PFControlTypeEnum.分页下拉;
                            if (!string.IsNullOrEmpty(idName))
                            {
                                var idP = type.GetProperty(idName);
                                if (idP != null && requireAttr == null)
                                {
                                    var tempRequireAttr = this.GetAttributeByProperty<DataFieldRequireAttribute>(idP);
                                    if (tempRequireAttr != null)
                                        required = tempRequireAttr.IsRequire;
                                }
                                if (idP != null && !idP.PropertyType.IsNullableType())
                                    required = true;
                            }
                        }


                        var editColumn = pageEditColumns == null ? null : pageEditColumns.FirstOrDefault(t => t.FIELD_NAME == colFieldName);
                        if (editColumn == null)
                        {
                            editColumn = new T_PF_EDIT_COLUMN();
                            editColumn.ORG_ID = pageEdit.ORG_ID;
                            editColumn.PAGE_EDIT_ID = pageEdit.ID;
                            editColumn.FIELD_NAME = colFieldName;
                            editColumn.IS_DEFAULT = true;
                            editColumn.MAX_LEN = dataFileLen;
                            editColumn.TYPE_NAME = realPropertyType.Name;
                            if (editAttr != null && editAttr.Num != 0)
                                editColumn.NUM = editAttr.Num;
                            else
                            {
                                editColumn.NUM = editFieldNum;
                                editFieldNum += 10;
                            }
                            editColumn.REQUIRED = required;
                            editColumn.EDITABLE = editable;
                            editColumn.CODE_RULE_TYPE = codeRuleType;
                            editColumn.CONTROL_TYPE = controlType;
                            editColumn.CASE = editColCase;

                            editColumn.INPUT_DATA_API = inputDataApi;
                            editColumn.INPUT_FILTER_FIELD = inputFilterField;
                            editColumn.INPUT_LABEL_FIELD = inputLableFiled;
                            editColumn.INPUT_SHOW_FIELD = inputShowField;
                            editColumn.INPUT_NAV_FIELD = inputNavFiled;
                            editColumn.INPUT_SAVE_FIELD = inputSaveField;
                            editColumn.INPUT_ID_FIELD = inputIdField;

                            dbModel.AddEditColumns.Add(editColumn);

                            if (isAddEnableStatusFilter)
                            {
                                var editColumnFilter = new T_PF_EDIT_COLUMN_FILTER();
                                editColumnFilter.ORG_ID = editColumn.ORG_ID;
                                editColumnFilter.EDIT_COLUMN_ID = editColumn.ID;
                                editColumnFilter.PAGE_EDIT_ID = editColumn.PAGE_EDIT_ID;
                                editColumnFilter.FIELD_NAME = "ENABLE_STATUS";
                                editColumnFilter.OPERATION = 1;
                                editColumnFilter.VALUE = "0";
                                dbModel.AddEditColumnFilters.Add(editColumnFilter);
                            }
                        }
                        else
                        {
                            if (!dbModel.UpdateEditColumns.Any(t => t.ID == editColumn.ID)) dbModel.UpdateEditColumns.Add(editColumn);
                        }

                        editColumn.LABEL = !string.IsNullOrEmpty(editAttr.DisplayName) ? editAttr.DisplayName :
                                (propertyDescAttr != null ? propertyDescAttr.Description : colFieldName);
                        editColumn.ENUM = enumName;
                        editColumn.SHOW_FORM_CODE = showFormCode;
                        editColumn.SHOW_ID_FIELD = showIdField;

                    }
                    #endregion

                    #region 列表属性
                    if (tableAttr != null && pageTable != null)
                    {
                        bool isDefault = true;
                        int controlType = 0;
                        string enumName = null, showFormCode = null, showIdField = null;
                        string colFieldName = fieldName;

                        if (string.Compare(fieldName, "REMARK", true) == 0)
                        {
                            controlType = (int)PFColumnControlTypeEnum.文本_最大10字符;
                        }
                        else if (realPropertyType == typeof(int) || realPropertyType.IsEnum)
                        {
                            EnumNameAttribute enumNameAttr = this.GetAttributeByProperty<EnumNameAttribute>(property);
                            enumName = enumNameAttr != null ? enumNameAttr.EnumName : ((realPropertyType.IsEnum) ? realPropertyType.Name : string.Empty);

                        }
                        else if (realPropertyType == typeof(Guid) ||
                            realPropertyType.IsClass && realPropertyType != typeof(string))
                        {
                            string navTableName = string.Empty;
                            string idName = string.Empty;
                            string navFieldName = string.Empty;
                            GetNavInfoByProperty(type, tableName, property, fieldName, realPropertyType, ref navTableName,
                                ref idName, ref navFieldName);

                            if (string.IsNullOrEmpty(navFieldName))
                                isDefault = false;

                            if (!string.IsNullOrEmpty(navTableName))
                            {
                                var navType = DataHelper.GetTypeByEntityName(navTableName);
                                var navCodeP = navType.GetProperty("CODE");
                                var navNameP = navType.GetProperty("NAME");
                                if (navCodeP == null)
                                    navCodeP = navType.GetProperty("PDT_CODE");
                                if (navCodeP != null && navNameP != null)
                                {
                                    colFieldName = navFieldName + "." + navNameP.Name;
                                }
                                else if (navCodeP == null && navNameP != null)
                                {
                                    colFieldName = navFieldName + "." + navNameP.Name;
                                }
                                else if (navCodeP != null && navNameP == null)
                                {
                                    colFieldName = navFieldName + "." + navCodeP.Name;
                                }

                                var f = this.GetEntity<T_PF_FORM>(t => t.TABLE_NAME == navTableName &&
                                    t.ENABLE_STATUS == 0 && t.FORM_TYPE != (int)PFFormTypeEnum.列表表单 &&
                                        t.FORM_TYPE != (int)PFFormTypeEnum.图表表单);
                                if (f != null)
                                {
                                    showFormCode = f.CODE;
                                    showIdField = idName;
                                }
                            }
                        }


                        var column = pageColumns == null ? null : pageColumns.FirstOrDefault(t => t.FIELD_NAME == colFieldName);
                        if (column == null)
                        {
                            column = new T_PF_COLUMN();
                            column.ORG_ID = pageTable.ORG_ID;
                            column.PAGE_TABLE_ID = pageTable.ID;
                            column.FIELD_NAME = colFieldName;
                            column.IS_DEFAULT = isDefault;
                            column.CONTROL_TYPE = controlType;
                            if (tableAttr != null && tableAttr.Num != 0)
                                column.NUM = tableAttr.Num;
                            else
                            {
                                column.NUM = tableFieldNum;
                                tableFieldNum += 10;
                            }
                            dbModel.AddColums.Add(column);
                        }
                        else
                        {
                            if (!dbModel.UpdateColums.Any(t => t.ID == column.ID)) dbModel.UpdateColums.Add(column);
                        }

                        column.LABEL = !string.IsNullOrEmpty(tableAttr.DisplayName) ? tableAttr.DisplayName :
                                (propertyDescAttr != null ? propertyDescAttr.Description : fieldName);
                        column.ENUM = enumName;
                        column.SHOW_FORM_CODE = showFormCode;
                        column.SHOW_ID_FIELD = showIdField;
                    }
                    #endregion

                    #region 树属性
                    if (treeAttr != null && pageTree != null)
                    {

                        var treeColumn = pageTreeColumns == null ? null : pageTreeColumns.FirstOrDefault(t => t.FIELD_NAME == fieldName);
                        if (treeColumn == null)
                        {
                            treeColumn = new T_PF_TREE_COLUMN();
                            treeColumn.ORG_ID = pageTree.ORG_ID;
                            treeColumn.PAGE_TREE_ID = pageTree.ID;
                            treeColumn.FIELD_NAME = fieldName;
                            if (treeAttr != null && treeAttr.Num != 0)
                                treeColumn.NUM = treeAttr.Num;
                            else
                            {
                                treeColumn.NUM = treeFieldNum;
                                treeFieldNum += 10;
                            }
                            dbModel.AddTreeColumns.Add(treeColumn);
                        }
                        else
                        {
                            if (!dbModel.UpdateTreeColumns.Any(t => t.ID == treeColumn.ID)) dbModel.UpdateTreeColumns.Add(treeColumn);
                        }

                        if (realPropertyType == typeof(int) || realPropertyType.IsEnum)
                        {
                            EnumNameAttribute enumNameAttr = this.GetAttributeByProperty<EnumNameAttribute>(property);
                            treeColumn.ENUM = enumNameAttr != null ? enumNameAttr.EnumName : ((realPropertyType.IsEnum) ? realPropertyType.Name : string.Empty);

                        }
                    }
                    #endregion

                }


            }
        }

        private void GetNavInfoByProperty(Type tableType, string tableName, PropertyInfo property,
             string fieldName, Type realPropertyType, ref string navTableName,
                    ref string idName, ref string navFieldName)
        {
            if (realPropertyType == typeof(Guid))
            {
                var keyP = this.GetAttributeByProperty<DataFieldForeignKeyAttribute>(property);
                if (keyP != null)
                    navFieldName = keyP.NavFieldName;
                else
                {
                    var keyModel = this.UnitOfWork.GetModelForeignKeyById(tableName, fieldName);
                    if (keyModel != null)
                        navFieldName = keyModel.ForeignNavName;
                }
                if (!string.IsNullOrEmpty(navFieldName))
                {
                    var navP = tableType.GetProperty(navFieldName);
                    if (navP != null)
                        navTableName = navP.PropertyType.Name;
                }
                idName = fieldName;
            }
            else
            {
                navTableName = realPropertyType.Name;
                navFieldName = fieldName;
                foreach (var pp in tableType.GetProperties())
                {
                    var keyPP = this.GetAttributeByProperty<DataFieldForeignKeyAttribute>(pp);
                    if (keyPP != null && string.Compare(keyPP.NavFieldName, fieldName, true) == 0)
                        idName = pp.Name;
                }
                if (string.IsNullOrEmpty(idName))
                {
                    var keyModel = this.UnitOfWork.GetModelForeignKey(tableName, navFieldName);
                    if (keyModel != null)
                        idName = keyModel.ForeignFieldName;
                }
            }
        }







    }
}
