using NCC.Common.Core.Manager; using NCC.Common.Extension; using NCC.Common.FileManage; using NCC.Common.Filter; using NCC.Common.Helper; using NCC.Dependency; using NCC.DynamicApiController; using NCC.Extend.Entitys.common_extend; using NCC.Extend.Entitys.Dto.Order; using NCC.Extend.Entitys.Model; using NCC.LinqBuilder; using NCC.System.Entitys.Permission; using NCC.System.Interfaces.Permission; using NCC.System.Interfaces.System; using Mapster; using Microsoft.AspNetCore.Mvc; using SqlSugar; using SqlSugar.IOC; using System; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Yitter.IdGenerator; using NCC.Code; using NCC.FriendlyException; using NCC.Common.Enum; using NCC.Extend.Entitys.Dto; using NCC.Common.Extensions; using NCC.Common; using System.Linq.Expressions; using NCC.System.Interfaces.Common; using NCC.Extend.Entitys.Dto.Document; using NCC.Common.Model.NPOI; using NCC.Common.Configuration; using NCC.DataEncryption; using Microsoft.Extensions.Logging; using Serilog; using NCC.Logging; namespace NCC.Extend { ///     /// 订单管理     /// 版 本:V1.20.15     /// 版 权:Wesley(https://www.NCCsoft.com)     /// 作 者:NCC开发平台组     /// 日 期:2022-03-16     /// [ApiDescriptionSettings(Tag = "演示", Name = "Demo", Order = 200)] [Route("api/extend/[controller]")] public class DemoService : IDynamicApiController, ITransient { private readonly IFileService _fileService; private readonly ISqlSugarRepository _demoRepository; private readonly ISqlSugarRepository _orderRepository; private readonly IUserManager _userManager; // 用户管理 private readonly IUsersService _usersService; //用户服务 private readonly IAuthorizeService _authorizeService; private readonly ILogger _logger; private readonly SqlSugarScope db;// 核心对象:拥有完整的SqlSugar全部功能 /// /// 初始化一个类型的演示实例 /// public DemoService(ISqlSugarRepository demoRepository, ISqlSugarRepository orderRepository, IFileService fileService, IUserManager userManager, IUsersService usersService, IAuthorizeService authorizeService, ILogger logger) { _orderRepository = orderRepository; _demoRepository = demoRepository; db = demoRepository.Context; _userManager = userManager; _usersService = usersService; _authorizeService = authorizeService; _fileService = fileService; _logger = logger; } //数据库初始化 创建表 实体类实现 DTO 映射 //依赖注入 & 直接调用 (基于接口) //模块化 和定义标准 (暂不集成网关) //接口 注释 swagger //匿名接口 AllowAnonymous 私有不暴露的方法 [NonAction] //实体转换 Mapster Adapt用法 public void Test() { Log.Debug("wesley Debugger;"); //Log.Information("hellow!"); //_logger.LogDebug("_wesley LogDebug"); //_logger.LogInformation("_wesley LogInformation"); //_logger.LogWarning("_wesley LogWarning"); //_logger.LogError("_wesley LogError"); } /// /// 一些 比较好 的溧子 /// /// public async Task DemoYYDS() { //自定义配置节点信息 //var setting = App.GetConfig("AntisSoftSettings", true); #region 登录用户获取 ////当前用户ID(登录信息中取) //string cuserid = _userManager.UserId; ////获取当前用户 优先从缓存中取 泛型对象《UserInfo》 //var cuser = _userManager.GetUserInfo(); ////从数据库取(无缓存) //var cuser1 = _userManager.User; #endregion //基础新增 删除 修改 查询 //YitIdHelper.NextId().ToString() #region 新增 #region 插入单个 ////插入单条 //db.Insertable(new DemoEntity() //{ // Id = "antis", // CustomerName = "110", // Age = 100, // Sex = "男", // CreatorTime = DateTime.Now, // CreatorUserId = "1111", // DeleteMark = 0, // OrderDate = DateTime.Now //}).ExecuteCommand(); //db.Insertable(new //{ // Id = "222", // CustomerName = "222", // Age = 200, // Sex = "男", // CreatorTime = DateTime.Now, // CreatorUserId = "1111", // DeleteMark = 0, // OrderDate = DateTime.Now //}).ExecuteCommand(); #endregion #region 批量Insert //List demolist = new List() { // new DemoEntity() { // Id = "333", // CustomerName = "333", // Age = 200, // Sex = "男", // CreatorTime = DateTime.Now, // CreatorUserId = "333", // DeleteMark = 0, // OrderDate = DateTime.Now // }, // new DemoEntity() { // Id = "4444", // CustomerName = "444", // Age = 200, // Sex = "男", // CreatorTime = DateTime.Now, // CreatorUserId = "4444", // DeleteMark = 0, // OrderDate = DateTime.Now // }}; //await db.Insertable(demolist.ToArray()).ExecuteCommandAsync(); #endregion #endregion #region 删除 ////实体删除 需要设置主键 //db.Deleteable().Where(new DemoEntity() { Id = "666" }).ExecuteCommand(); ////主键包含删除 //db.Deleteable().In(new string[] { "777", "888" }).ExecuteCommand(); ////指定条件删除 //db.Deleteable().Where(it => it.Id == "333").ExecuteCommand(); //// 子查询删除 //db.Deleteable().Where(p => p.Id == SqlFunc.Subqueryable().Where(s => s.Id == p.ReId).Select(s => s.Id)).ExecuteCommand() #endregion #region 修改 ////拿到一个信息 //var entity = await _demoRepository.FirstOrDefaultAsync(o => o.Id == "111"); ////1.单个修改 //entity.CustomerName += "_new"; ////直接修改(不等待) //_demoRepository.Context.Updateable(entity).ExecuteCommand(); ////指定需要修改的字段 //var isOk = await _demoRepository.Context //.Updateable(entity) //.IgnoreColumns(ignoreAllNullColumns: true) //按需加载 排除 null值的字段 //.CallEntityMethod(m => m.LastModify()) //.UpdateColumns(o => new { o.CustomerName, o.LastModifyTime, o.LastModifyUserId }) //.ExecuteCommandAsync(); //if (isOk < 1) // throw NCCException.Oh(ErrorCode.COM1001); ////2.批量修改 按条件 //List ids = new List { "111", "222" }; //var isOk1 = await db.Updateable() // .SetColumns(x => new DemoEntity() //指定要修改的信息 // { // DeleteMark = 1,//删除 // DeleteTime = null, // DeleteUserId = null // }) // .Where(o => ids.Contains(o.Id)) // .ExecuteCommandAsync(); //if (isOk1 < 1) // throw NCCException.Oh(ErrorCode.COM1001); #endregion #region 查询 //查询表的所有 //var list = db.Queryable().ToList(); //string keyword = "antis"; ////条件查询 和 条件判断 //var qlist = db.Queryable() // .Where(o => o.Id != "111") // //动态 条件筛选 // .WhereIF(!keyword.IsNullOrEmpty(), o => o.CustomerName.Contains(keyword)) // .WhereIF(keyword.IsNullOrEmpty(), o => o.CustomerName == null || o.CustomerName != "") // .ToList(); //分组取第一条,部分数据库支持 //var list3 = db.Queryable() //.PartitionBy(it => new { it.Age, it.CustomerName }).Take(1).ToList(); ////快速多表查询 //var list = db.Queryable((o, u, d) => o.CreatorUserId == u.Id && u.Id == d.ReId) // .Select((o, u, d) => new OrderInfoOutput // { // customerId = SqlFunc.GetSelfAndAutoFill(o.Id), // customerName = d.CustomerName //[d].[Name] AS [CustomName] // }) // .ToList(); ////sql 语句 直接查询 //int total = 0; //db.SqlQueryable("select * from OrderEntity").OrderBy("id asc").ToPageList(1, 2, ref total); //简介联表查询 //var queryorder = db.Queryable() //.LeftJoin((o, d) => o.Id == d.ReId)//多个条件用&& //.LeftJoin((o, d, u) => o.CreatorUserId == u.CreatorUserId) //.Where((o,d1,u) => o.Id == "112233" ) //.Select(o => o) //.ToList(); //复杂组合查询 //Case when // SqlFunc.IF(st.Id > 1) //.Return(st.Id) //.ElseIF(st.Id == 1) //.Return(st.SchoolId).End(st.Id) //等于 ////Left Join 连表查询 //var oneClass = db.Queryable((o, i, c) => new JoinQueryInfos( //JoinType.Left, o.CreatorUserId == i.Id, //JoinType.Left, o.Id == c.ReId //)) //.Select((o, i, c) => new //{ // Id = SqlFunc.GetSelfAndAutoFill(o.Id),// o.* // CustomName = c.CustomerName //[c].[Name] AS [CustomName] //}).ToList(); ////多表联合查询 Join中Where用法 //var SearchList = db.Queryable((o, i, c) => new JoinQueryInfos( //JoinType.Left, o.CreatorUserId == i.Id, //JoinType.Left, o.Id == c.ReId //)) //.Where(o => o.CustomerName.Contains("Antis")) //只用到o这样写就行 //.Where((o, i) => i.Account.Contains("Antis")) //如果用到i需要这么写 //.Select((o, i, c) => new //{ // Id = SqlFunc.GetSelfAndAutoFill(o.Id),// o.* // CustomName = c.CustomerName //[c].[Name] AS [CustomName] //}).ToList() //两个queryable查询 把一个单 表查询和一个多表查询在进行了一次Join操作 //var query1 = db.Queryable((d, user) => new JoinQueryInfos( //JoinType.Left, d.CreatorUserId == user.Id //)) //.Where(st => st.CustomerName.Contains("antis")); //var query2 = db.Queryable().Where(o => o.DeleteMark == 0); //db.Queryable(query1, query2, (p1, p2) => p1.CreatorUserId == p2.CreatorUserId).Select((d1, d2) => new DemoEntity //{ // //....赋值 //}) //.ToPagedList(1, 10); //也可分页 ////1.判断是否存在 //bool exists1 = db.Queryable().Any(q => q.CustomerName == "YYDS"); //Console.WriteLine(exists1); ////2.模糊查询,含有 //List contains1 = db.Queryable() // .Where(q => q.CustomerName.Contains("antis")) // .ToList(); //Console.WriteLine(contains1.ToJson()); ////以End王结尾 //List end1 = db.Queryable() // .Where(q => q.CustomerName.EndsWith("End王")) // .ToList(); //Console.WriteLine(end1.ToJson()); ////3. in关键词查询 //string[] idList = new string[] { "111", "222" }; //List in1 = db.Queryable() // .In(q => q.Id, idList) // .ToList(); //Console.WriteLine(in1.ToJson()); //List in2 = db.Queryable() // .Where(q => idList.Equals(q.Id)) // .ToList(); //Console.WriteLine(in2.ToJson()); ////1.获取总数 //int count = db.Queryable() // .Where(q => q.Sex == "男") // .Count(); //Console.WriteLine("count=" + count); ////2.获取最大值 //decimal maxDegree = db.Queryable() // .Where(q => q.Sex == "男") // .Max(q => q.Age) // .ObjToInt(); //Console.WriteLine("maxAge:" + maxDegree); ////3.获取最小值 //decimal minDegree = db.Queryable() // .Where(q => q.Sex == "男") // .Min(q => q.Age) // .ObjToInt(); //Console.WriteLine("minAge:" + minDegree); //var top10 = db.Queryable().Take(10).ToList();//查询前10 //获取第一个 //var getFirst = db.Queryable().First(it => it.Id == "111");//查询单条 //NoLock查询 //var getAllNoLock = db.Queryable().With(SqlWith.NoLock).ToList();//SqlServer 有效 #endregion #region 事务的实现 try { db.BeginTran(); for (int i = 0; i < 10; i++) { var isOk = await db.Insertable(new DemoEntity { Age = 10 + i, CustomerName = $"antis_{i}" }) .CallEntityMethod(m => m.Creator()) .CallEntityMethod(m => m.LastModify()) .ExecuteCommandAsync(); if (isOk < 1) { db.RollbackTran(); throw NCCException.Bah($"操作失败!"); } db.CommitTran(); } } catch (Exception ee) { db.RollbackTran(); throw NCCException.Bah($"操作失败!"); } #endregion #region 文件操作 上传 下载 //Uploader //Export #endregion #region excel导出 //Export #endregion } /// /// 复杂逻辑 SQL结果查询分页 /// /// /// public async Task GetTrashList([FromQuery] PageInputBase input) { var sidx = input.sidx.IsNullOrWhiteSpace() ? "Id" : input.sidx; string userid = _userManager.UserId; string strSql = $@" select * from ( select F_Id as Id,Name,F_LastModifyTime,Size,Extension,'folder' type,F_LastModifyTime LastModifyTime from disk_document_folder where F_DeleteMark = 1 and F_CREATORUSERID = '{userid}' union all select F_Id as Id, Name,F_LastModifyTime,Size,Extension,'file' type,F_LastModifyTime LastModifyTime from disk_document where F_DeleteMark = 1 and F_CREATORUSERID = '{userid}' ) T "; int total = 0; //table对象返回时得到总条数 var dt = await db.SqlQueryable(strSql) //.WhereIF(!input.keyword.IsNullOrEmpty(), m => m.Name.Contains(input.keyword)) .OrderBy(sidx + " " + input.sort) .ToPagedListAsync(input.currentPage, input.pageSize); //如果直接使用table对象 可用下列方法实现 //.ToDataTablePageAsync(input.currentPage, input.pageSize, total); //dt.DataTableToDicList(); var pageList = new SqlSugarPagedList() { list = dt.list, pagination = dt.pagination, //获取table对象后 需要主动构建 分页信息 //pagination = new PagedModel { // list = dt.list, // PageIndex = input.currentPage, // PageSize = input.pageSize, // Total = total //} }; return PageResult.SqlSugarPageResult(pageList); } /// /// 导出合作方信息 /// /// 请求参数 /// [HttpGet("Actions/Export")] public async Task Export([FromQuery] DemoQuery input) { var userInfo = await _userManager.GetUserInfo(); var exportData = db.Queryable().Where(o => o.CreatorUserId == "antis").ToList(); List paramList = new List(); ExcelConfig excelconfig = new ExcelConfig(); excelconfig.FileName = "AntisSoftExport.xls"; excelconfig.HeadFont = "微软雅黑"; excelconfig.HeadPoint = 10; excelconfig.IsAllSizeColumn = true; excelconfig.ColumnModel = new List(); excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "CustomerName", ExcelColumn = "我的名字" }); //...列配置 var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName; ExcelExportHelper.Export(exportData, excelconfig, addPath); var fileName = _userManager.UserId + "|" + addPath + "|xls"; var output = new { name = excelconfig.FileName, url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC") }; return output; } /// /// 上传文件 /// /// [HttpPost("Uploader")] public async Task Uploader([FromForm] DocumentUploaderInput input) { long Size = input.file.Length; var currentUser = _userManager.User; _fileService.UploadFile("document", input.file); //文件名(存文件名即可) string FileName = input.file.FileName; //获取路径 出去文件名的完整路径 string PrevPath = _fileService.GetPathByType("document"); //完整路径 string path = PrevPath + FileName; //缩略图生成 //FileHelper.MakeThumbnail(path, "新的路径", 100, 100, "W", "jpg", 0, 0); bool IsOk = false; //。。。。业务逻辑 if (!IsOk) throw NCCException.Oh(ErrorCode.D8001); } #region GET /// /// 列表 (带分页) /// /// /// [HttpGet("")] public async Task GetList([FromQuery] DemoQuery input) { var sidx = input.sidx.IsNullOrWhiteSpace() ? "F_CREATORTIME" : input.sidx; var list = await _demoRepository.Entities .Where(x => x.CreatorUserId == _userManager.UserId && (x.DeleteMark == null || x.DeleteMark == 0)) .WhereIF(!input.keyword.IsNullOrEmpty(), m => m.CustomerName.Contains(input.keyword) || m.Description.Contains(input.keyword)) .WhereIF(!input.CustomeName.IsNullOrEmpty(), m => m.CustomerName == input.CustomeName) .OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize); var pageList = new SqlSugarPagedList() { list = list.list.Adapt>(), pagination = list.pagination }; return PageResult.SqlSugarPageResult(pageList); } /// /// 信息 /// /// 主键值 /// [HttpGet("{id}")] public async Task GetInfo(string id) { return (await _demoRepository.FirstOrDefaultAsync(x => x.Id == id && x.DeleteMark == null)).Adapt(); } #endregion #region POST /// /// 新建 /// /// 请求参数 /// [HttpPost("")] public async Task Create([FromBody] DemoEntity input) { App.GetService().UseBillNumber("OrderNumber"); var orderEntity = input.Adapt(); orderEntity.Id = YitIdHelper.NextId().ToString(); if (await _demoRepository.AnyAsync(x => x.CustomerName == input.CustomerName && x.DeleteMark != 1)) throw NCCException.Oh(ErrorCode.COM1004); var entity = input.Adapt(); entity.DeleteMark = 0; var isOk = await _demoRepository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync(); if (isOk < 1) throw NCCException.Oh(ErrorCode.COM1000); } /// /// 更新 /// /// 请求参数 /// [HttpPut("{id}")] public async Task Update([FromBody] DemoEntity input) { var Entity = input.Adapt(); _demoRepository.Update(Entity); } /// /// 删除 /// /// 主键值 /// [HttpDelete("{id}")] public async Task Delete(string id) { var entity = await _demoRepository.FirstOrDefaultAsync(x => x.Id == id && x.DeleteMark == null); if (entity != null) { await _demoRepository.DeleteAsync(x => x.Id == id); } else throw NCCException.Oh(ErrorCode.COM1002); } #endregion } }