using JNPF.Common.Configuration; using JNPF.Common.Const; using JNPF.Common.Core.Manager; using JNPF.Common.Core.Manager.Files; using JNPF.Common.Dtos.VisualDev; using JNPF.Common.Enums; using JNPF.Common.Extension; using JNPF.Common.Filter; using JNPF.Common.Helper; using JNPF.Common.Manager; using JNPF.Common.Models.NPOI; using JNPF.Common.Security; using JNPF.DatabaseAccessor; using JNPF.DataEncryption; using JNPF.DependencyInjection; using JNPF.DynamicApiController; using JNPF.FriendlyException; using JNPF.RemoteRequest.Extensions; using JNPF.Systems.Entitys.Model.DataInterFace; using JNPF.Systems.Entitys.Permission; using JNPF.Systems.Entitys.System; using JNPF.Systems.Interfaces.System; using JNPF.VisualDev.Engine; using JNPF.VisualDev.Engine.Core; using JNPF.VisualDev.Engine.Security; using JNPF.VisualDev.Entitys; using JNPF.VisualDev.Entitys.Dto.VisualDev; using JNPF.VisualDev.Entitys.Dto.VisualDevModelData; using JNPF.VisualDev.Interfaces; using JNPF.WorkFlow.Interfaces.Service; using Mapster; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using SqlSugar; using Yitter.IdGenerator; namespace JNPF.VisualDev { /// /// 可视化开发基础. /// [ApiDescriptionSettings(Tag = "VisualDev", Name = "OnlineDev", Order = 172)] [Route("api/visualdev/[controller]")] public class VisualDevModelDataService : IDynamicApiController, ITransient { /// /// 服务基础仓储. /// private readonly ISqlSugarRepository _visualDevRepository; // 在线开发功能实体 /// /// 可视化开发基础. /// private readonly IVisualDevService _visualDevService; /// /// 在线开发运行服务. /// private readonly RunService _runService; /// /// 单据. /// private readonly IBillRullService _billRuleService; /// /// 用户管理. /// private readonly IUserManager _userManager; /// /// 缓存管理. /// private readonly ICacheManager _cacheManager; /// /// 文件服务. /// private readonly IFileManager _fileManager; /// /// 工作流. /// private readonly IFlowTaskService _flowTaskService; /// /// 数据连接服务. /// private readonly IDbLinkService _dbLinkService; /// /// 切库. /// private readonly IDataBaseManager _databaseService; /// /// 数据接口. /// private readonly IDataInterfaceService _dataInterfaceService; /// /// 多租户事务. /// private readonly ITenant _db; /// /// 初始化一个类型的新实例. /// public VisualDevModelDataService( ISqlSugarRepository visualDevRepository, IVisualDevService visualDevService, RunService runService, IDbLinkService dbLinkService, IDataInterfaceService dataInterfaceService, IUserManager userManager, IDataBaseManager databaseService, IBillRullService billRuleService, ICacheManager cacheManager, IFlowTaskService flowTaskService, IFileManager fileManager, ISqlSugarClient context) { _visualDevRepository = visualDevRepository; _visualDevService = visualDevService; _databaseService = databaseService; _dbLinkService = dbLinkService; _runService = runService; _billRuleService = billRuleService; _userManager = userManager; _cacheManager = cacheManager; _flowTaskService = flowTaskService; _fileManager = fileManager; _dataInterfaceService = dataInterfaceService; _db = context.AsTenant(); } #region Get /// /// 获取列表表单配置JSON. /// /// 主键id. /// 1 线上版本, 0 草稿版本. /// [HttpGet("{modelId}/Config")] [NonUnify] public async Task GetData(string modelId, string type) { if (type.IsNullOrEmpty()) type = "1"; VisualDevEntity? data = await _visualDevService.GetInfoById(modelId, type.Equals("1")); if (data == null) return new { code = 400, msg = "未找到该模板!" }; if (data.EnableFlow.Equals(-1) && data.FlowId.IsNotEmptyOrNull()) return new { code = 400, msg = "该功能配置的流程已停用!" }; if (data.EnableFlow.Equals(1) && data.FlowId.IsNullOrWhiteSpace()) return new { code = 400, msg = "该流程功能未绑定流程!" }; if (data.WebType.Equals(1) && data.FormData.IsNullOrWhiteSpace()) return new { code = 400, msg = "该模板内表单内容为空,无法预览!" }; else if (data.WebType.Equals(2) && data.ColumnData.IsNullOrWhiteSpace()) return new { code = 400, msg = "该模板内列表内容为空,无法预览!" }; return new { code = 200, data = data.Adapt() }; } /// /// 获取列表配置JSON. /// /// 主键id. /// [HttpGet("{modelId}/ColumnData")] public async Task GetColumnData(string modelId) { VisualDevEntity? data = await _visualDevService.GetInfoById(modelId); return new { columnData = data.ColumnData }; } /// /// 获取列表配置JSON. /// /// 主键id. /// [HttpGet("{modelId}/FormData")] public async Task GetFormData(string modelId) { VisualDevEntity? data = await _visualDevService.GetInfoById(modelId); return new { formData = data.FormData }; } /// /// 获取列表配置JSON. /// /// 主键id. /// [HttpGet("{modelId}/FlowTemplate")] public async Task GetFlowTemplate(string modelId) { VisualDevEntity? data = await _visualDevService.GetInfoById(modelId); return new { flowTemplateJson = data.FlowTemplateJson }; } /// /// 获取数据信息. /// /// /// /// [HttpGet("{modelId}/{id}")] public async Task GetInfo(string id, string modelId) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.GetAsync != null) { return await overideSvc.OverideFuncs.GetAsync(id); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); // 模板实体 // 有表 if (!string.IsNullOrEmpty(templateEntity.Tables) && !"[]".Equals(templateEntity.Tables)) return new { id = id, data = (await _runService.GetHaveTableInfo(id, templateEntity)).ToJsonString() }; else return null; } } /// /// 获取详情. /// /// /// /// [HttpGet("{modelId}/{id}/DataChange")] public async Task GetDetails(string id, string modelId) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.GetDetailsAsync != null) { return await overideSvc.OverideFuncs.GetDetailsAsync(id); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); // 模板实体 // 有表 if (!string.IsNullOrEmpty(templateEntity.Tables) && !"[]".Equals(templateEntity.Tables)) return new { id = id, data = await _runService.GetHaveTableInfoDetails(id, templateEntity) }; else return null; } } #endregion #region Post /// /// 功能导出. /// /// /// [HttpPost("{modelId}/Actions/ExportData")] public async Task ActionsExportData(string modelId) { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId); // 模板实体 if (templateEntity.State.Equals(1)) { var vREntity = await _visualDevRepository.AsSugarClient().Queryable().FirstAsync(v => v.Id == modelId && v.DeleteMark == null); templateEntity = vREntity.Adapt(); templateEntity.State = 0; } string? jsonStr = templateEntity.ToJsonString(); return await _fileManager.Export(jsonStr, templateEntity.FullName, ExportFileType.vdd); } /// /// 导入. /// /// /// [HttpPost("Model/Actions/ImportData")] public async Task ActionsActionsImport(IFormFile file) { string? fileType = Path.GetExtension(file.FileName).Replace(".", string.Empty); if (!fileType.ToLower().Equals(ExportFileType.vdd.ToString())) throw Oops.Oh(ErrorCode.D3006); string? josn = _fileManager.Import(file); VisualDevEntity? templateEntity; try { templateEntity = josn.ToObject(); } catch { throw Oops.Oh(ErrorCode.D3006); } if (templateEntity == null || templateEntity.Type.IsNullOrEmpty()) throw Oops.Oh(ErrorCode.D3006); else if (templateEntity.Type != 1) throw Oops.Oh(ErrorCode.D3009); if (await _visualDevService.GetDataExists(templateEntity.EnCode, templateEntity.FullName)) throw Oops.Oh(ErrorCode.D1400); await _visualDevService.CreateImportData(templateEntity); } /// /// 获取数据列表. /// /// 主键id. /// 分页查询条件. /// [HttpPost("{modelId}/List")] public async Task List(string modelId, [FromBody] VisualDevModelListQueryInput input) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.GetListAsync != null) { return await overideSvc.OverideFuncs.GetListAsync(input); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); return await _runService.GetListResult(templateEntity, input); } } /// /// 创建数据. /// /// /// /// [HttpPost("{modelId}")] public async Task Create(string modelId, [FromBody] VisualDevModelDataCrInput visualdevModelDataCrForm) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.CreateAsync != null) { await overideSvc.OverideFuncs.CreateAsync(visualdevModelDataCrForm); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); await _runService.Create(templateEntity, visualdevModelDataCrForm); } } /// /// 修改数据. /// /// /// /// /// [HttpPut("{modelId}/{id}")] public async Task Update(string modelId, string id, [FromBody] VisualDevModelDataUpInput visualdevModelDataUpForm) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.UpdateAsync != null) { await overideSvc.OverideFuncs.UpdateAsync(id, visualdevModelDataUpForm); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); await _runService.Update(id, templateEntity, visualdevModelDataUpForm); } } /// /// 删除数据. /// /// /// /// [HttpDelete("{modelId}/{id}")] public async Task Delete(string id, string modelId) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.DeleteAsync != null) { await overideSvc.OverideFuncs.DeleteAsync(id); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); if (!string.IsNullOrEmpty(templateEntity.Tables) && !"[]".Equals(templateEntity.Tables)) await _runService.DelHaveTableInfo(id, templateEntity); } } /// /// 批量删除. /// /// /// /// [HttpPost("batchDelete/{modelId}")] public async Task BatchDelete(string modelId, [FromBody] VisualDevModelDataBatchDelInput input) { var overideSvc = OverideVisualDevManager.GetOrDefault(modelId); if (overideSvc != null && overideSvc.OverideFuncs.DeleteRangeAsync != null) { await overideSvc.OverideFuncs.DeleteRangeAsync(input); } else { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); if (!string.IsNullOrEmpty(templateEntity.Tables) && !"[]".Equals(templateEntity.Tables)) await _runService.BatchDelHaveTableData(input.ids, templateEntity); } } /// /// 导出. /// /// /// /// [HttpPost("{modelId}/Actions/Export")] public async Task Export(string modelId, [FromBody] VisualDevModelListQueryInput input) { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); List list = new List(); if (input.dataType == "1") input.pageSize = 99999999; PageResult>? pageList = await _runService.GetListResult(templateEntity, input); // 如果是 分组表格 模板 ColumnDesignModel? columnData = templateEntity.ColumnData.ToObject(); // 列配置模型 if (columnData.type == 3) { List>? newValueList = new List>(); pageList.list.ForEach(item => { List>? tt = item["children"].ToJsonString().ToObject>>(); newValueList.AddRange(tt); }); pageList.list = newValueList; } List> realList = pageList.list.Copy(); var templateInfo = new TemplateParsingBase(templateEntity); var res = GetCreateFirstColumnsHeader(input.selectKey, realList, templateInfo.AllFieldsModel); var firstColumns = res.First().ToObject>(); var resultList = res.Last().ToObject>>(); var newResultList = new List>(); resultList.ForEach(row => { foreach (var item in input.selectKey) { if (row[item].IsNotEmptyOrNull()) { newResultList.Add(row); break; } } }); var excelName = string.Format("{0}", SnowflakeIdHelper.NextId()); _cacheManager.Set(excelName + ".xls", string.Empty); return firstColumns.Any() ? await ExcelCreateModel(templateInfo.AllFieldsModel, resultList, input.selectKey, excelName, firstColumns) : await ExcelCreateModel(templateInfo.AllFieldsModel, resultList, input.selectKey, excelName); } /// /// 模板下载. /// /// [HttpGet("{modelId}/TemplateDownload")] public async Task TemplateDownload(string modelId) { var tInfo = await GetUploaderTemplateInfoAsync(modelId); if (tInfo.selectKey == null || !tInfo.selectKey.Any()) throw Oops.Oh(ErrorCode.D1411); // 初始化 一条空数据 List>? dataList = new List>(); // 赋予默认值 var dicItem = new Dictionary(); tInfo.AllFieldsModel.Where(x => tInfo.selectKey.Contains(x.__vModel__)).ToList().ForEach(item => { switch (item.__config__.jnpfKey) { case JnpfKeyConst.CREATEUSER: case JnpfKeyConst.MODIFYUSER: case JnpfKeyConst.CREATETIME: case JnpfKeyConst.MODIFYTIME: case JnpfKeyConst.CURRORGANIZE: case JnpfKeyConst.CURRPOSITION: case JnpfKeyConst.CURRDEPT: case JnpfKeyConst.BILLRULE: dicItem.Add(item.__vModel__, "系统自动生成"); break; case JnpfKeyConst.COMSELECT: dicItem.Add(item.__vModel__, item.multiple ? "例:拓通智联/产品部,拓通智联/技术部" : "例:拓通智联/技术部"); break; case JnpfKeyConst.DEPSELECT: dicItem.Add(item.__vModel__, item.multiple ? "例:产品部/部门编码,技术部/部门编码" : "例:技术部/部门编码"); break; case JnpfKeyConst.POSSELECT: dicItem.Add(item.__vModel__, item.multiple ? "例:技术经理/岗位编码,技术员/岗位编码" : "例:技术员/岗位编码"); break; case JnpfKeyConst.USERSSELECT: dicItem.Add(item.__vModel__, item.selectType.Equals("all") ? "例:拓通智联/产品部,产品部/部门编码,技术经理/岗位编码,研发人员/角色编码,A分组/分组编码,张三/账号" : "例:李四/账号"); break; case JnpfKeyConst.USERSELECT: dicItem.Add(item.__vModel__, item.multiple ? "例:张三/账号,李四/账号" : "例:张三/账号"); break; case JnpfKeyConst.ROLESELECT: dicItem.Add(item.__vModel__, item.multiple ? "例:研发人员/角色编码,测试人员/角色编码" : "例:研发人员/角色编码"); break; case JnpfKeyConst.GROUPSELECT: dicItem.Add(item.__vModel__, item.multiple ? "例:A分组/分组编码,B分组/分组编码" : "例:A分组/分组编码"); break; case JnpfKeyConst.DATE: dicItem.Add(item.__vModel__, string.Format("例:{0}", item.format)); break; case JnpfKeyConst.TIME: dicItem.Add(item.__vModel__, "例: HH:mm:ss"); break; case JnpfKeyConst.ADDRESS: switch (item.level) { case 0: dicItem.Add(item.__vModel__, item.multiple ? "例:福建省,广东省" : "例:福建省"); break; case 1: dicItem.Add(item.__vModel__, item.multiple ? "例:福建省/莆田市,广东省/广州市" : "例:福建省/莆田市"); break; case 2: dicItem.Add(item.__vModel__, item.multiple ? "例:福建省/莆田市/城厢区,广东省/广州市/荔湾区" : "例:福建省/莆田市/城厢区"); break; case 3: dicItem.Add(item.__vModel__, item.multiple ? "例:福建省/莆田市/城厢区/霞林街道,广东省/广州市/荔湾区/沙面街道" : "例:福建省/莆田市/城厢区/霞林街道"); break; } break; default: dicItem.Add(item.__vModel__, string.Empty); break; } }); dicItem.Add("id", "id"); dataList.Add(dicItem); var excelName = string.Format("{0} 导入模板_{1}", tInfo.FullName, SnowflakeIdHelper.NextId()); var res = GetCreateFirstColumnsHeader(tInfo.selectKey, dataList, tInfo.AllFieldsModel); var firstColumns = res.First().ToObject>(); var resultList = res.Last().ToObject>>(); _cacheManager.Set(excelName + ".xls", string.Empty); return firstColumns.Any() ? await ExcelCreateModel(tInfo.AllFieldsModel, resultList, tInfo.selectKey, excelName, firstColumns) : await ExcelCreateModel(tInfo.AllFieldsModel, resultList, tInfo.selectKey, excelName); } /// /// 上传文件. /// /// /// [HttpPost("Uploader")] public async Task Uploader(IFormFile file) { var _filePath = _fileManager.GetPathByType(string.Empty); var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName); var stream = file.OpenReadStream(); await _fileManager.UploadFileByType(stream, _filePath, _fileName); return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) }; } /// /// 导入预览. /// /// [HttpGet("{modelId}/ImportPreview")] public async Task ImportPreview(string modelId, string fileName) { var tInfo = await GetUploaderTemplateInfoAsync(modelId); var resData = new List>(); var headerRow = new List(); var isChildTable = tInfo.ColumnData.columnList.Any(x => tInfo.ChildTableFields.ContainsKey(x.__vModel__)); try { var FileEncode = tInfo.AllFieldsModel.Where(x => tInfo.selectKey.Contains(x.__vModel__)).ToList(); string? savePath = Path.Combine(FileVariable.TemporaryFilePath, fileName); // 得到数据 global::System.Data.DataTable? excelData = ExcelImportHelper.ToDataTable(savePath); if (isChildTable) excelData = ExcelImportHelper.ToDataTable(savePath, 0, 1); if (excelData.Columns.Count > tInfo.selectKey.Count) excelData.Columns.RemoveAt(tInfo.selectKey.Count); foreach (object? item in excelData.Columns) { excelData.Columns[item.ToString()].ColumnName = FileEncode.Where(x => x.__config__.label == item.ToString()).FirstOrDefault().__vModel__; } resData = excelData.ToObject>>(); if (resData.Any()) { if (isChildTable) { var hRow = resData[1].Copy(); foreach (var item in hRow) { if (item.Key.Contains("tableField") && item.Key.Contains("-")) { var childVModel = item.Key.Split("-").First(); if (!headerRow.Any(x => x.id.Equals(childVModel))) { var child = new List(); hRow.Where(x => x.Key.Contains(childVModel)).ToList().ForEach(x => { child.Add(new { id = x.Key.Replace(childVModel + "-", string.Empty), fullName = x.Value.ToString().Replace(string.Format("({0})", x.Key), string.Empty) }); }); headerRow.Add(new { id = childVModel, fullName = tInfo.AllFieldsModel.Find(x => x.__vModel__.Equals(childVModel)).__config__.label.Replace(string.Format("({0})", childVModel), string.Empty), children = child }); } } else { headerRow.Add(new { id = item.Key, fullName = item.Value.ToString().Replace(string.Format("({0})", item.Key), string.Empty) }); } } resData.Remove(resData.First()); resData.Remove(resData.First()); } else { foreach (var item in resData.First().Copy()) headerRow.Add(new { id = item.Key, fullName = item.Value.ToString().Replace(string.Format("({0})", item.Key), string.Empty) }); resData.Remove(resData.First()); } } } catch (Exception e) { throw Oops.Oh(ErrorCode.D1410); } try { // 带子表字段数据导入 if (isChildTable) { var newData = new List>(); var singleForm = tInfo.selectKey.Where(x => !x.Contains("tableField")).ToList(); var childTableVModel = tInfo.AllFieldsModel.Where(x => x.__config__.jnpfKey.Equals(JnpfKeyConst.TABLE)).Select(x => x.__vModel__).ToList(); resData.ForEach(dataItem => { var addItem = new Dictionary(); var isNextRow = false; singleForm.ForEach(item => { if (dataItem[item].IsNotEmptyOrNull()) isNextRow = true; }); // 单条数据 (多行子表数据合并) if (isNextRow) { singleForm.ForEach(item => addItem.Add(item, dataItem[item])); // 子表数据 childTableVModel.ForEach(item => { var childAddItem = new Dictionary(); tInfo.selectKey.Where(x => x.Contains(item)).ToList().ForEach(it => { childAddItem.Add(it.Replace(item + "-", string.Empty), dataItem[it]); }); addItem.Add(item, new List> { childAddItem }); }); newData.Add(addItem); } else { var item = newData.LastOrDefault(); if (item != null) { // 子表数据 childTableVModel.ForEach(citem => { var childAddItem = new Dictionary(); tInfo.selectKey.Where(x => x.Contains(citem)).ToList().ForEach(it => { childAddItem.Add(it.Replace(citem + "-", string.Empty), dataItem[it]); }); if (!item.ContainsKey(citem)) { item.Add(citem, new List> { childAddItem }); } else { var childList = item[citem].ToObject>>(); childList.Add(childAddItem); item[citem] = childList; } }); } else { singleForm.ForEach(item => addItem.Add(item, dataItem[item])); // 子表数据 childTableVModel.ForEach(item => { var childAddItem = new Dictionary(); tInfo.selectKey.Where(x => x.Contains(item)).ToList().ForEach(it => { childAddItem.Add(it.Replace(item + "-", string.Empty), dataItem[it]); }); addItem.Add(item, new List> { childAddItem }); }); newData.Add(addItem); } } }); resData = newData; } } catch { throw Oops.Oh(ErrorCode.D1412); } resData.ForEach(items => { foreach (var item in items) { var vmodel = tInfo.AllFieldsModel.FirstOrDefault(x => x.__vModel__.Equals(item.Key)); if (vmodel != null && vmodel.__config__.jnpfKey.Equals(JnpfKeyConst.DATE) && item.Value.IsNotEmptyOrNull()) items[item.Key] = item.Value + " "; } }); // 返回结果 return new { dataRow = resData, headerRow = headerRow }; } /// /// 导入数据的错误报告. /// /// /// [HttpPost("{modelId}/ImportExceptionData")] [UnitOfWork] public async Task ExportExceptionData(string modelId, [FromBody] VisualDevImportDataInput list) { var tInfo = await GetUploaderTemplateInfoAsync(modelId); //object[]? res = await ImportMenuData(tInfo, list.list, tInfo.visualDevEntity); // 错误数据 tInfo.selectKey.Add("errorsInfo"); tInfo.AllFieldsModel.Add(new FieldsModel() { __vModel__ = "errorsInfo", __config__ = new ConfigModel() { label = "异常原因" } }); for (var i = 0; i < list.list.Count(); i++) list.list[i].Add("id", i); var result = GetCreateFirstColumnsHeader(tInfo.selectKey, list.list, tInfo.AllFieldsModel); var firstColumns = result.First().ToObject>(); var resultList = result.Last().ToObject>>(); _cacheManager.Set(string.Format("{0} 导入错误报告.xls", tInfo.FullName), string.Empty); return firstColumns.Any() ? await ExcelCreateModel(tInfo.AllFieldsModel, resultList, tInfo.selectKey, string.Format("{0} 导入错误报告", tInfo.FullName), firstColumns) : await ExcelCreateModel(tInfo.AllFieldsModel, resultList, tInfo.selectKey, string.Format("{0} 导入错误报告", tInfo.FullName)); } /// /// 导入数据. /// /// /// [HttpPost("{modelId}/ImportData")] [UnitOfWork] public async Task ImportData(string modelId, [FromBody] VisualDevImportDataInput list) { var tInfo = await GetUploaderTemplateInfoAsync(modelId); object[]? res = await ImportMenuData(tInfo, list.list, tInfo.visualDevEntity); var addlist = res.First() as List>; var errorlist = res.Last() as List>; var result = new VisualDevImportDataOutput() { snum = addlist.Count, fnum = errorlist.Count, failResult = errorlist, resultType = errorlist.Count < 1 ? 0 : 1 }; return result; } #endregion #region PublicMethod /// /// Excel 转输出 Model. /// /// 控件集合. /// 数据列表. /// /// 导出文件名称. /// 手动输入第一行(合并主表列和各个子表列). /// VisualDevModelDataExportOutput. public async Task ExcelCreateModel(List fieldList, List> realList, List keys, string excelName = null, Dictionary firstColumns = null) { VisualDevModelDataExportOutput output = new VisualDevModelDataExportOutput(); try { List columnList = new List(); ExcelConfig excelconfig = new ExcelConfig(); excelconfig.FileName = (excelName.IsNullOrEmpty() ? SnowflakeIdHelper.NextId() : excelName) + ".xls"; excelconfig.HeadFont = "微软雅黑"; excelconfig.HeadPoint = 10; excelconfig.IsAllSizeColumn = true; excelconfig.ColumnModel = new List(); foreach (string? item in keys) { FieldsModel? excelColumn = fieldList.Find(t => t.__vModel__ == item); if (excelColumn != null) { excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = item, ExcelColumn = excelColumn.__config__.label }); columnList.Add(excelColumn.__config__.label); } } string? addPath = Path.Combine(FileVariable.TemporaryFilePath, excelconfig.FileName); var fs = firstColumns == null ? ExcelExportHelper>.ExportMemoryStream(realList, excelconfig, columnList) : ExcelExportHelper>.ExportMemoryStream(realList, excelconfig, columnList, firstColumns); var flag = await _fileManager.UploadFileByType(fs, FileVariable.TemporaryFilePath, excelconfig.FileName); if (flag) { fs.Flush(); fs.Close(); } output.name = excelconfig.FileName; output.url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + excelconfig.FileName + "|" + addPath, "JNPF"); return output; } catch (Exception) { throw; } } /// /// 组装导出带子表得数据,返回 第一个合并行标头,第二个导出数据. /// /// 导出选择列. /// 原数据集合. /// 控件列表. /// 第一行标头 , 导出数据. public object[] GetCreateFirstColumnsHeader(List selectKey, List> realList, List fieldList) { selectKey.ForEach(item => { realList.ForEach(it => { if (!it.ContainsKey(item)) it.Add(item, string.Empty); }); }); var newRealList = realList.Copy(); realList.ForEach(items => { var rowChildDatas = new Dictionary>>(); foreach (var item in items) { if (item.Value != null && item.Key.ToLower().Contains("tablefield") && (item.Value is List> || item.Value.GetType().Name.Equals("JArray"))) { var ctList = item.Value.ToObject>>(); rowChildDatas.Add(item.Key, ctList); } } var len = rowChildDatas.Select(x => x.Value.Count()).OrderByDescending(x => x).FirstOrDefault(); if (len != null && len > 0) { for (int i = 0; i < len; i++) { if (i == 0) { var newRealItem = newRealList.Find(x => x["id"].Equals(items["id"])); foreach (var cData in rowChildDatas) { var itemData = cData.Value.FirstOrDefault(); if (itemData != null) { foreach (var key in itemData) if (newRealItem.ContainsKey(cData.Key + "-" + key.Key)) newRealItem[cData.Key + "-" + key.Key] = key.Value; } } } else { var newRealItem = new Dictionary(); foreach (var it in items) { if (it.Key.Equals("id")) newRealItem.Add(it.Key, it.Value); else newRealItem.Add(it.Key, string.Empty); } foreach (var cData in rowChildDatas) { if (cData.Value.Count > i) { foreach (var it in cData.Value[i]) if (newRealItem.ContainsKey(cData.Key + "-" + it.Key)) newRealItem[cData.Key + "-" + it.Key] = it.Value; } } newRealList.Add(newRealItem); } } } }); var resultList = new List>(); newRealList.ForEach(newRealItem => { if (!resultList.Any(x => x["id"].Equals(newRealItem["id"]))) resultList.AddRange(newRealList.Where(x => x["id"].Equals(newRealItem["id"])).ToList()); }); var firstColumns = new Dictionary(); if (selectKey.Any(x => x.Contains("-") && x.ToLower().Contains("tablefield"))) { var empty = string.Empty; var keyList = selectKey.Select(x => x.Split("-").First()).Distinct().ToList(); var mainFieldIndex = 1; keyList.ForEach(item => { if (item.ToLower().Contains("tablefield")) { var title = fieldList.FirstOrDefault(x => x.__vModel__.Equals(item))?.__config__.label; firstColumns.Add(title + empty, selectKey.Count(x => x.Contains(item))); empty += " "; mainFieldIndex = 1; } else { if (mainFieldIndex == 1) empty += " "; if (!firstColumns.ContainsKey(empty)) firstColumns.Add(empty, mainFieldIndex); else firstColumns[empty] = mainFieldIndex; mainFieldIndex++; } }); } return new object[] { firstColumns, resultList }; } #endregion #region PrivateMethod /// /// 获取导出模板信息. /// /// /// private async Task GetUploaderTemplateInfoAsync(string modelId) { VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(modelId, true); var tInfo = new TemplateParsingBase(templateEntity); tInfo.DbLink = await _dbLinkService.GetInfo(templateEntity.DbLinkId); if (tInfo.DbLink == null) tInfo.DbLink = _databaseService.GetTenantDbLink(_userManager.TenantId, _userManager.TenantDbName); // 当前数据库连接 var tableList = _databaseService.GetFieldList(tInfo.DbLink, tInfo.MainTableName); // 获取主表所有列 var mainPrimary = tableList.Find(t => t.primaryKey); // 主表主键 if (mainPrimary == null || mainPrimary.IsNullOrEmpty()) throw Oops.Oh(ErrorCode.D1402); // 主表未设置主键 tInfo.MainPrimary = mainPrimary.field; tInfo.AllFieldsModel = tInfo.AllFieldsModel.Where(x => !x.__config__.jnpfKey.Equals(JnpfKeyConst.UPLOADFZ) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.UPLOADIMG) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.COLORPICKER) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.POPUPTABLESELECT) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.RELATIONFORM) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.POPUPSELECT) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.RELATIONFORMATTR) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.POPUPATTR) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.QRCODE) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.BARCODE) && !x.__config__.jnpfKey.Equals(JnpfKeyConst.CALCULATE)).ToList(); tInfo.AllFieldsModel.Where(x => x.__vModel__.IsNotEmptyOrNull()).ToList().ForEach(item => item.__config__.label = string.Format("{0}({1})", item.__config__.label, item.__vModel__)); return tInfo; } /// /// 导入数据. /// /// 模板信息. /// 数据集合. /// 开发实体. /// [成功列表,失败列表]. private async Task ImportMenuData(TemplateParsingBase tInfo, List> list, VisualDevEntity tEntity = null) { List> userInputList = ImportFirstVerify(tInfo, list); List fieldsModelList = tInfo.AllFieldsModel.Where(x => tInfo.selectKey.Contains(x.__vModel__)).ToList(); var successList = new List>(); var errorsList = new List>(); // 捞取控件解析数据 var cData = await GetCDataList(tInfo.AllFieldsModel, new Dictionary>>()); var res = await ImportDataAssemble(tInfo.AllFieldsModel, userInputList, cData); res.Where(x => x.ContainsKey("errorsInfo")).ToList().ForEach(item => errorsList.Add(item)); res.Where(x => !x.ContainsKey("errorsInfo")).ToList().ForEach(item => successList.Add(item)); try { // 唯一验证已处理,入库前去掉. tInfo.AllFieldsModel.Where(x => x.__config__.jnpfKey.Equals(JnpfKeyConst.COMINPUT) && x.__config__.unique).ToList().ForEach(item => item.__config__.unique = false); _db.BeginTran(); foreach (var item in successList) { if (item.ContainsKey("Update_MainTablePrimary_Id")) { string? mainId = item["Update_MainTablePrimary_Id"].ToString(); var haveTableSql = await _runService.GetUpdateSqlByTemplate(tInfo, new VisualDevModelDataUpInput() { data = item.ToJsonString() }, mainId); foreach (var it in haveTableSql) await _databaseService.ExecuteSql(tInfo.DbLink, it); // 修改功能数据 } else { if (tInfo.visualDevEntity.EnableFlow.Equals(1)) { var flowId = _visualDevRepository.AsSugarClient().Queryable().First(x => x.Id.Equals(tInfo.visualDevEntity.Id)).FlowId; await _flowTaskService.Create(new Common.Models.WorkFlow.FlowTaskSubmitModel() { formData = item, flowId = flowId, flowUrgent = 1, status = 1 }); } else { string? mainId = SnowflakeIdHelper.NextId(); var haveTableSql = await _runService.GetCreateSqlByTemplate(tInfo, new VisualDevModelDataCrInput() { data = item.ToJsonString() }, mainId); // 主表自增长Id. if (haveTableSql.ContainsKey("MainTableReturnIdentity")) haveTableSql.Remove("MainTableReturnIdentity"); foreach (var it in haveTableSql) await _databaseService.ExecuteSql(tInfo.DbLink, it.Key, it.Value); // 新增功能数据 } } } _db.CommitTran(); } catch (Exception e) { _db.RollbackTran(); throw; } errorsList.ForEach(item => { if (item.ContainsKey("errorsInfo") && item["errorsInfo"].IsNotEmptyOrNull()) item["errorsInfo"] = item["errorsInfo"].ToString().TrimStart(',').TrimEnd(','); }); return new object[] { successList, errorsList }; } /// /// 导入功能数据初步验证. /// private List> ImportFirstVerify(TemplateParsingBase tInfo, List> list) { var errorKey = "errorsInfo"; var resList = new List>(); list.ForEach(item => { var addItem = item.Copy(); addItem.Add(errorKey, string.Empty); resList.Add(addItem); }); #region 验证必填控件 var childTableList = tInfo.AllFieldsModel.Where(x => x.__config__.jnpfKey.Equals(JnpfKeyConst.TABLE)).Select(x => x.__vModel__).ToList(); var requiredList = tInfo.AllFieldsModel.Where(x => x.__config__.required).ToList(); var VModelList = requiredList.Select(x => x.__vModel__).ToList(); if (VModelList.Any()) { var newResList = new List>(); resList.ForEach(items => { var newItems = items.Copy(); foreach (var item in items) { if (item.Value.IsNullOrEmpty() && VModelList.Contains(item.Key)) { var errorInfo = requiredList.Find(x => x.__vModel__.Equals(item.Key)).__config__.label + ": 值不能为空"; if (newItems.ContainsKey(errorKey)) newItems[errorKey] = newItems[errorKey] + "," + errorInfo; else newItems.Add(errorKey, errorInfo); } // 子表 if (childTableList.Contains(item.Key)) { item.Value.ToObject>>().ForEach(childItems => { foreach (var childItem in childItems) { if (childItem.Value.IsNullOrEmpty() && VModelList.Contains(item.Key + "-" + childItem.Key)) { var errorInfo = tInfo.AllFieldsModel.Find(x => x.__vModel__.Equals(item.Key)).__config__.children.Find(x => x.__vModel__.Equals(item.Key + "-" + childItem.Key)).__config__.label + ": 值不能为空"; if (newItems.ContainsKey(errorKey)) newItems[errorKey] = newItems[errorKey] + "," + errorInfo; else newItems.Add(errorKey, errorInfo); } } }); } } newResList.Add(newItems); }); resList = newResList; } #endregion #region 验证唯一 var uniqueList = tInfo.AllFieldsModel.Where(x => x.__config__.unique).ToList(); VModelList = uniqueList.Select(x => x.__vModel__).ToList(); if (uniqueList.Any()) { resList.ForEach(items => { foreach (var item in items) { if (VModelList.Contains(item.Key)) { var vlist = new List>(); resList.Where(x => x.ContainsKey(item.Key) && x.ContainsValue(item.Value)).ToList().ForEach(it => { foreach (var dic in it) { if (dic.Value != null && item.Value != null && dic.Key.Equals(item.Key) && dic.Value.Equals(item.Value)) { vlist.Add(it); break; } } }); if (vlist.Count > 1) { for (var i = 1; i < vlist.Count; i++) { var errorInfo = tInfo.AllFieldsModel.Find(x => x.__vModel__.Equals(item.Key)).__config__.label + ": 值不能重复"; items[errorKey] = items[errorKey] + "," + errorInfo; } } } // 子表 var updateItemCList = new List>(); var ctItemErrors = new List(); if (childTableList.Contains(item.Key)) { var itemCList = item.Value.ToObject>>(); itemCList.ForEach(childItems => { if (tInfo.dataType.Equals("2")) { foreach (var childItem in childItems) { var uniqueKey = item.Key + "-" + childItem.Key; if (VModelList.Contains(uniqueKey)) { var vlist = itemCList.Where(x => x.ContainsKey(childItem.Key) && x.ContainsValue(childItem.Value)).ToList(); if (!updateItemCList.Any(x => x.ContainsKey(childItem.Key) && x.ContainsValue(childItem.Value))) updateItemCList.Add(vlist.Last()); } } } else { foreach (var childItem in childItems) { var uniqueKey = item.Key + "-" + childItem.Key; if (VModelList.Contains(uniqueKey) && childItem.Value != null) { var vlist = itemCList.Where(x => x.ContainsKey(childItem.Key) && x.ContainsValue(childItem.Value)).ToList(); if (vlist.Count > 1) { for (var i = 1; i < vlist.Count; i++) { var errorTxt = tInfo.AllFieldsModel.Find(x => x.__vModel__.Equals(uniqueKey)).__config__.label + ": 值不能重复"; if (!ctItemErrors.Any(x => x.Equals(errorTxt))) ctItemErrors.Add(errorTxt); } } } } } }); } if (tInfo.dataType.Equals("2") && updateItemCList.Any()) items[item.Key] = updateItemCList; if (ctItemErrors.Any()) { items[errorKey] = items[errorKey].IsNullOrEmpty() ? string.Join(",", ctItemErrors) : items[errorKey] + "," + string.Join(",", ctItemErrors); } } }); // 表里的数据验证唯一 List? relationKey = new List(); List? auxiliaryFieldList = tInfo.AuxiliaryTableFieldsModelList.Select(x => x.__config__.tableName).Distinct().ToList(); auxiliaryFieldList.ForEach(tName => { string? tableField = tInfo.AllTable.Find(tf => tf.table == tName)?.tableField; relationKey.Add(tInfo.MainTableName + "." + tInfo.MainPrimary + "=" + tName + "." + tableField); }); resList.ForEach(allDataMap => { List? fieldList = new List(); var whereList = new List(); fieldList.Add(string.Format("{0}.{1}", tInfo.MainTableName, tInfo.MainPrimary)); tInfo.SingleFormData.Where(x => x.__config__.jnpfKey.Equals(JnpfKeyConst.COMINPUT) && x.__config__.unique).ToList().ForEach(item => { fieldList.Add(string.Format("{0}.{1} {2}", item.__config__.tableName, item.__vModel__.Split("_jnpf_").Last(), item.__vModel__)); if (allDataMap.ContainsKey(item.__vModel__) && allDataMap[item.__vModel__] != null) { whereList.Add(new ConditionalCollections() { ConditionalList = new List>() { new KeyValuePair(WhereType.Or, new ConditionalModel { FieldName = string.Format("{0}.{1}", item.__config__.tableName, item.__vModel__.Split("_jnpf_").Last()), ConditionalType =allDataMap.ContainsKey(item.__vModel__) ? ConditionalType.Equal: ConditionalType.IsNullOrEmpty, FieldValue = allDataMap.ContainsKey(item.__vModel__) ? allDataMap[item.__vModel__].ToString() : string.Empty, }) } }); } }); var itemWhere = _visualDevRepository.AsSugarClient().SqlQueryable("@").Where(whereList).ToSqlString(); if (!itemWhere.Equals("@")) { var whereStrList = new List(); whereStrList.AddRange(relationKey); whereStrList.Add(itemWhere.Split("WHERE").Last()); var querStr = string.Format( "select {0} from {1} where {2}", string.Join(",", fieldList), auxiliaryFieldList.Any() ? tInfo.MainTableName + "," + string.Join(",", auxiliaryFieldList) : tInfo.MainTableName, string.Join(" and ", whereStrList)); // 多表, 联合查询 var res = _databaseService.GetInterFaceData(tInfo.DbLink, querStr, null).ToObject>>(); if (res.Any()) { var errorList = new List(); res.ForEach(items => { if (tInfo.dataType.Equals("2")) { if (items.Last().Value == null || items.Last().Value.Equals(allDataMap[items.Last().Key].ToString())) { if (!allDataMap.ContainsKey("Update_MainTablePrimary_Id")) allDataMap.Add("Update_MainTablePrimary_Id", items[tInfo.MainPrimary]); } } else { if (items.Last().Value == null || items.Last().Value.Equals(allDataMap[items.Last().Key].ToString())) { var errorInfo = tInfo.SingleFormData.First(x => x.__vModel__.Equals(items.Last().Key))?.__config__.label + ": 值不能重复"; if (allDataMap.ContainsKey(errorKey)) { if (!allDataMap[errorKey].ToString().Contains(errorInfo)) allDataMap[errorKey] = allDataMap[errorKey] + "," + errorInfo; } else { allDataMap.Add(errorKey, errorInfo); } } } }); } } }); } #endregion resList.ForEach(item => { if (item[errorKey].IsNullOrEmpty()) item.Remove(errorKey); }); return resList; } /// /// 获取模板控件解析数据. /// /// /// /// private async Task>>> GetCDataList(List listFieldsModel, Dictionary>> resData) { foreach (var item in listFieldsModel.Where(x => !x.__config__.jnpfKey.Equals(JnpfKeyConst.TABLE)).ToList()) { var addItem = new List>(); switch (item.__config__.jnpfKey) { case JnpfKeyConst.COMSELECT: { if (!resData.ContainsKey(JnpfKeyConst.COMSELECT)) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1) .Select(x => new OrganizeEntity { Id = x.Id, OrganizeIdTree = x.OrganizeIdTree, FullName = x.FullName }).ToListAsync(); dataList.ForEach(item => { if (item.OrganizeIdTree.IsNullOrEmpty()) item.OrganizeIdTree = item.Id; var orgNameList = new List(); item.OrganizeIdTree.Split(",").ToList().ForEach(it => { var org = dataList.Find(x => x.Id == it); if (org != null) orgNameList.Add(org.FullName); }); Dictionary dictionary = new Dictionary(); dictionary.Add(item.OrganizeIdTree, string.Join("/", orgNameList)); addItem.Add(dictionary); }); resData.Add(JnpfKeyConst.COMSELECT, addItem); } } break; case JnpfKeyConst.ADDRESS: { string? addCacheKey = "Import_Address"; if (!resData.ContainsKey(JnpfKeyConst.ADDRESS)) { if (_cacheManager.Exists(addCacheKey)) { addItem = _cacheManager.Get(addCacheKey).ToObject>>(); resData.Add(JnpfKeyConst.ADDRESS, addItem); } else { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Select(x => new ProvinceEntity { Id = x.Id, ParentId = x.ParentId, Type = x.Type, FullName = x.FullName }).ToListAsync(); // 处理省市区树 dataList.Where(x => x.Type == "1").ToList().ForEach(item => { item.QuickQuery = item.FullName; item.Description = item.Id; Dictionary address = new Dictionary(); address.Add(item.Description, item.QuickQuery); addItem.Add(address); }); dataList.Where(x => x.Type == "2").ToList().ForEach(item => { item.QuickQuery = dataList.Find(x => x.Id == item.ParentId).QuickQuery + "/" + item.FullName; item.Description = dataList.Find(x => x.Id == item.ParentId).Description + "," + item.Id; Dictionary address = new Dictionary(); address.Add(item.Description, item.QuickQuery); addItem.Add(address); }); dataList.Where(x => x.Type == "3").ToList().ForEach(item => { item.QuickQuery = dataList.Find(x => x.Id == item.ParentId).QuickQuery + "/" + item.FullName; item.Description = dataList.Find(x => x.Id == item.ParentId).Description + "," + item.Id; Dictionary address = new Dictionary(); address.Add(item.Description, item.QuickQuery); addItem.Add(address); }); dataList.Where(x => x.Type == "4").ToList().ForEach(item => { ProvinceEntity? it = dataList.Find(x => x.Id == item.ParentId); if (it != null) { item.QuickQuery = it.QuickQuery + "/" + item.FullName; item.Description = it.Description + "," + item.Id; Dictionary address = new Dictionary(); address.Add(item.Description, item.QuickQuery); addItem.Add(address); } }); dataList.ForEach(it => { if (it.Description.IsNotEmptyOrNull()) { Dictionary dictionary = new Dictionary(); dictionary.Add(it.Description, it.QuickQuery); addItem.Add(dictionary); } }); var noTypeList = dataList.Where(x => x.Type.IsNullOrWhiteSpace()).ToList(); foreach (var it in noTypeList) { it.QuickQuery = GetAddressByPList(noTypeList, it); it.Description = GetAddressIdByPList(noTypeList, it); } foreach (var it in noTypeList) { Dictionary address = new Dictionary(); address.Add(it.Description, it.QuickQuery); addItem.Add(address); } _cacheManager.Set(addCacheKey, addItem, TimeSpan.FromDays(7)); // 缓存七天 resData.Add(JnpfKeyConst.ADDRESS, addItem); } } } break; case JnpfKeyConst.GROUPSELECT: { if (!resData.ContainsKey(JnpfKeyConst.GROUPSELECT)) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new GroupEntity() { Id = x.Id, EnCode = x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); addItem.Add(dictionary); }); resData.Add(JnpfKeyConst.GROUPSELECT, addItem); } } break; case JnpfKeyConst.ROLESELECT: { if (!resData.ContainsKey(JnpfKeyConst.ROLESELECT)) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new RoleEntity() { Id = x.Id, EnCode = x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); addItem.Add(dictionary); }); resData.Add(JnpfKeyConst.ROLESELECT, addItem); } } break; case JnpfKeyConst.SWITCH: { if (!resData.ContainsKey(item.__vModel__)) { Dictionary dictionary = new Dictionary(); dictionary.Add("1", item.activeTxt); addItem.Add(dictionary); Dictionary dictionary2 = new Dictionary(); dictionary2.Add("0", item.inactiveTxt); addItem.Add(dictionary2); resData.Add(item.__vModel__, addItem); } } break; case JnpfKeyConst.CHECKBOX: case JnpfKeyConst.SELECT: case JnpfKeyConst.RADIO: { if (!resData.ContainsKey(item.__vModel__)) { var propsValue = string.Empty; var propsLabel = string.Empty; var children = string.Empty; if (item.__config__.jnpfKey.Equals(JnpfKeyConst.TREESELECT) || item.__config__.jnpfKey.Equals(JnpfKeyConst.CASCADER)) { propsValue = item.props.props.value; propsLabel = item.props.props.label; children = item.props.props.children; } else { propsValue = item.__config__.props.value; propsLabel = item.__config__.props.label; children = item.__config__.props.children; } if (item.__config__.dataType.Equals("static")) { if (item.__slot__ != null && item.__slot__.options != null) { item.__slot__.options.ForEach(option => { Dictionary dictionary = new Dictionary(); dictionary.Add(option[propsValue].ToString(), option[propsLabel].ToString()); addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } } else if (item.__config__.dataType.Equals("dictionary")) { var dictionaryDataList = await _visualDevRepository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.DictionaryTypeId)) .WhereIF(item.__config__.dictionaryType.IsNotEmptyOrNull(), (a, b) => b.Id == item.__config__.dictionaryType || b.EnCode == item.__config__.dictionaryType) .Where(a => a.DeleteMark == null).Select(a => new { a.Id, a.EnCode, a.FullName }).ToListAsync(); foreach (var it in dictionaryDataList) { Dictionary dictionary = new Dictionary(); if (propsValue.Equals("id")) dictionary.Add(it.Id, it.FullName); if (propsValue.Equals("enCode")) dictionary.Add(it.EnCode, it.FullName); addItem.Add(dictionary); } resData.Add(item.__vModel__, addItem); } else if (item.__config__.dataType.Equals("dynamic")) { List> list = new List>(); // 获取远端数据 DataInterfaceEntity? dynamic = await _dataInterfaceService.GetInfo(item.__config__.propsUrl); if (dynamic == null) continue; switch (dynamic.DataType) { // SQL数据 case 1: { // 远端数据 配置参数 List? parameter = new List(); if (_userManager.ToKen != null) { parameter.Add(new SugarParameter("@user", _userManager.UserId)); parameter.Add(new SugarParameter("@organization", _userManager?.User?.OrganizeId)); var subordinates = _userManager.Subordinates; subordinates.Add(_userManager.UserId); parameter.Add(new SugarParameter("@currentUsersAndSubordinates", subordinates)); var subsidiary = _userManager.Subsidiary; subsidiary.Add(_userManager.User.OrganizeId); parameter.Add(new SugarParameter("@currentOrganizationAndSuborganization", subsidiary)); var chargeorganization = _userManager.DataScope.Where(x => x.organizeId == _userManager.User.OrganizeId && x.Select).ToList().FirstOrDefault(); parameter.Add(new SugarParameter("@chargeorganization", chargeorganization?.organizeId)); subsidiary = _userManager.DataScope.Select(x => x.organizeId).Intersect(_userManager.Subsidiary).ToList(); parameter.Add(new SugarParameter("@currentChargeorganizationAndSuborganization", subsidiary)); } DbLinkEntity? linkEntity = await _visualDevRepository.AsSugarClient().Queryable().Where(m => m.Id == dynamic.DBLinkId && m.DeleteMark == null).FirstAsync(); if (linkEntity == null) linkEntity = _databaseService.GetTenantDbLink(_userManager.TenantId, _userManager.TenantDbName); _dataInterfaceService.ReplaceParameterValue(dynamic, new Dictionary()); System.Data.DataTable? dt = _databaseService.GetInterFaceData(linkEntity, dynamic.Query, parameter.ToArray()); List> dynamicDataList = dt.ToJsonString().ToObject>>(); foreach (Dictionary? it in dynamicDataList) { Dictionary dynamicDic = new Dictionary(); dynamicDic.Add(it[propsValue]?.ToString(), it[propsLabel]?.ToString()); list.Add(dynamicDic); } } break; // 静态数据 case 2: { foreach (var data in JValue.Parse(dynamic.Query)) { Dictionary dic = new Dictionary(); dic[data.Value(propsValue)] = data.Value(propsLabel); list.Add(dic); if (children != null && data.Value(children) != null && data.Value(children).ToString().IsNotEmptyOrNull()) list.AddRange(GetDynamicInfiniteData(data.Value(children).ToString(), item.__config__.props)); } } break; // Api数据 case 3: { // 获取远端数据 var dynamicList = await _dataInterfaceService.GetInfo(item.__config__.propsUrl); if (dynamicList == null) break; var redisName = CommonConst.VISUALDEV + _userManager.TenantId + "_" + item.__config__.jnpfKey + "_" + item.__config__.renderKey; switch (dynamicList.DataType) { case 1: // SQL数据 { _dataInterfaceService.ReplaceParameterValue(dynamicList, new Dictionary()); var pObj = await _dataInterfaceService.GetData(dynamicList); list = pObj.ToJsonString().ToObject>>(); } break; case 2: // 静态数据 { foreach (var data in JValue.Parse(dynamicList.Query)) { Dictionary dic = new Dictionary(); dic[propsValue] = data.Value(propsValue); dic[propsLabel] = data.Value(propsLabel); list.Add(dic); if (children != null && data.Value(children) != null && data.Value(children).ToString() != "") list.AddRange(GetDynamicInfiniteData(data.Value(children).ToString(), item.__config__.props)); } } break; case 3: // Api数据 { var result = await GetApiDataByTypePreview(dynamicList); // 请求接口 list = result.ContainsKey("list") ? result["list"].ToObject>>() : new List>(); } break; } } break; } resData.Add(item.__vModel__, list); } } } break; case JnpfKeyConst.TREESELECT: case JnpfKeyConst.CASCADER: { if (!resData.ContainsKey(item.__vModel__)) { if (item.__config__.dataType.Equals("static")) { if (item.options != null) resData.Add(item.__vModel__, GetStaticList(item)); } else if (item.__config__.dataType.Equals("dictionary")) { var dictionaryDataList = await _visualDevRepository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.DictionaryTypeId)) .WhereIF(item.__config__.dictionaryType.IsNotEmptyOrNull(), (a, b) => b.Id == item.__config__.dictionaryType || b.EnCode == item.__config__.dictionaryType) .Where(a => a.DeleteMark == null).Select(a => new { a.Id, a.EnCode, a.FullName }).ToListAsync(); foreach (var it in dictionaryDataList) { Dictionary dictionary = new Dictionary(); dictionary.Add(it.Id, it.FullName); dictionary.Add(it.EnCode, it.FullName); addItem.Add(dictionary); } resData.Add(item.__vModel__, addItem); } else if (item.__config__.dataType.Equals("dynamic")) { var propsValue = string.Empty; var propsLabel = string.Empty; var children = string.Empty; if (item.__config__.jnpfKey.Equals(JnpfKeyConst.TREESELECT) || item.__config__.jnpfKey.Equals(JnpfKeyConst.CASCADER)) { propsValue = item.props.props.value; propsLabel = item.props.props.label; children = item.props.props.children; } else { propsValue = item.__config__.props.value; propsLabel = item.__config__.props.label; children = item.__config__.props.children; } List> list = new List>(); // 获取远端数据 DataInterfaceEntity? dynamic = await _dataInterfaceService.GetInfo(item.__config__.propsUrl); if (dynamic == null) continue; switch (dynamic.DataType) { // SQL数据 case 1: { // 远端数据 配置参数 List? parameter = new List(); if (_userManager.ToKen != null) { parameter.Add(new SugarParameter("@user", _userManager.UserId)); parameter.Add(new SugarParameter("@organization", _userManager?.User?.OrganizeId)); var subordinates = _userManager.Subordinates; subordinates.Add(_userManager.UserId); parameter.Add(new SugarParameter("@currentUsersAndSubordinates", subordinates)); var subsidiary = _userManager.Subsidiary; subsidiary.Add(_userManager.User.OrganizeId); parameter.Add(new SugarParameter("@currentOrganizationAndSuborganization", subsidiary)); var chargeorganization = _userManager.DataScope.Where(x => x.organizeId == _userManager.User.OrganizeId && x.Select).ToList().FirstOrDefault(); parameter.Add(new SugarParameter("@chargeorganization", chargeorganization?.organizeId)); subsidiary = _userManager.DataScope.Select(x => x.organizeId).Intersect(_userManager.Subsidiary).ToList(); parameter.Add(new SugarParameter("@currentChargeorganizationAndSuborganization", subsidiary)); } DbLinkEntity? linkEntity = await _visualDevRepository.AsSugarClient().Queryable().Where(m => m.Id == dynamic.DBLinkId && m.DeleteMark == null).FirstAsync(); if (linkEntity == null) linkEntity = _databaseService.GetTenantDbLink(_userManager.TenantId, _userManager.TenantDbName); _dataInterfaceService.ReplaceParameterValue(dynamic, new Dictionary()); System.Data.DataTable? dt = _databaseService.GetInterFaceData(linkEntity, dynamic.Query, parameter.ToArray()); List> dynamicDataList = dt.ToJsonString().ToObject>>(); foreach (Dictionary? it in dynamicDataList) { Dictionary dynamicDic = new Dictionary(); dynamicDic.Add(it[propsValue]?.ToString(), it[propsLabel]?.ToString()); list.Add(dynamicDic); } } break; // 静态数据 case 2: { foreach (var data in JValue.Parse(dynamic.Query)) { Dictionary dic = new Dictionary(); dic[data.Value(propsValue)] = data.Value(propsLabel); list.Add(dic); if (children != null && data.Value(children) != null && data.Value(children).ToString().IsNotEmptyOrNull()) list.AddRange(GetDynamicInfiniteData(data.Value(children).ToString(), item.props.props)); } } break; // Api数据 case 3: { // 获取远端数据 var dynamicList = await _dataInterfaceService.GetInfo(item.__config__.propsUrl); if (dynamicList == null) break; var redisName = CommonConst.VISUALDEV + _userManager.TenantId + "_" + item.__config__.jnpfKey + "_" + item.__config__.renderKey; switch (dynamicList.DataType) { case 1: // SQL数据 { _dataInterfaceService.ReplaceParameterValue(dynamicList, new Dictionary()); var pObj = await _dataInterfaceService.GetData(dynamicList); list = pObj.ToJsonString().ToObject>>(); } break; case 2: // 静态数据 { foreach (var data in JValue.Parse(dynamicList.Query)) { Dictionary dic = new Dictionary(); dic[propsValue] = data.Value(propsValue); dic[propsLabel] = data.Value(propsLabel); list.Add(dic); if (children != null && data.Value(children) != null && data.Value(children).ToString() != "") list.AddRange(GetDynamicInfiniteData(data.Value(children).ToString(), item.props.props)); } } break; case 3: // Api数据 { var result = await GetApiDataByTypePreview(dynamicList); // 请求接口 list = result.ContainsKey("list") ? result["list"].ToObject>>() : new List>(); } break; } } break; } resData.Add(item.__vModel__, list); } } } break; case JnpfKeyConst.POPUPTABLESELECT: { if (!resData.ContainsKey(item.__vModel__)) { var popDataList = await GetDynamicList(item); resData.Add(item.__vModel__, popDataList); } } break; case JnpfKeyConst.USERSELECT: { if (!resData.ContainsKey(item.__vModel__)) { if (item.selectType.Equals("all")) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new UserEntity() { Id = x.Id, Account = x.Account }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.Account); addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } else if (item.selectType.Equals("custom")) { var userIdList = await _visualDevRepository.AsSugarClient().Queryable() .WhereIF(item.ableUserIds.Any(), x => item.ableUserIds.Contains(x.UserId) || item.ableDepIds.Contains(x.ObjectId) || item.ablePosIds.Contains(x.ObjectId) || item.ableRoleIds.Contains(x.ObjectId) || item.ableGroupIds.Contains(x.ObjectId)).Select(x => x.UserId).ToListAsync(); var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null && userIdList.Contains(x.Id)) .Select(x => new UserEntity() { Id = x.Id, Account = x.Account }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.Account); if (!addItem.Any(x => x.ContainsKey(item.Id))) addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } } } break; case JnpfKeyConst.USERSSELECT: { if (!resData.ContainsKey(item.__vModel__)) { if (item.selectType.Equals("all")) { if (item.multiple) { (await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new { x.Id, x.RealName, x.Account }).ToListAsync()).ForEach(item => { Dictionary user = new Dictionary(); user.Add(item.Id + "--user", item.RealName + "/" + item.Account); addItem.Add(user); }); var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null) .Select(x => new OrganizeEntity { Id = x.Id, OrganizeIdTree = x.OrganizeIdTree, FullName = x.FullName, EnCode = x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary user = new Dictionary(); user.Add(item.Id + "--department", item.FullName + "/" + item.EnCode); addItem.Add(user); if (item.OrganizeIdTree.IsNullOrEmpty()) item.OrganizeIdTree = item.Id; var orgNameList = new List(); item.OrganizeIdTree.Split(",").ToList().ForEach(it => { var org = dataList.Find(x => x.Id == it); if (org != null) orgNameList.Add(org.FullName); }); Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id + "--company", string.Join("/", orgNameList)); addItem.Add(dictionary); }); (await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new { x.Id, x.FullName, x.EnCode }).ToListAsync()).ForEach(item => { Dictionary user = new Dictionary(); user.Add(item.Id + "--role", item.FullName + "/" + item.EnCode); addItem.Add(user); }); (await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new { x.Id, x.FullName, x.EnCode }).ToListAsync()).ForEach(item => { Dictionary user = new Dictionary(); user.Add(item.Id + "--position", item.FullName + "/" + item.EnCode); addItem.Add(user); }); (await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new { x.Id, x.FullName, x.EnCode }).ToListAsync()).ForEach(item => { Dictionary user = new Dictionary(); user.Add(item.Id + "--group", item.FullName + "/" + item.EnCode); addItem.Add(user); }); } else { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new UserEntity() { Id = x.Id, Account = x.Account }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id + "--user", item.Account); if (!addItem.Any(x => x.ContainsKey(item.Id))) addItem.Add(dictionary); }); } resData.Add(item.__vModel__, addItem); } else if (item.selectType.Equals("custom")) { if (item.ableIds.Any()) { var newAbleIds = new List(); item.ableIds.ForEach(x => newAbleIds.Add(x.Split("--").FirstOrDefault())); var userIdList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => newAbleIds.Contains(x.UserId) || newAbleIds.Contains(x.ObjectId)).Select(x => x.UserId).ToListAsync(); var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => userIdList.Contains(x.Id)).Select(x => new UserEntity() { Id = x.Id, Account = x.Account }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id + "--user", item.Account); if (!addItem.Any(x => x.ContainsKey(item.Id))) addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } } } } break; case JnpfKeyConst.DEPSELECT: { if (!resData.ContainsKey(item.__vModel__)) { if (item.selectType.Equals("all")) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).Select(x => new { x.Id, x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } else if (item.selectType.Equals("custom")) { if (item.ableDepIds.Any()) { var listQuery = new List>(); item.ableDepIds.ForEach(x => listQuery.Add(_visualDevRepository.AsSugarClient().Queryable().Where(xx => xx.OrganizeIdTree.Contains(x)))); var dataList = await _visualDevRepository.AsSugarClient().UnionAll(listQuery).Where(x => x.DeleteMark == null).Select(x => new { x.Id, x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); if (!addItem.Any(x => x.ContainsKey(item.Id))) addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } } } } break; case JnpfKeyConst.POSSELECT: { if (!resData.ContainsKey(item.__vModel__)) { if (item.selectType.Equals("all")) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null).Select(x => new PositionEntity() { Id = x.Id, EnCode = x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } else if (item.selectType.Equals("custom")) { if (item.ableDepIds.Any()) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null && item.ableDepIds.Contains(x.OrganizeId)) .Select(x => new PositionEntity() { Id = x.Id, EnCode = x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); addItem.Add(dictionary); }); resData.Add(item.__vModel__, addItem); } if (item.ablePosIds.Any()) { var dataList = await _visualDevRepository.AsSugarClient().Queryable().Where(x => x.DeleteMark == null && item.ablePosIds.Contains(x.Id)) .Select(x => new PositionEntity() { Id = x.Id, EnCode = x.EnCode }).ToListAsync(); dataList.ForEach(item => { Dictionary dictionary = new Dictionary(); dictionary.Add(item.Id, item.EnCode); addItem.Add(dictionary); }); if (resData.ContainsKey(item.__vModel__)) { var newAddItem = new List>(); foreach (var it in addItem) { var tempIt = it.FirstOrDefault().Value; if (tempIt.IsNotEmptyOrNull() && !resData[item.__vModel__].Any(x => x.ContainsValue(tempIt))) newAddItem.Add(it); } resData[item.__vModel__].AddRange(newAddItem); } else resData.Add(item.__vModel__, addItem); } } } } break; } } listFieldsModel.Where(x => x.__config__.jnpfKey.Equals(JnpfKeyConst.TABLE)).ToList().ForEach(async item => { var res = await GetCDataList(item.__config__.children, resData); if (res.Any()) foreach (var it in res) if (!resData.ContainsKey(it.Key)) resData.Add(it.Key, it.Value); }); return resData; } /// /// 导入数据组装. /// /// 控件列表. /// 导入数据列表. /// 控件解析缓存数据. /// private async Task>> ImportDataAssemble(List fieldsModelList, List> dataList, Dictionary>> cDataList) { var errorKey = "errorsInfo"; UserEntity? userInfo = _userManager.User; var resList = new List>(); foreach (var dataItems in dataList) { var newDataItems = dataItems.Copy(); foreach (var item in dataItems) { var vModel = fieldsModelList.Find(x => x.__vModel__.Equals(item.Key)); if (vModel == null) continue; var dicList = new List>(); if (cDataList.ContainsKey(vModel.__config__.jnpfKey)) dicList = cDataList[vModel.__config__.jnpfKey]; if ((dicList == null || !dicList.Any()) && cDataList.ContainsKey(vModel.__vModel__)) dicList = cDataList[vModel.__vModel__]; switch (vModel.__config__.jnpfKey) { case JnpfKeyConst.DATE: try { if (item.Value.IsNotEmptyOrNull()) { var date = DateTime.Parse(item.Value.ToString()); newDataItems[item.Key] = date.ParseToUnixTime().ToString(); } } catch { var errorInfo = vModel.__config__.label + ": 日期格式错误"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } break; case JnpfKeyConst.TIME: // 时间选择 try { if (item.Value.IsNotEmptyOrNull()) { var timeRange = item.Value.ToString(); string? udate = string.Format("{0:yyyy-MM-dd}", DateTime.MaxValue); DateTime.Parse(udate + " " + timeRange); newDataItems[item.Key] = item.Value.ToString(); } } catch { var errorInfo = vModel.__config__.label + ": 时间格式错误"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } break; case JnpfKeyConst.COMSELECT: case JnpfKeyConst.ADDRESS: { if (item.Value.IsNotEmptyOrNull()) { if (vModel.multiple) { var addList = new List(); item.Value.ToString().Split(",").ToList().ForEach(it => { if (vModel.__config__.jnpfKey.Equals(JnpfKeyConst.COMSELECT) || (it.Count(x => x == '/') == vModel.level || (vModel.level == 3 && it.Count(x => x == '/') == 2 && it.Contains("市辖区")))) { if (dicList.Where(x => x.ContainsValue(it)).Any()) { var value = dicList.Where(x => x.ContainsValue(it)).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key.Split(",").ToList()); } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } }); newDataItems[item.Key] = addList; } else { if (vModel.__config__.jnpfKey.Equals(JnpfKeyConst.COMSELECT) || (item.Value?.ToString().Count(x => x == '/') == vModel.level || (vModel.level == 3 && item.Value.ToString().Count(x => x == '/') == 2 && item.Value.ToString().Contains("市辖区")))) { if (dicList.Where(x => x.ContainsValue(item.Value?.ToString())).Any()) { var value = dicList.Where(x => x.ContainsValue(item.Value?.ToString())).FirstOrDefault().FirstOrDefault(); newDataItems[item.Key] = value.Key.Split(",").ToList(); } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } } break; case JnpfKeyConst.CHECKBOX: case JnpfKeyConst.SWITCH: case JnpfKeyConst.SELECT: case JnpfKeyConst.RADIO: { if (item.Value.IsNotEmptyOrNull()) { if (vModel.multiple || vModel.__config__.jnpfKey.Equals(JnpfKeyConst.CHECKBOX)) { var addList = new List(); item.Value.ToString().Split(",").ToList().ForEach(it => { if (dicList.Where(x => x.ContainsValue(it)).Any()) { if (dicList.Count(x => x.ContainsValue(it)) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it)).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } }); newDataItems[item.Key] = addList; } else { if (dicList.Where(x => x.ContainsValue(item.Value.ToString())).Any()) { if (dicList.Count(x => x.ContainsValue(item.Value.ToString())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(item.Value?.ToString())).FirstOrDefault().FirstOrDefault(); newDataItems[item.Key] = value.Key; } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } } break; case JnpfKeyConst.DEPSELECT: case JnpfKeyConst.POSSELECT: case JnpfKeyConst.GROUPSELECT: case JnpfKeyConst.ROLESELECT: case JnpfKeyConst.USERSELECT: { if (item.Value.IsNotEmptyOrNull()) { if (vModel.multiple) { var addList = new List(); item.Value.ToString().Split(",").ToList().ForEach(it => { if (dicList.Where(x => x.ContainsValue(it.Split("/").Last())).Any()) { if (dicList.Count(x => x.ContainsValue(it.Split("/").Last())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it.Split("/").Last())).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } }); newDataItems[item.Key] = addList; } else { if (dicList.Where(x => x.ContainsValue(item.Value.ToString().Split("/").Last())).Any()) { if (dicList.Count(x => x.ContainsValue(item.Value.ToString().Split("/").Last())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(item.Value?.ToString().Split("/").Last())).FirstOrDefault().FirstOrDefault(); newDataItems[item.Key] = value.Key; } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } } break; case JnpfKeyConst.USERSSELECT: { if (item.Value.IsNotEmptyOrNull()) { if (vModel.multiple) { var addList = new List(); item.Value.ToString().Split(",").ToList().ForEach(it => { if (dicList.Where(x => x.ContainsValue(it)).Any()) { if (dicList.Count(x => x.ContainsValue(it)) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it)).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key); } } else { if (dicList.Where(x => x.ContainsValue(it.Split("/").Last())).Any()) { if (dicList.Count(x => x.ContainsValue(it.Split("/").Last())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it.Split("/").Last())).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } }); newDataItems[item.Key] = addList; } else { if (dicList.Where(x => x.ContainsValue(item.Value.ToString())).Any()) { if (dicList.Count(x => x.ContainsValue(item.Value.ToString())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(item.Value?.ToString())).FirstOrDefault().FirstOrDefault(); newDataItems[item.Key] = value.Key; } } else { if (dicList.Where(x => x.ContainsValue(item.Value.ToString().Split("/").Last())).Any()) { if (dicList.Count(x => x.ContainsValue(item.Value.ToString().Split("/").Last())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(item.Value?.ToString().Split("/").Last())).FirstOrDefault().FirstOrDefault(); newDataItems[item.Key] = value.Key; } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } } } break; case JnpfKeyConst.TREESELECT: { if (item.Value.IsNotEmptyOrNull()) { if (vModel.multiple) { var addList = new List(); item.Value.ToString().Split(",").ToList().ForEach(it => { if (dicList.Where(x => x.ContainsValue(it)).Any()) { if (dicList.Count(x => x.ContainsValue(it)) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it)).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } }); newDataItems[item.Key] = addList; } else { if (dicList.Where(x => x.ContainsValue(item.Value.ToString())).Any()) { if (dicList.Count(x => x.ContainsValue(item.Value.ToString())) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(item.Value?.ToString())).FirstOrDefault().FirstOrDefault(); newDataItems[item.Key] = value.Key; } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } } break; case JnpfKeyConst.CASCADER: { if (item.Value.IsNotEmptyOrNull()) { if (vModel.props.props.multiple) { var addsList = new List(); item.Value.ToString().Split(",").ToList().ForEach(its => { var txtList = its.Split(vModel.separator).ToList(); var add = new List(); txtList.ForEach(it => { if (dicList.Where(x => x.ContainsValue(it)).Any()) { if (dicList.Count(x => x.ContainsValue(it)) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it)).FirstOrDefault().FirstOrDefault(); add.Add(value.Key); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } }); addsList.Add(add); }); newDataItems[item.Key] = addsList; } else { var txtList = item.Value.ToString().Split(vModel.separator).ToList(); var addList = new List(); txtList.ForEach(it => { if (dicList.Where(x => x.ContainsValue(it)).Any()) { if (dicList.Count(x => x.ContainsValue(it)) > 1) { var errorInfo = vModel.__config__.label + ": 存在多条值-无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } else { var value = dicList.Where(x => x.ContainsValue(it)).FirstOrDefault().FirstOrDefault(); addList.Add(value.Key); } } else { var errorInfo = vModel.__config__.label + ": 值无法匹配"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } }); newDataItems[item.Key] = addList; } } } break; case JnpfKeyConst.TABLE: { if (item.Value != null) { var valueList = item.Value.ToObject>>(); var newValueList = new List>(); valueList.ForEach(it => { var addValue = new Dictionary(); foreach (var value in it) addValue.Add(vModel.__vModel__ + "-" + value.Key, value.Value); newValueList.Add(addValue); }); var res = await ImportDataAssemble(vModel.__config__.children, newValueList, cDataList); if (res.Any(x => x.ContainsKey(errorKey))) { if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + res.FirstOrDefault(x => x.ContainsKey(errorKey))[errorKey].ToString(); else newDataItems.Add(errorKey, res.FirstOrDefault(x => x.ContainsKey(errorKey))[errorKey].ToString()); res.Remove(res.FirstOrDefault(x => x.ContainsKey(errorKey))); } var result = new List>(); res.ForEach(it => { var addValue = new Dictionary(); foreach (var value in it) addValue.Add(value.Key.Replace(vModel.__vModel__ + "-", string.Empty), value.Value); result.Add(addValue); }); newDataItems[item.Key] = result; } } break; case JnpfKeyConst.RATE: if (item.Value.IsNotEmptyOrNull()) { try { var value = int.Parse(item.Value.ToString()); if (vModel.max != null) { if (vModel.max < value) { var errorInfo = vModel.__config__.label + ": 评分超过设置的最大值"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } catch { var errorInfo = vModel.__config__.label + ": 评分格式错误"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } break; case JnpfKeyConst.SLIDER: if (item.Value.IsNotEmptyOrNull()) { try { var value = int.Parse(item.Value.ToString()); if (vModel.max != null) { if (vModel.max < value) { var errorInfo = vModel.__config__.label + ": 滑块超过设置的最大值"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } if (vModel.min != null) { if (vModel.min > value) { var errorInfo = vModel.__config__.label + ": 滑块超过设置的最小值"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } catch { var errorInfo = vModel.__config__.label + ": 滑块格式错误"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } break; case JnpfKeyConst.NUMINPUT: if (item.Value.IsNotEmptyOrNull()) { try { var value = int.Parse(item.Value.ToString()); if (vModel.max != null) { if (vModel.max < value) { var errorInfo = vModel.__config__.label + ": 数字输入超过设置的最大值"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } if (vModel.min != null) { if (vModel.min > value) { var errorInfo = vModel.__config__.label + ": 数字输入超过设置的最小值"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } } catch { var errorInfo = vModel.__config__.label + ": 数字输入格式错误"; if (newDataItems.ContainsKey(errorKey)) newDataItems[errorKey] = newDataItems[errorKey] + "," + errorInfo; else newDataItems.Add(errorKey, errorInfo); } } break; } } // 系统自动生成控件 foreach (var item in dataItems) { if (newDataItems.ContainsKey(errorKey)) continue; // 如果存在错误信息 则 不生成 var vModel = fieldsModelList.Find(x => x.__vModel__.Equals(item.Key)); if (vModel == null) continue; switch (vModel.__config__.jnpfKey) { case JnpfKeyConst.BILLRULE: string billNumber = await _billRuleService.GetBillNumber(vModel.__config__.rule); if (!"单据规则不存在".Equals(billNumber)) newDataItems[item.Key] = billNumber; else newDataItems[item.Key] = string.Empty; break; case JnpfKeyConst.MODIFYUSER: newDataItems[item.Key] = string.Empty; break; case JnpfKeyConst.CREATEUSER: newDataItems[item.Key] = userInfo.Id; break; case JnpfKeyConst.MODIFYTIME: newDataItems[item.Key] = string.Empty; break; case JnpfKeyConst.CREATETIME: newDataItems[item.Key] = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now); break; case JnpfKeyConst.CURRPOSITION: string? pid = await _visualDevRepository.AsSugarClient().Queryable((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.PositionId)) .Where((a, b) => a.Id == userInfo.Id && a.DeleteMark == null).Select((a, b) => a.PositionId).FirstAsync(); if (pid.IsNotEmptyOrNull()) newDataItems[item.Key] = pid; else newDataItems[item.Key] = string.Empty; break; case JnpfKeyConst.CURRORGANIZE: if (userInfo.OrganizeId != null) newDataItems[item.Key] = userInfo.OrganizeId; else newDataItems[item.Key] = string.Empty; break; } } if (newDataItems.ContainsKey(errorKey)) { if (dataItems.ContainsKey(errorKey)) dataItems[errorKey] = newDataItems[errorKey].ToString(); else dataItems.Add(errorKey, newDataItems[errorKey]); resList.Add(dataItems); } else { resList.Add(newDataItems); } } return resList; } /// /// 处理静态数据. /// /// /// private List> GetStaticList(FieldsModel model) { PropsBeanModel? props = model.props.props; List? optionList = GetTreeOptions(model.options, props); List> list = new List>(); foreach (OptionsModel? item in optionList) { Dictionary option = new Dictionary(); option.Add(item.value, item.label); list.Add(option); } return list; } /// /// options无限级. /// /// private List GetTreeOptions(List model, PropsBeanModel props) { List options = new List(); foreach (object? item in model) { OptionsModel option = new OptionsModel(); Dictionary? dicObject = item.ToJsonString().ToObject>(); option.label = dicObject[props.label].ToString(); option.value = dicObject[props.value].ToString(); if (dicObject.ContainsKey(props.children)) { List? children = dicObject[props.children].ToJsonString().ToObject>(); options.AddRange(GetTreeOptions(children, props)); } options.Add(option); } return options; } /// /// 获取动态无限级数据. /// /// /// /// private List> GetDynamicInfiniteData(string data, PropsBeanModel props) { List> list = new List>(); string? value = props.value; string? label = props.label; string? children = props.children; foreach (JToken? info in JToken.Parse(data)) { Dictionary dic = new Dictionary(); dic[info.Value(value)] = info.Value(label); list.Add(dic); if (info.Value(children) != null && info.Value(children).ToString() != string.Empty) list.AddRange(GetDynamicInfiniteData(info.Value(children).ToString(), props)); } return list; } /// /// 处理远端数据. /// /// /// private async Task>> GetDynamicList(FieldsModel model) { List> list = new List>(); // 获取远端数据 DataInterfaceEntity? dynamic = await _dataInterfaceService.GetInfo(model.__config__.propsUrl); if (dynamic == null) return list; var propsValue = string.Empty; var propsLabel = string.Empty; var children = string.Empty; if (model.__config__.jnpfKey.Equals(JnpfKeyConst.TREESELECT) || model.__config__.jnpfKey.Equals(JnpfKeyConst.CASCADER)) { propsValue = model.props.props.value; propsLabel = model.props.props.label; children = model.props.props.children; } else { propsValue = model.__config__.props.value; propsLabel = model.__config__.props.label; children = model.__config__.props.children; } switch (dynamic.DataType) { // SQL数据 case 1: { // 远端数据 配置参数 List? parameter = new List(); if (_userManager.ToKen != null) { parameter.Add(new SugarParameter("@user", _userManager.UserId)); parameter.Add(new SugarParameter("@organization", _userManager?.User?.OrganizeId)); var subordinates = _userManager.Subordinates; subordinates.Add(_userManager.UserId); parameter.Add(new SugarParameter("@currentUsersAndSubordinates", subordinates)); var subsidiary = _userManager.Subsidiary; subsidiary.Add(_userManager.User.OrganizeId); parameter.Add(new SugarParameter("@currentOrganizationAndSuborganization", subsidiary)); var chargeorganization = _userManager.DataScope.Where(x => x.organizeId == _userManager.User.OrganizeId && x.Select).ToList().FirstOrDefault(); parameter.Add(new SugarParameter("@chargeorganization", chargeorganization?.organizeId)); subsidiary = _userManager.DataScope.Select(x => x.organizeId).Intersect(_userManager.Subsidiary).ToList(); parameter.Add(new SugarParameter("@currentChargeorganizationAndSuborganization", subsidiary)); } DbLinkEntity? linkEntity = await _visualDevRepository.AsSugarClient().Queryable().Where(m => m.Id == dynamic.DBLinkId && m.DeleteMark == null).FirstAsync(); if (linkEntity == null) linkEntity = _databaseService.GetTenantDbLink(_userManager.TenantId, _userManager.TenantDbName); _dataInterfaceService.ReplaceParameterValue(dynamic, new Dictionary()); System.Data.DataTable? dt = _databaseService.GetInterFaceData(linkEntity, dynamic.Query, parameter.ToArray()); List> dynamicDataList = dt.ToJsonString().ToObject>>(); foreach (Dictionary? item in dynamicDataList) { Dictionary dynamicDic = new Dictionary(); dynamicDic.Add(item[propsValue]?.ToString(), item[propsLabel]?.ToString()); list.Add(dynamicDic); } } break; // 静态数据 case 2: { foreach (var data in JValue.Parse(dynamic.Query)) { Dictionary dic = new Dictionary(); dic[data.Value(propsValue)] = data.Value(propsLabel); list.Add(dic); if (data.Value(children) != null && data.Value(children).ToString().IsNotEmptyOrNull()) list.AddRange(GetDynamicInfiniteData(data.Value(children).ToString(), model.props.props)); } } break; // Api数据 case 3: { // 获取远端数据 var dynamicList = await _dataInterfaceService.GetInfo(model.__config__.propsUrl); if (dynamicList == null) break; var redisName = CommonConst.VISUALDEV + _userManager.TenantId + "_" + model.__config__.jnpfKey + "_" + model.__config__.renderKey; switch (dynamicList.DataType) { case 1: // SQL数据 { _dataInterfaceService.ReplaceParameterValue(dynamicList, new Dictionary()); var pObj = await _dataInterfaceService.GetData(dynamicList); list = pObj.ToJsonString().ToObject>>(); } break; case 2: // 静态数据 { foreach (var data in JValue.Parse(dynamicList.Query)) { Dictionary dic = new Dictionary(); dic[propsValue] = data.Value(propsValue); dic[propsLabel] = data.Value(propsLabel); list.Add(dic); if (data.Value(children) != null && data.Value(children).ToString() != "") list.AddRange(GetDynamicInfiniteData(data.Value(children).ToString(), model.props.props)); } } break; case 3: // Api数据 { var result = await GetApiDataByTypePreview(dynamicList); // 请求接口 list = result.ContainsKey("list") ? result["list"].ToObject>>() : new List>(); } break; } } break; } return list; } /// /// 根据不同规则请求接口(预览). /// /// /// private async Task GetApiDataByTypePreview(DataInterfaceEntity entity) { var result = new JObject(); var parameters = entity.RequestParameters.ToObject>(); var parametersHerader = entity.RequestHeaders.ToObject>(); var dic = new Dictionary(); var dicHerader = new Dictionary(); dicHerader.Add("JNPF_API", true); if (_userManager.ToKen != null && !_userManager.ToKen.Contains("::")) dicHerader.Add("Authorization", _userManager.ToKen); foreach (var key in parameters) { dic.Add(key.field, key.defaultValue); } foreach (var key in parametersHerader) { dicHerader[key.field] = key.defaultValue; } switch (entity.RequestMethod) { case "6": result = (await entity.Path.SetHeaders(dicHerader).SetQueries(dic).GetAsStringAsync()).ToObject(); break; case "7": result = (await entity.Path.SetHeaders(dicHerader).SetBody(dic).PostAsStringAsync()).ToObject(); break; } return result; } /// /// 递归获取手动添加的省市区,名称处理成树形结构. /// /// private string GetAddressByPList(List addressEntityList, ProvinceEntity pEntity) { if (pEntity.ParentId == null || pEntity.ParentId.Equals("-1")) { return pEntity.FullName; } else { var pItem = addressEntityList.Find(x => x.Id == pEntity.ParentId); if (pItem != null) pEntity.QuickQuery = GetAddressByPList(addressEntityList, pItem) + "/" + pEntity.FullName; else pEntity.QuickQuery = pEntity.FullName; return pEntity.QuickQuery; } } /// /// 递归获取手动添加的省市区,Id处理成树形结构. /// /// private string GetAddressIdByPList(List addressEntityList, ProvinceEntity pEntity) { if (pEntity.ParentId == null || pEntity.ParentId.Equals("-1")) { return pEntity.Id; } else { var pItem = addressEntityList.Find(x => x.Id == pEntity.ParentId); if (pItem != null) pEntity.Id = GetAddressIdByPList(addressEntityList, pItem) + "," + pEntity.Id; else pEntity.Id = pEntity.Id; return pEntity.Id; } } #endregion } }