using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace APT.BaseData.Services.Services.FM
{
    public class FMImportService : CommonService, IFMImportService
    {
        public FMImportService(IRepository repository)
            : base(repository)
        {

        }

        private Dictionary<string, object> NavcationList = new Dictionary<string, object>();

        /// <summary>
        /// 获取导入数据
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="configCode"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public ImportDataModel GetImortData(Guid orgId, string configCode, string filePath, bool IsUpdate, bool delFlag)
        {
            var importConfig = this.GetEntity<T_FM_IMPORT_CONFIG>(t => t.CODE == configCode, new BaseFilter(orgId));
            if (importConfig == null)
                throw new Exception("无效导入配置");
            if (string.IsNullOrEmpty(importConfig.TABLE_NAME))
                throw new Exception("未配置表名");
            Dictionary<string, Type> existTypes = new Dictionary<string, Type>();
            var type = this.GetTypeByEntityName(importConfig.TABLE_NAME, existTypes);
            if (type == null)
                throw new Exception("无效表名");

            var configDetails = this.GetEntities<T_FM_IMPORT_CONFIG_DETAIL>(t => t.IMPORT_CONFIG_ID == importConfig.ID, new BaseFilter(orgId), new string[] { "Nav_Fields" }).ToList();
            if (configDetails == null || !configDetails.Any())
                throw new Exception("未配置明细信息");
            ImportDataModel importData = new ImportDataModel();

            Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
            configDetails.ForEach(t =>
            {
                startRowIndexs[t.SHEET_INDEX] = t.START_ROW_INDEX;
            });
            //获取数据
            var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);

            List<T_PF_PAGE_EDIT> pageEdits = null;
            if (!string.IsNullOrEmpty(importConfig.EDIT_FORM_CODE))
                pageEdits = this.GetEntities<T_PF_PAGE_EDIT>(t => t.Nav_PageForm.CODE == importConfig.EDIT_FORM_CODE, new BaseFilter(importConfig.ORG_ID), new string[] { "Nav_Columns" }).ToList();

            //获取主表配置信息
            var firstConfigDetail = configDetails.FirstOrDefault(t => t.PARENT_ID == null);
            var param = DoGetImportInvokeParam(firstConfigDetail, null, dataTables, pageEdits, existTypes, importData);
            if (param != null)
            {
                param.IsUpdate = IsUpdate;
                param.DelFlag = delFlag;
                //获取从表配置信息
                GetImportInvokeParam(firstConfigDetail.ID, param, configDetails, dataTables, pageEdits, existTypes, importData);

                //从数据获取对象
                try
                {

                    MethodInfo methodInfo = this.GetType().GetMethod("DoGetEntityByTable", BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                    importData.Data = methodInfo.MakeGenericMethod(new Type[] { type }).Invoke(this, new object[] { param });
                }
                catch (TargetInvocationException ex)
                {
                    this.ThrowError("010001", ex.InnerException.Message);
                }
            }
            return importData;
        }
        public dynamic DownLoadFile(dynamic config)
        {
            string editConfig = config.CODE;
            Guid orgid = config.ORG_ID;
            bool isData = config.IsData;
            var importConfig = this.GetEntity<T_FM_IMPORT_CONFIG>(t => t.CODE == editConfig, new BaseFilter(orgid));
            if (importConfig == null)
                throw new Exception("无效导入配置");
            if (string.IsNullOrEmpty(importConfig.TABLE_NAME))
                throw new Exception("未配置表名");
            //Dictionary<string, Type> existTypes = new Dictionary<string, Type>();
            //var type = this.GetTypeByEntityName(importConfig.TABLE_NAME, existTypes);
            var filter = new BaseFilter(orgid);
            filter.Sort = "SHEET_INDEX";

            var configDetails = this.GetEntities<T_FM_IMPORT_CONFIG_DETAIL>(t => t.IMPORT_CONFIG_ID == importConfig.ID,
                filter, new string[] { "Nav_Fields" }).OrderBy(t => t.SHEET_INDEX).ToList();
            if (configDetails == null || !configDetails.Any())
                throw new Exception("未配置明细信息");
            //configDetails = configDetails.OrderBy(t => t.SHEET_INDEX);
            List<T_PF_PAGE_EDIT> pageEdits = null;
            if (!string.IsNullOrEmpty(importConfig.EDIT_FORM_CODE))
                pageEdits = this.GetEntities<T_PF_PAGE_EDIT>(t => t.Nav_PageForm.CODE == importConfig.EDIT_FORM_CODE,
                        new BaseFilter(importConfig.ORG_ID), new string[] { "Nav_Columns" }).ToList();
            var editConfigs = GetImportColumns(importConfig);
            foreach (var c in configDetails)
            {
                T_PF_PAGE_EDIT table = null;
                if (c.PARENT_ID == null)
                {
                    table = pageEdits.FirstOrDefault(i => i.PARENT_ID == null);

                }
                else
                {
                    if (!string.IsNullOrEmpty(c.PAGE_EDIT_CODE))
                    {
                        table = pageEdits.FirstOrDefault(i => i.CODE == c.PAGE_EDIT_CODE);
                    }
                    else
                    {
                        table = pageEdits.FirstOrDefault();
                    }
                }
                ImportData(orgid, c, table, configDetails, editConfigs, isData);
            }
            if (configDetails.Any())
            {
                var index = configDetails.LastOrDefault().SHEET_INDEX + 1;
                T_FM_IMPORT_CONFIG_DETAIL infoDetail = new T_FM_IMPORT_CONFIG_DETAIL();
                infoDetail.SHEET_INDEX = index;
                infoDetail.DESCRIPTION = "导入枚举字段说明";

                List<ImportTableColumnModel> enumsCols = new List<ImportTableColumnModel>();
                GetEnumColums(editConfigs, enumsCols);
                //Dictionary<string, string> enumDesc = new Dictionary<string, string>();
                infoDetail.Nav_Fields = new List<T_FM_IMPORT_CONFIG_FIELD>();
                infoDetail.Nav_Fields.Add(new T_FM_IMPORT_CONFIG_FIELD() { DEST_FIELD_NAME = "enumname", SRC_FIELD_NAME = "字段" });
                infoDetail.Nav_Fields.Add(new T_FM_IMPORT_CONFIG_FIELD() { DEST_FIELD_NAME = "enumdesc", SRC_FIELD_NAME = "对应关系" });
                if (enumsCols.Any())
                {
                    var data = new List<dynamic>();
                    List<string> hasEnums = new List<string>();
                    foreach (var e in enumsCols)
                    {


                        var enumType = DataHelper.EnumToType(e.Nav_EditColumn.ENUM);
                        if (enumType != null && enumType.IsEnum && !hasEnums.Contains(e.Nav_EditColumn.ENUM))
                        {
                            dynamic enumObj = new System.Dynamic.ExpandoObject();
                            enumObj.enumname = e.Nav_EditColumn.LABEL;
                            var desc = "";
                            hasEnums.Add(e.Nav_EditColumn.ENUM);
                            foreach (var x in Enum.GetNames(enumType))
                            {
                                var value = (int)Enum.Parse(enumType, x.ToString());

                                desc += $"{x}:{value},";
                            }
                            desc = desc.TrimEnd(',');
                            enumObj.enumdesc = desc;
                            data.Add(enumObj);
                        }
                    }
                    //
                    infoDetail.Data = data;
                }
                configDetails.Add(infoDetail);
            }



            dynamic retObj = new System.Dynamic.ExpandoObject();
            retObj.Name = importConfig.NAME;
            retObj.ImportTable = configDetails;
            return retObj;
        }

        private void ImportData(Guid orgid, T_FM_IMPORT_CONFIG_DETAIL c,
            T_PF_PAGE_EDIT table, List<T_FM_IMPORT_CONFIG_DETAIL> Details, ImportTableModel tableModel, bool isData)
        {
            if (table != null)
            {
                var tableName = table.EDIT_NAME;
                var fileds = c.Nav_Fields.Select(i => i.DEST_FIELD_NAME).ToArray();
                BasePageFilter filter = new BasePageFilter();
                filter.OrgId = orgid;
                filter.Limit = 10;
                filter.PageIndex = 1;
                filter.Sort = "ID";
                filter.Order = DbOrder.ASC;
                //filter.SelectField = fileds;
                T_FM_IMPORT_CONFIG_FIELD addKeyField = null;
                T_FM_IMPORT_CONFIG_DETAIL parent = null;
                string relationField = "";
                Dictionary<Guid, object> parentPairs = new Dictionary<Guid, object>();
                var filterRuleList = new List<FilterRule>();
                var filterGroup = new FilterGroup();
                filterGroup.IsAnd = false;
                filter.FilterGroup.Groups.Add(filterGroup);
                foreach (var filed in fileds)
                {
                    if (filed.IndexOf(".") > 0)
                    {
                        var indexPos = filed.LastIndexOf(".");
                        var navfield = filed.Substring(0, indexPos);
                        if (!filter.Include.Contains(navfield))
                            filter.Include.Add(navfield);
                    }
                }
                Type typeName = DataHelper.GetTypeByEntityName(tableName);
                //filter.Include.Clear();
                if (typeName == null)
                    this.ThrowError("020011");
                if (c.PARENT_ID != null)
                {

                    parent = Details.FirstOrDefault(x => x.ID == c.PARENT_ID);

                    var parentDataId = new List<Guid>();
                    if (parent != null)
                    {
                        var parentModel = GetTableMode(tableModel, parent.ID);
                        Type parentType = DataHelper.GetTypeByEntityName(parentModel.Nav_PageEdit.EDIT_NAME);
                        if (parentType == null)
                            this.ThrowError("020011");
                        var parentKey = parent.Nav_Fields.FirstOrDefault(i => i.SRC_FIELD_NAME ==
                    parent.SHEET_KEY_FIELD_NAME);
                        if (parentKey == null)
                        {
                            this.ThrowError("020011");
                        }
                        addKeyField = new T_FM_IMPORT_CONFIG_FIELD();
                        addKeyField.DEST_FIELD_NAME = parentKey.DEST_FIELD_NAME;
                        addKeyField.SRC_FIELD_NAME = parentKey.SRC_FIELD_NAME;
                        foreach (var d in parent.Data)
                        {
                            if (!parentDataId.Contains(d.ID))
                                parentDataId.Add(d.ID);
                            if (!parentPairs.ContainsKey(d.ID))
                                parentPairs.Add(d.ID, this.GetFieldValue(addKeyField.DEST_FIELD_NAME, d));
                        }
                    }
                    var model = GetTableMode(tableModel, c.ID);

                    if (model != null)
                    {
                        relationField = model.Nav_PageEdit.RELATION_FIELD;
                        if (parentDataId.Any())
                        {

                            foreach (var i in parentDataId)
                            {
                                var fiterRule = new FilterRule();
                                fiterRule.Field = relationField;
                                fiterRule.Operate = FilterOperate.Equal;
                                fiterRule.Value = i;
                                filterRuleList.Add(fiterRule);
                            }

                        }
                    }
                }
                dynamic tmpResult = new System.Dynamic.ExpandoObject();
                MethodInfo methodInfo = null;
                if (!isData)
                {
                    methodInfo = this.GetType().GetMethod("GetEntityByInvoke", new Type[] { typeof(BasePageFilter) });
                }
                else
                {
                    methodInfo = this.GetType().GetMethod("GetEntitiesByInvoke", new Type[] { typeof(BasePageFilter) });
                }


                if (filterRuleList.Any())
                {
                    var limit = 1000;
                    List<dynamic> tmpTotal = new List<dynamic>();
                    for (var x = 0; x < filterRuleList.Count; x = x + limit)
                    {
                        filterGroup.Rules.Clear();
                        var pageRules = filterRuleList.Skip(x).Take(limit).ToArray();
                        for (var j = 0; j < pageRules.Count(); j++)
                        {
                            filterGroup.Rules.Add(pageRules[j]);
                        }
                        dynamic tmp = methodInfo.MakeGenericMethod(new Type[] { typeName }).Invoke(this, new object[] { filter });
                        foreach (var row in tmp)
                            tmpTotal.Add(row);
                    }
                    tmpResult = tmpTotal;
                }
                else
                {
                    tmpResult = methodInfo.MakeGenericMethod(new Type[] { typeName }).Invoke(this, new object[] { filter });
                }

                if (c.PARENT_ID != null && addKeyField != null)
                {
                    addKeyField.DEST_FIELD_NAME = c.PARENT_ID + "_" + addKeyField.DEST_FIELD_NAME;
                    c.Nav_Fields.Add(addKeyField);
                    List<dynamic> tmp = new List<dynamic>();
                    foreach (var row in tmpResult)
                    {
                        dynamic info = new System.Dynamic.ExpandoObject();
                        var dic = (IDictionary<string, object>)info;

                        var props = typeName.GetProperties();
                        foreach (var p in props)
                        {
                            var pValue = typeName.GetProperty(p.Name).GetValue(row);
                            if (!dic.ContainsKey(p.Name))
                                dic.Add(p.Name, pValue);
                            if (p.Name == relationField)
                            {
                                if (!dic.ContainsKey(addKeyField.DEST_FIELD_NAME))
                                {
                                    dic.Add(addKeyField.DEST_FIELD_NAME, parentPairs[pValue]);
                                }

                            }
                        }
                        tmp.Add(info);
                    }
                    tmpResult = tmp;

                }

                c.Data = tmpResult;
            }
        }

        private ImportTableModel GetTableMode(ImportTableModel model, Guid configDetailId)
        {
            if (model != null)
            {
                if (model.Nav_ConfigDetail.ID == configDetailId)
                {
                    return model;
                }
                else
                {
                    var childModels = model.Nav_SubTables;
                    if (childModels != null && childModels.Any())
                    {
                        foreach (var c in childModels)
                        {
                            var subModel = GetTableMode(c, configDetailId);
                            if (subModel != null)
                                return subModel;
                        }
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 获取导入配置信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="configCode"></param>
        /// <returns></returns>
        public ImportConfigModel GetImportConfig(Guid orgId, string configCode)
        {
            ImportConfigModel config = new ImportConfigModel();
            var importConfig = this.GetEntity<T_FM_IMPORT_CONFIG>(t => t.CODE == configCode, new BaseFilter(orgId));
            if (importConfig == null)
                throw new Exception("无效导入配置");
            if (!string.IsNullOrEmpty(importConfig.EDIT_FORM_CODE))
                config.Nav_EditForm = this.GetEntity<T_PF_FORM>(t => t.CODE == importConfig.EDIT_FORM_CODE, new BaseFilter(importConfig.ORG_ID));
            config.Nav_ImportConfig = importConfig;
            config.Nav_ImportTable = this.GetImportColumns(importConfig);
            return config;
        }

        #region  私有函数
        /// <summary>
        /// 获取导入列信息
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="configCode"></param>
        /// <returns></returns>
        private ImportTableModel GetImportColumns(T_FM_IMPORT_CONFIG importConfig)
        {

            if (string.IsNullOrEmpty(importConfig.TABLE_NAME))
                throw new Exception("未配置表名");


            var configDetails = this.GetEntities<T_FM_IMPORT_CONFIG_DETAIL>(t => t.IMPORT_CONFIG_ID == importConfig.ID, new BaseFilter(importConfig.ORG_ID), new string[] { "Nav_Fields" }).ToList();
            if (configDetails == null || !configDetails.Any())
                throw new Exception("未配置明细信息");

            List<T_PF_PAGE_EDIT> pageEdits = null;
            if (!string.IsNullOrEmpty(importConfig.EDIT_FORM_CODE))
                pageEdits = this.GetEntities<T_PF_PAGE_EDIT>(t => t.Nav_PageForm.CODE == importConfig.EDIT_FORM_CODE,
                        new BaseFilter(importConfig.ORG_ID), new string[] { "Nav_Columns" }).ToList();

            //获取主表配置信息
            var firstConfigDetail = configDetails.FirstOrDefault(t => t.PARENT_ID == null);
            if (firstConfigDetail == null)
                throw new Exception("未配置主表信息");

            var table = DoGetImportTable(firstConfigDetail, null, pageEdits);
            if (table != null)
            {
                //获取从表配置信息
                GetImportTable(firstConfigDetail.ID, table, configDetails, pageEdits);
            }
            return table;
        }

        private void GetEnumColums(ImportTableModel editConfigs, List<ImportTableColumnModel> enums)
        {
            if (editConfigs != null)
            {
                var cols = editConfigs.Nav_Columns.Where(i => !string.IsNullOrEmpty(i.Nav_EditColumn.ENUM)).ToList();
                if (cols.Any())
                {
                    enums.AddRange(cols);
                }
                if (editConfigs.Nav_SubTables != null && editConfigs.Nav_SubTables.Any())
                {
                    foreach (var table in editConfigs.Nav_SubTables)
                    {
                        GetEnumColums(table, enums);
                    }
                }
            }

        }


        /// <summary>
        /// 获取反射调用参数
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="parentParam"></param>
        /// <param name="configDetails"></param>
        /// <param name="dataTables"></param>
        /// <param name="pageEdits"></param>
        private void GetImportInvokeParam(Guid? parentId, ImportInvokeParamModel parentParam,
                List<T_FM_IMPORT_CONFIG_DETAIL> configDetails, DataSet dataTables, List<T_PF_PAGE_EDIT> pageEdits,
                Dictionary<string, Type> existTypes, ImportDataModel importDataModel)
        {
            if (configDetails == null) return;
            var list = configDetails.Where(t => t.PARENT_ID == parentId).ToList();
            if (list == null || !list.Any()) return;
            list.ForEach(t =>
            {
                var param = DoGetImportInvokeParam(t, parentParam, dataTables, pageEdits, existTypes, importDataModel);
                if (param != null)
                {
                    if (parentParam != null)
                        parentParam.Nav_ChildConfigDetails.Add(param);
                    GetImportInvokeParam(t.ID, param, configDetails, dataTables, pageEdits, existTypes, importDataModel);
                }
            });
        }
        /// <summary>
        /// 实际获取反射调用参数
        /// </summary>
        /// <param name="configDetail"></param>
        /// <param name="parentParam"></param>
        /// <param name="dataTables"></param>
        /// <param name="pageEdits"></param>
        /// <returns></returns>
        private ImportInvokeParamModel DoGetImportInvokeParam(T_FM_IMPORT_CONFIG_DETAIL configDetail, ImportInvokeParamModel parentParam, DataSet dataTables,
            List<T_PF_PAGE_EDIT> pageEdits, Dictionary<string, Type> existTypes, ImportDataModel importDataModel)
        {
            ImportInvokeParamModel param = new ImportInvokeParamModel();
            param.Nav_ConfigDetail = configDetail;
            param.ExistTypes = existTypes;
            param.ImportDataModel = importDataModel;
            if (dataTables.Tables.Count > configDetail.SHEET_INDEX)
                param.Nav_DataTable = dataTables.Tables[configDetail.SHEET_INDEX];

            if (configDetail != null && configDetail.Nav_Fields != null && configDetail.Nav_Fields.Any())
            {
                foreach (var f in configDetail.Nav_Fields)
                {
                    ImportInvokeFieldModel field = new ImportInvokeFieldModel();
                    field.Nav_ConfigField = f;
                    param.Fields.Add(field);
                }
            }



            if (pageEdits != null && pageEdits.Any())
            {
                if (configDetail.PARENT_ID == null)
                    param.Nav_PageEdit = pageEdits.FirstOrDefault(t => t.PARENT_ID == null);
                else
                {
                    if (!string.IsNullOrEmpty(configDetail.PAGE_EDIT_CODE))
                    {
                        param.Nav_PageEdit = pageEdits.FirstOrDefault(t => t.CODE == configDetail.PAGE_EDIT_CODE);
                    }
                    else
                    {
                        param.Nav_PageEdit = pageEdits.FirstOrDefault(t => parentParam != null && parentParam.Nav_PageEdit != null && t.PARENT_ID == parentParam.Nav_PageEdit.ID);
                    }
                }


                //获取编辑表列中的导航字段的Include字段
                if (param.Nav_PageEdit != null && param.Nav_PageEdit.Nav_Columns != null && param.Nav_PageEdit.Nav_Columns.Any())
                {
                    foreach (var col in param.Nav_PageEdit.Nav_Columns)
                    {
                        if (string.IsNullOrEmpty(col.FIELD_NAME)) continue;

                        var invokeField = param.Fields.FirstOrDefault(t => t.Nav_ConfigField != null && t.Nav_ConfigField.DEST_FIELD_NAME == col.FIELD_NAME);
                        if (invokeField != null)
                            invokeField.Nav_EditColumn = col;

                        var fields = col.FIELD_NAME.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                        if (fields.Count > 1)
                        {
                            fields.RemoveAt(fields.Count - 1);
                            string tmp = string.Join(".", fields);
                            if (!param.PageEditTableIncludes.ContainsKey(tmp))
                                param.PageEditTableIncludes.Add(tmp, 0);
                            if (fields.Count > 1)
                            {
                                string first = fields[0];
                                fields.RemoveAt(0);
                                string includeField = string.Join(".", fields);
                                Dictionary<string, byte> includes = null;
                                if (!param.PageEditColumnNavIncludes.TryGetValue(first, out includes))
                                {
                                    includes = new Dictionary<string, byte>();
                                    param.PageEditColumnNavIncludes.Add(first, includes);
                                }
                                if (!includes.ContainsKey(includeField))
                                    includes.Add(includeField, 0);
                            }
                        }
                    }
                }
            }
            return param;
        }

        /// <summary>
        /// 获取导入显示表信息
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="parentTable"></param>
        /// <param name="configDetails"></param>
        /// <param name="pageEdits"></param>
        private void GetImportTable(Guid? parentId, ImportTableModel parentTable,
                List<T_FM_IMPORT_CONFIG_DETAIL> configDetails, List<T_PF_PAGE_EDIT> pageEdits)
        {
            if (configDetails == null) return;
            var list = configDetails.Where(t => t.PARENT_ID == parentId).ToList();
            if (list == null || !list.Any()) return;
            list.ForEach(t =>
            {
                var table = DoGetImportTable(t, parentTable, pageEdits);
                if (table != null)
                {
                    if (parentTable != null)
                        parentTable.Nav_SubTables.Add(table);
                    GetImportTable(t.ID, table, configDetails, pageEdits);
                }
            });
        }


        /// <summary>
        /// 实际获取导入显示表信息
        /// </summary>
        /// <param name="configDetail"></param>
        /// <param name="parentTable"></param>
        /// <param name="pageEdits"></param>
        /// <returns></returns>

        private ImportTableModel DoGetImportTable(T_FM_IMPORT_CONFIG_DETAIL configDetail, ImportTableModel parentTable, List<T_PF_PAGE_EDIT> pageEdits)
        {
            ImportTableModel table = new ImportTableModel();
            table.Nav_ConfigDetail = configDetail;
            if (pageEdits != null && pageEdits.Any())
            {
                if (configDetail.PARENT_ID == null)
                    table.Nav_PageEdit = pageEdits.FirstOrDefault(t => t.PARENT_ID == null);
                else
                {
                    if (!string.IsNullOrEmpty(configDetail.PAGE_EDIT_CODE))
                    {
                        table.Nav_PageEdit = pageEdits.FirstOrDefault(t => !string.IsNullOrEmpty(configDetail.PAGE_EDIT_CODE) && t.CODE == configDetail.PAGE_EDIT_CODE);
                    }
                    else
                    {
                        table.Nav_PageEdit = pageEdits.FirstOrDefault(t => parentTable != null && parentTable.Nav_PageEdit != null && t.PARENT_ID == parentTable.Nav_PageEdit.ID);
                    }

                }
                if (table.Nav_PageEdit != null)
                {
                    table.NavProperty = table.Nav_PageEdit.NAV_PROPERTY;
                    if (table.Nav_PageEdit.Nav_Columns != null && table.Nav_PageEdit.Nav_Columns.Any())
                    {
                        var list = table.Nav_PageEdit.Nav_Columns.OrderBy(t => t.NUM).ToList();
                        list.ForEach(t1 =>
                        {
                            ImportTableColumnModel col = new ImportTableColumnModel();
                            col.Nav_EditColumn = t1;
                            col.Label = t1.LABEL;
                            col.FieldName = t1.FIELD_NAME;
                            table.Nav_Columns.Add(col);
                        });
                    }
                }

            }
            return table;
        }

        private Type GetTypeByEntityName(string entityName, Dictionary<string, Type> existTypes)
        {
            Type type = null;
            if (existTypes == null || !existTypes.TryGetValue(entityName, out type))
            {
                type = DataHelper.GetTypeByEntityName(entityName);
                if (existTypes != null)
                    existTypes.Add(entityName, type);
            }
            return type;
        }

        enum ImportMessageTypeEnum
        {
            /// <summary>信息</summary>
            Info = 0,
            /// <summary>警告</summary>
            Warning = 1,
            /// <summary>错误</summary>
            Error = 2,
        }

        private void AddMessage(ImportInvokeParamModel param, ImportMessageTypeEnum messageType, string message)
        {
            if (param.ImportDataModel != null && param.ImportDataModel.MessageList != null)
            {
                string messageTypeStr = string.Empty;
                switch (messageType)
                {
                    case ImportMessageTypeEnum.Error:
                        messageTypeStr = "【错误】：";
                        break;
                    case ImportMessageTypeEnum.Info:
                        messageTypeStr = "【信息】：";
                        break;
                    case ImportMessageTypeEnum.Warning:
                        messageTypeStr = "【警告】：";
                        break;
                }
                param.ImportDataModel.MessageList.Add(messageTypeStr + message);
            }
        }
        /// <summary>
        /// 根据行项获取字段值
        /// </summary>
        /// <param name="param"></param>
        /// <param name="row"></param>
        /// <param name="invokeField"></param>
        /// <param name="table"></param>
        /// <param name="entityType"></param>
        /// <param name="srcValue"></param>
        /// <returns></returns>
        private object GetFieldValueByRow(ImportInvokeParamModel param, DataRow row, ImportInvokeFieldModel invokeField,
                DataTable table, Type entityType, out string srcValue)
        {
            srcValue = string.Empty;
            var field = invokeField.Nav_ConfigField;
            if (field == null) return null;

            T_FM_IMPORT_CONFIG_DETAIL configDetail = param.Nav_ConfigDetail;
            if (field.SRC_FEILD_TYPE == (int)FMImportConfigSrcFieldTypeEnum.字段 || field.SRC_FEILD_TYPE == (int)FMImportConfigSrcFieldTypeEnum.ID字段)
            {
                if (string.IsNullOrEmpty(field.SRC_FIELD_NAME)) return null;
                DataColumn col = table.Columns[field.SRC_FIELD_NAME];
                if (col == null)
                    return null;
                srcValue = LibUtils.ToString(row[col]);
            }
            else if (field.SRC_FEILD_TYPE == (int)FMImportConfigSrcFieldTypeEnum.固定值)
            {
                srcValue = field.SRC_FIELD_NAME;
            }
            if (!string.IsNullOrEmpty(srcValue))
                srcValue = srcValue.Trim();
            if (string.IsNullOrEmpty(srcValue)) return null;

            string destFieldName = field.DEST_FIELD_NAME;//目的字段

            if (field.SRC_FEILD_TYPE == (int)FMImportConfigSrcFieldTypeEnum.ID字段)
            {
                if (string.IsNullOrEmpty(field.ID_TABLE_NAME) || string.IsNullOrEmpty(field.ID_TABLE_FIELD_NAME)) return null;
                if (destFieldName.IndexOf(".", StringComparison.OrdinalIgnoreCase) == -1)//字段中不存在.
                {
                    BaseFilter filter = new BaseFilter(configDetail.ORG_ID);
                    filter.FilterGroup.Rules.Add(new FilterRule(field.ID_TABLE_FIELD_NAME, srcValue, FilterOperate.Equal));
                    var type = this.GetTypeByEntityName(field.ID_TABLE_NAME, param.ExistTypes);
                    if (type != null)
                    {
                        MethodInfo methodInfo = this.GetType().GetMethod("GetEntityByInvoke", BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                        var tmpEntity = methodInfo.MakeGenericMethod(new Type[] { type }).
                                    Invoke(this, new object[] { filter });
                        if (tmpEntity != null)
                        {
                            var entityBase = tmpEntity as EntityBase<Guid>;
                            if (entityBase != null) return entityBase.ID;
                        }
                    }
                }
            }
            else
            {
                var splitDestFieldName = destFieldName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (splitDestFieldName != null && splitDestFieldName.Any())
                {
                    string firstField = splitDestFieldName[0];
                    var des = entityType.GetProperty(firstField);
                    if (des == null) return null;
                    if (splitDestFieldName.Count == 1)
                    {
                        #region 属性
                        string propertyTypeName = des.PropertyType.Name;
                        string fullTypeName = des.PropertyType.FullName;
                        if (string.Compare(propertyTypeName, "GUID", true) == 0 || fullTypeName.IndexOf("Guid", StringComparison.OrdinalIgnoreCase) > -1)
                            return LibUtils.ToGuid(srcValue);
                        else if (string.Compare(propertyTypeName, "DateTime", true) == 0 || fullTypeName.IndexOf("DateTime", StringComparison.OrdinalIgnoreCase) > -1)
                            return LibUtils.ToDateTime(srcValue);
                        else if (string.Compare(propertyTypeName, "bool", true) == 0 || string.Compare(propertyTypeName, "boolean", true) == 0 || fullTypeName.IndexOf("bool", StringComparison.OrdinalIgnoreCase) > -1)
                            return LibUtils.ToBoolean(srcValue);
                        else if (string.Compare(propertyTypeName, "int", true) == 0 || fullTypeName.IndexOf("int", StringComparison.OrdinalIgnoreCase) > -1 || des.PropertyType.IsEnum)
                        {
                            int r = LibUtils.ToInt(srcValue);

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

                            string enumName = string.Empty;

                            //下拉选择
                            //if (invokeField.Nav_EditColumn != null
                            //        && !string.IsNullOrEmpty(invokeField.Nav_EditColumn.ENUM))
                            //    enumName = invokeField.Nav_EditColumn.ENUM;
                            //else if (r == 0 && enumNameAttr != null
                            //        && !string.IsNullOrEmpty(enumNameAttr.EnumName))
                            //    enumName = enumNameAttr.EnumName;

                            //if (!string.IsNullOrEmpty(enumName))
                            //{
                            //    var enumType = DataHelper.EnumToType(enumName);
                            //    if (enumType != null && enumType.IsEnum)
                            //    {
                            //        foreach (var x in Enum.GetValues(enumType))
                            //        {
                            //            if (string.Compare(x.ToString(), srcValue, true) == 0)
                            //            {
                            //                r = (int)x;
                            //                break;
                            //            }
                            //        }
                            //    }
                            //}

                            return r;
                        }
                        else if (string.Compare(propertyTypeName, "decimal", true) == 0 || fullTypeName.IndexOf("decimal", StringComparison.OrdinalIgnoreCase) > -1)
                            return LibUtils.ToDecimal(srcValue);
                        else
                            return srcValue;
                        #endregion
                    }
                    else
                    {


                        #region 导航属性
                        if (string.IsNullOrEmpty(srcValue))
                            return null;
                        splitDestFieldName.RemoveAt(0);
                        BaseFilter filter = new BaseFilter(configDetail.ORG_ID);
                        string ruleField = string.Join(".", splitDestFieldName);
                        var typeKey = des.PropertyType?.Name + "&&" + ruleField + "==" + srcValue;
                        if (NavcationList.ContainsKey(typeKey))
                        {
                            return NavcationList[typeKey];
                        }
                        filter.FilterGroup.Rules.Add(new FilterRule(ruleField, srcValue, FilterOperate.Equal));
                        Dictionary<string, byte> includes = null;
                        if (param.PageEditColumnNavIncludes != null && param.PageEditColumnNavIncludes.TryGetValue(firstField, out includes))
                        {
                            foreach (var item in includes)
                                filter.Include.Add(item.Key);
                        }
                        try
                        {
                            MethodInfo methodInfo = this.GetType().GetMethod("GetEntityByInvoke", new Type[] { typeof(BaseFilter) });
                            var tmpEntity = methodInfo.MakeGenericMethod(new Type[] { des.PropertyType }).Invoke(this, new object[] { filter });
                            if (tmpEntity != null)
                            {
                                if (!NavcationList.ContainsKey(typeKey))
                                    NavcationList.Add(typeKey, tmpEntity);
                                return tmpEntity;

                            }

                            else
                            {
                                string errorLine = des.PropertyType.Name;
                                this.ThrowError("010001", errorLine + " 列 "+ srcValue + " 不存在");
                            }
                               
                        }
                        catch (TargetInvocationException ex)
                        {
                            this.ThrowError("010001", ex.Message);
                        }

                        #endregion
                    }
                }
            }
            return null;
        }

        private string GetFieldValue(string fieldName, object o)
        {
            //var tmpType = d;
            var tmpO = o;
            var tmpFieldName = fieldName;
            if (fieldName.IndexOf(".") < 0)
            {
                var obj = o.GetType().GetProperty(fieldName).GetValue(tmpO);
                if (obj == null)
                {
                    return "";
                }
                return obj.ToString();
            }
            else
            {
                var indexPos = fieldName.IndexOf(".");
                tmpFieldName = tmpFieldName.Substring(0, indexPos);
                var subName = fieldName.Substring(indexPos + 1);
                var prop = o.GetType().GetProperty(tmpFieldName);
                if (prop != null)
                {
                    var objVal = prop.GetValue(o);
                    if (objVal == null)
                    {
                        return "";
                        //this.ThrowError("010001", "字段：" + prop.Name + "对应数据不存在," + Newtonsoft.Json.JsonConvert.SerializeObject(o));
                    }
                    return GetFieldValue(subName, objVal);
                }
            }
            return "";


        }

        #endregion

        #region 用于反射
        public T GetEntityByInvoke<T>(BaseFilter filter) where T : MesEntityBase, new()
        {
            return this.GetEntity<T>(null, filter);
        }

        public List<T> GetEntityByInvoke<T>(BasePageFilter filter) where T : MesEntityBase, new()
        {

            return this.GetOrderPageEntities<T>(null, filter).Items.ToList();
        }

        public List<T> GetEntitiesByInvoke<T>(BasePageFilter filter) where T : MesEntityBase, new()
        {
            return this.GetEntities<T>(null, filter).ToList();
        }

        /// <summary>
        /// 根据数据表获取实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<T> DoGetEntityByTable<T>(ImportInvokeParamModel param) where T : MesEntityBase, new()
        {
            NavcationList.Clear();
            if (param == null) return null;
            T_FM_IMPORT_CONFIG_DETAIL configDetail = param.Nav_ConfigDetail;
            var codeRuleService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IPFCodeRuleService>();
            if (configDetail == null) return null;

            DataTable table = param.Nav_DataTable;
            if (table == null)
            {
                //this.AddMessage(param, ImportMessageTypeEnum.Warning, string.Format("未获取到表{0}对应数据", configDetail.DESCRIPTION));
                this.ThrowError("020022", configDetail.DESCRIPTION);
                return null;
            }


            try
            {
                List<T> result = new List<T>();
                List<T> addResult = new List<T>();
                List<T> updateResult = new List<T>();
                Type entityType = typeof(T);

                BaseFilter filter = new BaseFilter(param.Nav_PageEdit.ORG_ID);
                var group = new FilterGroup();
                group.IsAnd = false;
                filter.FilterGroup.Groups.Add(group);
                filter.IgnoreDataRule = true;
                List<T> dbData = new List<T>();
                Dictionary<string, Guid> keyValuePairs = new Dictionary<string, Guid>();
                ImportInvokeFieldModel keyFieldModel = null;
                //ImportInvokeFieldModel parentKeyModel = null;
                var keyFieldSrcVal = "";
                //构造查询条件
                var ruleList = new List<FilterRule>();
                foreach (DataRow row in table.Rows)
                {
                    var list = !param.IsParentAdd && param.Fields != null && param.Fields.Any() ?
                            param.Fields.Where(t1 => t1.Nav_ConfigField != null).ToList() : null;
                    if (list != null && list.Any())
                    {

                        //BaseFilter filter = new BaseFilter(configDetail.ORG_ID);
                        if (!string.IsNullOrEmpty(configDetail.SHEET_KEY_FIELD_NAME))
                        {
                            keyFieldModel = list.FirstOrDefault(i => i.Nav_ConfigField.SRC_FIELD_NAME == configDetail.SHEET_KEY_FIELD_NAME);
                            if (keyFieldModel == null)
                                this.ThrowError("020012", configDetail.SHEET_KEY_FIELD_NAME);

                            var fieldValue = this.GetFieldValueByRow(param, row, keyFieldModel, table, entityType, out keyFieldSrcVal);
                            if (fieldValue != null)
                            {
                                ruleList.Add(new FilterRule(keyFieldModel.Nav_ConfigField.DEST_FIELD_NAME, keyFieldSrcVal.Trim(), FilterOperate.Equal));
                            }

                        }
                        //foreach (var invokeField in list)
                        //{
                        //    var field = invokeField.Nav_ConfigField;
                        //    if (field == null) continue;
                        //    string destFieldName = field.DEST_FIELD_NAME;//目的字段
                        //    if (string.IsNullOrEmpty(destFieldName)) continue;
                        //    if (invokeField.Nav_ConfigField.SRC_FIELD_NAME == configDetail.SHEET_KEY_FIELD_NAME)
                        //    {
                        //        string srcValue = string.Empty;
                        //        var fieldValue = this.GetFieldValueByRow(param, row, invokeField, table, entityType, out srcValue);
                        //        if (fieldValue != null)
                        //            group.Rules.Add(new FilterRule(destFieldName, srcValue.Trim(), FilterOperate.Equal));
                        //        break;
                        //    }
                        //    //}
                        //    //else if (!string.IsNullOrEmpty(srcValue))
                        //    //    filter.FilterGroup.Rules.Add(new FilterRule(destFieldName, srcValue, FilterOperate.Equal));
                        //}

                        //从表关联主表字段
                        if (param.Nav_PageEdit != null && !string.IsNullOrEmpty(param.Nav_PageEdit.RELATION_FIELD))
                        {
                            //parentKeyModel=  list.FirstOrDefault(i => i.Nav_ConfigField.SRC_FIELD_NAME == param.KeyField);
                            var col = row[param.KeyField];
                            if (col == null)
                            {
                                this.ThrowError("020013", param.Nav_ConfigDetail.DESCRIPTION, param.KeyField);
                            }
                            //var fieldSrc = "";
                            //var fieldValue = this.GetFieldValueByRow(param, row, parentKeyModel, table, entityType, out fieldSrc);
                            var fieldValue = LibUtils.ToString(row[param.KeyField]);
                            if (param.KeyPairDic.Any() && param.KeyPairDic.ContainsKey(fieldValue))
                            {
                                filter.FilterGroup.Rules.Add(new FilterRule(param.Nav_PageEdit.RELATION_FIELD, param.KeyPairDic[fieldValue], FilterOperate.Equal));
                            }
                            else
                            {
                                this.ThrowError("020014", param.Nav_ConfigDetail.DESCRIPTION, param.KeyField, fieldValue);
                            }
                        }
                        //添加导航
                        if (param.PageEditTableIncludes != null && param.PageEditTableIncludes.Any())
                        {
                            foreach (var k in param.PageEditTableIncludes)
                                if (!filter.Include.Contains(k.Key))
                                    filter.Include.Add(k.Key);
                        }

                    }

                }
                var limit = 1000;
                for (var x = 0; x < ruleList.Count; x = x + limit)
                {
                    var pageRule = ruleList.Skip(x).Take(limit).ToArray();
                    group.Rules.Clear();
                    for (var j = 0; j < pageRule.Count(); j++)
                    {
                        group.Rules.Add(pageRule[j]);
                    }
                    var pageData = this.GetEntities<T>(null, filter).ToList();
                    dbData.AddRange(pageData);
                }
                //dbData = this.GetEntities<T>(null, filter).ToList();
                //字段赋值 
                bool isParentSet = false;
                foreach (DataRow row in table.Rows)
                {
                    var keyFieldValue = "";
                    //主从表关系判断
                    //if (!string.IsNullOrEmpty(configDetail.SHEET_KEY_FIELD_NAME) && !string.IsNullOrEmpty(param.KeyValue))
                    //{
                    //    DataColumn col = table.Columns[configDetail.SHEET_KEY_FIELD_NAME];
                    //    string curKeyValue = col == null ? string.Empty : LibUtils.ToString(row[col]);
                    //    if (string.IsNullOrEmpty(curKeyValue) || string.Compare(curKeyValue, param.KeyValue, true) != 0) continue;
                    //}

                    bool isEntityAdd = false;

                    //获取已有数据
                    T t = null;

                    if (dbData.Any())
                    {
                        if (keyFieldModel != null)
                        {
                            string curKeyValue = LibUtils.ToString(row[configDetail.SHEET_KEY_FIELD_NAME]);
                            foreach (var d in dbData)
                            {
                                var dataFieldValue = this.GetFieldValue(keyFieldModel.Nav_ConfigField.DEST_FIELD_NAME, d);
                                if (dataFieldValue.Trim() == curKeyValue.Trim())
                                {
                                    t = d;
                                    break;
                                }
                            }
                        }
                    }
                    //不存在已有记录
                    if (t == null)
                    {
                        isEntityAdd = true;
                        t = new T();
                        addResult.Add(t);
                        Type type2 = t.GetType();
                        var orgPropoerty = type2.GetProperty("ORG_ID");
                        if (orgPropoerty != null)
                            orgPropoerty.SetValue(t, configDetail.ORG_ID, null);
                        if (param.Nav_PageEdit != null && !string.IsNullOrEmpty(param.Nav_PageEdit.RELATION_FIELD))
                        {
                            var des = type2.GetProperty(param.Nav_PageEdit.RELATION_FIELD);
                            if (des != null)
                            {
                                var col = row[param.KeyField];
                                if (col == null)
                                {
                                    this.ThrowError("020013", param.Nav_ConfigDetail.DESCRIPTION, param.KeyField);
                                }
                                var fieldValue = LibUtils.ToString(row[param.KeyField]);
                                if (param.KeyPairDic.Any() && param.KeyPairDic.ContainsKey(fieldValue))
                                {
                                    des.SetValue(t, param.KeyPairDic[fieldValue], null);
                                }
                                else
                                {
                                    this.ThrowError("020014", param.Nav_ConfigDetail.DESCRIPTION, param.KeyField, fieldValue);
                                }
                            }

                        }

                        if (param.Nav_PageEdit != null && !string.IsNullOrEmpty(param.Nav_PageEdit.CODE_FIELD_NAME) &&
                            param.Nav_PageEdit.CODE_RULE_TYPE.HasValue && param.Nav_PageEdit.CODE_RULE_TYPE != 0)
                        {
                            var des = entityType.GetProperty(param.Nav_PageEdit.CODE_FIELD_NAME);
                            if (des != null)
                            {
                                SystemCodeFilter codeFilter = new SystemCodeFilter();
                                codeFilter.CodeType = param.Nav_PageEdit.CODE_RULE_TYPE.Value;
                                codeFilter.Count = 1;
                                codeFilter.OrgId = configDetail.ORG_ID;
                                var c = codeRuleService.NewGenSerial(codeFilter);
                                des.SetValue(t, c, null);
                            }
                        }

                        if (param.Nav_PageEdit != null && param.Nav_PageEdit.Nav_Columns != null && param.Nav_PageEdit.Nav_Columns.Any())
                        {
                            foreach (var editCol in param.Nav_PageEdit.Nav_Columns)
                            {
                                if (editCol.CONTROL_TYPE == (int)PFControlTypeEnum.系统序列号控件 &&
                                    editCol.CODE_RULE_TYPE.HasValue && editCol.CODE_RULE_TYPE != 0)
                                {
                                    var des1 = entityType.GetProperty(editCol.FIELD_NAME);
                                    if (des1 != null)
                                    {
                                        SystemCodeFilter codeFilter = new SystemCodeFilter();
                                        codeFilter.CodeType = editCol.CODE_RULE_TYPE.Value;
                                        codeFilter.Count = 1;
                                        codeFilter.OrgId = configDetail.ORG_ID;
                                        var c = codeRuleService.NewGenSerial(codeFilter);
                                        des1.SetValue(t, c, null);
                                    }
                                }
                                if (string.IsNullOrEmpty(editCol.FIELD_NAME) ||
                                    editCol.FIELD_NAME.IndexOf(".", StringComparison.OrdinalIgnoreCase) > -1 ||
                                    string.IsNullOrEmpty(editCol.DEFAULT_VALUE)) continue;
                                var des = entityType.GetProperty(editCol.FIELD_NAME);
                                if (des == null) return null;
                                string propertyTypeName = des.PropertyType.Name;
                                string fullTypeName = des.PropertyType.FullName;
                                object obj = null;
                                if (string.Compare(propertyTypeName, "GUID", true) == 0 || fullTypeName.IndexOf("Guid", StringComparison.OrdinalIgnoreCase) > -1)
                                    obj = LibUtils.ToGuid(editCol.DEFAULT_VALUE);
                                else if (string.Compare(propertyTypeName, "DateTime", true) == 0 || fullTypeName.IndexOf("DateTime", StringComparison.OrdinalIgnoreCase) > -1)
                                {
                                    if (editCol.DEFAULT_VALUE.StartsWith("@nowDate"))
                                        obj = DateTime.Now.Date;
                                    else if (editCol.DEFAULT_VALUE.StartsWith("@now"))
                                        obj = DateTime.Now;
                                    else
                                        obj = LibUtils.ToDateTime(editCol.DEFAULT_VALUE);
                                }
                                else if (string.Compare(propertyTypeName, "bool", true) == 0 || string.Compare(propertyTypeName, "boolean", true) == 0 || fullTypeName.IndexOf("bool", StringComparison.OrdinalIgnoreCase) > -1)
                                    obj = LibUtils.ToBoolean(editCol.DEFAULT_VALUE);
                                else if (string.Compare(propertyTypeName, "int", true) == 0 || fullTypeName.IndexOf("int", StringComparison.OrdinalIgnoreCase) > -1)
                                {
                                    int r = LibUtils.ToInt(editCol.DEFAULT_VALUE);
                                    //下拉选择
                                    //if (!string.IsNullOrEmpty(editCol.ENUM))
                                    //{
                                    //    var enumType = DataHelper.EnumToType(editCol.ENUM);
                                    //    if (enumType != null && enumType.IsEnum)
                                    //    {
                                    //        foreach (var x in Enum.GetValues(enumType))
                                    //        {
                                    //            if (string.Compare(x.ToString(), editCol.DEFAULT_VALUE, true) == 0)
                                    //                r = (int)x;
                                    //        }
                                    //    }
                                    //}
                                    obj = r;
                                }
                                else if (string.Compare(propertyTypeName, "decimal", true) == 0 || fullTypeName.IndexOf("decimal", StringComparison.OrdinalIgnoreCase) > -1)
                                    obj = LibUtils.ToDecimal(editCol.DEFAULT_VALUE);
                                else if (!editCol.DEFAULT_VALUE.StartsWith("@"))
                                    obj = editCol.DEFAULT_VALUE;
                                if (obj != null)
                                    des.SetValue(t, obj, null);
                            }
                        }
                    }
                    else
                    {
                        updateResult.Add(t);
                    }
                    if (param.Fields != null && param.Fields.Any())
                    {
                        foreach (var invokeField in param.Fields)
                        {
                            var field = invokeField.Nav_ConfigField;
                            if (field == null) continue;
                            //父节点字段先不赋值
                            if (field.DEST_FIELD_NAME.StartsWith("Nav_Parent") && !param.IsParentUpdate)
                            {
                                isParentSet = true;
                                continue;
                            }

                            string destFieldName = field.DEST_FIELD_NAME;//目的字段
                            if (string.IsNullOrEmpty(destFieldName)) continue;
                            string srcValue = string.Empty;

                            //获取字段值
                            var fieldValue = this.GetFieldValueByRow(param, row, invokeField, table, entityType, out srcValue);
                            if (field.SRC_FEILD_TYPE == (int)FMImportConfigSrcFieldTypeEnum.ID字段)
                            {
                                if (destFieldName.IndexOf(".", StringComparison.OrdinalIgnoreCase) > -1)
                                {
                                    this.AddMessage(param, ImportMessageTypeEnum.Warning,
                                            string.Format("获取表{0}时，字段{1}不允许配置导航字段{2}", configDetail.DESCRIPTION, field.LABEL, field.DEST_FIELD_NAME));
                                    continue;
                                }
                                if (fieldValue == null)
                                {
                                    this.AddMessage(param, ImportMessageTypeEnum.Warning,
                                        string.Format("获取表{0}时，字段{1}未获取到有效记录", configDetail.DESCRIPTION, field.LABEL, field.ID_TABLE_NAME));
                                    continue;
                                }
                                var des = entityType.GetProperty(destFieldName);
                                if (des == null) continue;
                                des.SetValue(t, fieldValue, null);
                            }
                            else
                            {
                                var splitDestFieldName = destFieldName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                                if (splitDestFieldName != null && splitDestFieldName.Any())
                                {
                                    string firstField = splitDestFieldName[0];
                                    var des = entityType.GetProperty(firstField);
                                    if (des == null) continue;
                                    if (splitDestFieldName.Count == 1)
                                    {
                                        if (fieldValue == null) continue;
                                        des.SetValue(t, fieldValue, null);
                                    }
                                    else
                                    {
                                        if (string.IsNullOrEmpty(field.ID_FIELD_NAME))
                                        {
                                            this.AddMessage(param, ImportMessageTypeEnum.Warning,
                                                string.Format("获取表{0}时，字段{1}未配置ID字段名称", configDetail.DESCRIPTION, field.LABEL));
                                            continue;
                                        }
                                        var idFieldNameProperty = entityType.GetProperty(field.ID_FIELD_NAME);
                                        if (idFieldNameProperty == null)
                                        {
                                            this.AddMessage(param, ImportMessageTypeEnum.Warning,
                                                string.Format("获取表{0}时，字段{1}无效ID字段名称{2}", configDetail.DESCRIPTION, field.LABEL, field.ID_FIELD_NAME));
                                            continue;
                                        }
                                        if (fieldValue == null)
                                        {
                                            if (!string.IsNullOrEmpty(srcValue))
                                            {
                                                splitDestFieldName.RemoveAt(0);
                                                string ruleField = string.Join(".", splitDestFieldName);
                                                this.AddMessage(param, ImportMessageTypeEnum.Warning,
                                                    string.Format("获取表{0}时，导航字段{1}为匹配到实体（字段{2}，值{3}）", configDetail.DESCRIPTION, field.LABEL, ruleField, srcValue));
                                            }
                                            continue;
                                        }
                                        des.SetValue(t, fieldValue, null);
                                        var entityBase = fieldValue as EntityBase<Guid>;
                                        if (entityBase != null)
                                            idFieldNameProperty.SetValue(t, entityBase.ID, null);

                                    }
                                }
                            }

                        }
                    }
                    if (keyFieldModel != null)
                    {
                        keyFieldValue = GetFieldValue(keyFieldModel.Nav_ConfigField.DEST_FIELD_NAME, t);
                        if (!string.IsNullOrEmpty(keyFieldValue) && !keyValuePairs.ContainsKey(keyFieldValue))
                            keyValuePairs.Add(keyFieldValue, t.ID);
                    }
                    result.Add(t);
                }
                if (updateResult.Any())
                {
                    var type = updateResult.FirstOrDefault().GetType();
                    var pros = type.GetProperties().Where(i => i.Name.StartsWith("Nav"));
                    foreach (var s in updateResult)
                    {
                        foreach (var pro in pros)
                        {
                            type.GetProperty(pro.Name).SetValue(s, null);
                        }
                    }
                }
                if (addResult.Any())
                {
                    var type = addResult.FirstOrDefault().GetType();
                    var pros = type.GetProperties().Where(i => i.Name.StartsWith("Nav"));
                    foreach (var s in addResult)
                    {
                        foreach (var pro in pros)
                        {
                            type.GetProperty(pro.Name).SetValue(s, null);
                        }
                    }
                }
                if (configDetail.PARENT_ID == null)//主表
                    this.AddMessage(param, ImportMessageTypeEnum.Info, string.Format("获取到数据{0}笔", result.Count));
                ///更新
                if (param.IsUpdate)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (addResult.Any())
                            this.BantchAddEntityNoCommit(addResult);
                        if (updateResult.Any())
                            if (!param.IsParentUpdate)
                                this.BantchUpdateEntityNoCommit(updateResult);
                            else
                                this.BantchSaveEntityNoCommit(updateResult);
                    });
                }
                //父节点字段处理
                if (isParentSet)
                {
                    param.IsParentUpdate = true;
                    DoGetEntityByTable<T>(param);
                }

                //子表处理


                //foreach (DataRow row in table.Rows)
                //{
                //子表赋值
                if (!string.IsNullOrEmpty(configDetail.SHEET_KEY_FIELD_NAME) && param.Nav_ChildConfigDetails != null && param.Nav_ChildConfigDetails.Any())
                {
                    DataColumn col = table.Columns[configDetail.SHEET_KEY_FIELD_NAME];
                    //string keyValue = col == null ? string.Empty : LibUtils.ToString(row[col]);
                    //if (!string.IsNullOrEmpty(keyValue))
                    //{
                    foreach (var child in param.Nav_ChildConfigDetails)
                    {
                        child.IsUpdate = param.IsUpdate;
                        if (child.Nav_PageEdit == null || string.IsNullOrEmpty(child.Nav_PageEdit.NAV_PROPERTY))
                        {
                            this.AddMessage(param, ImportMessageTypeEnum.Warning, string.Format("获取表{0}时，子表{1}未配置导航",
                                configDetail.DESCRIPTION, child.Nav_ConfigDetail == null ? "" : child.Nav_ConfigDetail.DESCRIPTION));
                            continue;
                        }

                        var navProperty = entityType.GetProperty(child.Nav_PageEdit.NAV_PROPERTY);
                        if (navProperty == null)
                        {
                            this.AddMessage(param, ImportMessageTypeEnum.Warning, string.Format("获取表{0}时，子表{1}无效导航{2}", configDetail.DESCRIPTION,
                                    child.Nav_ConfigDetail == null ? "" : child.Nav_ConfigDetail.DESCRIPTION, child.Nav_PageEdit.NAV_PROPERTY));
                            continue;
                        }
                        child.IsParentAdd = false;
                        child.KeyPairDic = keyValuePairs;
                        child.KeyField = configDetail.SHEET_KEY_FIELD_NAME;
                        //child.KeyValue = keyValue;
                        //child.ParentId = keyValuePairs[keyValue];
                        int i1 = navProperty.PropertyType.FullName.IndexOf("T_");
                        if (i1 >= 0)
                        {
                            int i2 = navProperty.PropertyType.FullName.IndexOf(",", i1 + 2);
                            if (i2 >= 0)
                            {
                                var childTable = navProperty.PropertyType.FullName.Substring(i1, i2 - i1);
                                var type = this.GetTypeByEntityName(childTable, param.ExistTypes);
                                if (type != null)
                                {
                                    try
                                    {


                                        MethodInfo methodInfo = this.GetType().GetMethod("DoGetEntityByTable", BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                                        var tmpResult = methodInfo.MakeGenericMethod(new Type[] { type }).Invoke(this, new object[] { child });
                                        //if (tmpResult != null)
                                        //    navProperty.SetValue(t, tmpResult, null);
                                    }
                                    catch (TargetInvocationException ex)
                                    {
                                        this.ThrowError("010001", ex.InnerException.Message);
                                    }
                                }
                            }
                            //}
                        }
                    }
                    //}
                }
                //刪除
                if (param.DelFlag)
                {
                    var ids = addResult.Select(i => i.ID).ToList();
                    var updateIds = updateResult.Select(i => i.ID).ToList();
                    ids.AddRange(updateIds);
                    this.DeleteEntity<T>(i => !ids.Contains(i.ID));
                }

                return result;
            }
            catch (Exception ex)
            {
                this.AddMessage(param, ImportMessageTypeEnum.Error,
                    string.Format("获取表数据{0}发生错误，详情：{1}", configDetail.DESCRIPTION,
                    ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                this.ThrowError("010001", ex.Message);
            }
            return null;
        }




        #endregion

    }
}
