baotian
2024-06-04 b959135a1139fb66646523d92e5bd20c5910f283
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
using iWare.Wms.Core;
using Furion.ClayObject.Extensions;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using Yitter.IdGenerator;
 
namespace iWare.Wms.Application
{
    /// <summary>
    /// 通用方法
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TSearchDto"></typeparam>
    /// <typeparam name="TAddDto"></typeparam>
    /// <typeparam name="TUpdateDto"></typeparam>
    /// <typeparam name="TImportDto"></typeparam>
    /// <typeparam name="TDetailDto"></typeparam>
    /// <typeparam name="TPageListDto"></typeparam>
    /// <typeparam name="TExportDto"></typeparam>
    /// <typeparam name="TPrintDto"></typeparam>
    public class BaseService<TEntity, TSearchDto, TAddDto, TUpdateDto, TImportDto, TDetailDto, TPageListDto, TExportDto, TPrintDto>
        where TEntity : DEntityBase, new()
        where TUpdateDto : BaseDto
        where TSearchDto : PageInputBase
        where TPageListDto : new()
        where TExportDto : class, new()
        where TImportDto : class, new()
    {
        /// <summary>
        /// 数据仓储
        /// </summary>
        protected readonly IRepository<TEntity> Repository;
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        public BaseService(IRepository<TEntity> repository)
        {
            Repository = repository;
        }
 
        #region 查询/分页查询
 
        /// <summary>
        /// 主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<TDetailDto> Get(long id)
        {
            var entity = await Repository.DetachedEntities.FirstOrDefaultAsync(e => e.Id == id);
            return entity.Adapt<TDetailDto>();
        }
 
        /// <summary>
        /// 分页搜索前
        /// </summary>
        protected Func<TSearchDto, Expression<Func<TEntity, bool>>> SearchExpression = null;
 
        /// <summary>
        /// 自定义分页搜索(复杂查询)
        /// </summary>
        protected Func<TSearchDto, IQueryable<TEntity>> SearchQueryable = null;
 
        /// <summary>
        /// 分页数据返回前处理
        /// </summary>
        /// <returns></returns>
        protected Action<PageResult<TEntity>> PageListHandle = null;
 
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="searchDto"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("page")]
        public virtual async Task<PageResult<TEntity>> PageList(TSearchDto searchDto)
        {
            IQueryable<TEntity> queryable;
            if (SearchQueryable != null)
            {
                // 通过派生类中定义的委托方法自定义查询条件
                queryable = SearchQueryable(searchDto);
            }
            else
            {
                // 动态构建查询条件
                GetSearchParameters(searchDto);
                queryable = Repository.DetachedEntities.Search(searchDto);
 
                // 有自定义的查询条件
                if (SearchExpression != null)
                    queryable = queryable.Where(SearchExpression(searchDto));
            }
 
            var pageList = await queryable.ToADPagedListAsync(searchDto.PageNo, searchDto.PageSize);
 
            PageListHandle?.Invoke(pageList);
 
            return pageList;
        }
 
        #endregion 查询/分页查询
 
        #region 新增
 
        /// <summary>
        /// 新增前验证或处理
        /// </summary>
        protected Action<TAddDto> BeforeAddAction = null;
 
        /// <summary>
        /// 新增后处理
        /// </summary>
        protected Action<TEntity> AfterAddAction = null;
 
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="addDto"></param>
        public virtual async Task Add(TAddDto addDto)
        {
            // 新增前操作
            BeforeAddAction?.Invoke(addDto);
 
            // 写数据
            var entity = await addDto.Adapt<TEntity>().InsertAsync();
 
            // 新增后操作
            AfterAddAction?.Invoke(entity.Entity);
        }
 
        #endregion 新增
 
        #region 删除/假删除
 
        /// <summary>
        /// 删除前验证或处理
        /// </summary>
        protected Action<List<long>> BeforeDeleteAction = null;
 
        /// <summary>
        /// 删除后处理
        /// </summary>
        protected Action<List<long>, int> AfterDeleteAction = null;
 
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        public virtual async Task Delete(List<long> ids)
        {
            BeforeDeleteAction?.Invoke(ids);
            var count = await Repository.Context.DeleteRangeAsync<TEntity>(x => ids.Contains(x.Id));
 
            AfterDeleteAction?.Invoke(ids, count);
        }
 
        /// <summary>
        /// 假删除前验证或处理
        /// </summary>
        protected Action<List<long>> BeforeFakeDeleteAction = null;
 
        /// <summary>
        /// 假删除后处理
        /// </summary>
        protected Action<List<long>, int> AfterFakeDeleteAction = null;
 
        /// <summary>
        /// 假删除
        /// </summary>
        /// <param name="ids"></param>
        [HttpDelete("fakeDelete")]
        public virtual async Task FakeDelete(List<long> ids)
        {
            BeforeFakeDeleteAction?.Invoke(ids);
 
            var count = await Repository.Context.BatchUpdate<TEntity>()
                .Set(x => x.IsDeleted, x => true)
                .Where(x => ids.Contains(x.Id))
                .ExecuteAsync();
 
            AfterFakeDeleteAction?.Invoke(ids, count);
        }
 
        #endregion 删除/假删除
 
        #region 修改
 
        /// <summary>
        /// 更新前验证或处理
        /// </summary>
        protected Action<TUpdateDto> BeforeUpdateAction = null;
 
        /// <summary>
        /// 更新后处理
        /// </summary>
        protected Action<TEntity> AfterUpdateAction = null;
 
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="updateDto"></param>
        [HttpPut("edit")]
        public virtual async Task Update(TUpdateDto updateDto)
        {
            BeforeUpdateAction?.Invoke(updateDto);
            var entity = await updateDto.Adapt<TEntity>().UpdateAsync(true);
            AfterUpdateAction?.Invoke(entity.Entity);
        }
 
        #endregion 修改
 
        #region 导入
 
        /// <summary>
        /// 导入模版下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("importTemplate")]
        public virtual async Task<FileContentResult> ImportTemplate()
        {
            // 创建Excel导入对象
            IImporter importer = new ExcelImporter();
            var byteArray = await importer.GenerateTemplateBytes<TImportDto>();
 
            // 文件名称
            var fileName = typeof(TEntity).GetDescriptionValue<CommentAttribute>().Comment + "导入模版.xlsx";
 
            return await Task.FromResult(
                new FileContentResult(byteArray, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    FileDownloadName = fileName
                });
        }
 
        /// <summary>
        /// 导入前验证或处理
        /// </summary>
        protected Action<IEnumerable<TImportDto>> BeforeImportAction = null;
 
        /// <summary>
        /// 导入后处理
        /// </summary>
        protected Action<IEnumerable<TImportDto>> AfterImportAction = null;
 
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <exception cref="Exception"></exception>
        [UnitOfWork]
        public virtual async Task Import(IFormFile file)
        {
            var path = Path.Combine(Path.GetTempPath(), $"{YitIdHelper.NextId()}.xlsx");
            await using (var stream = File.Create(path))
            {
                await file.CopyToAsync(stream);
            }
 
            // 创建Excel导入对象
            IImporter importer = new ExcelImporter();
            var import = await importer.Import<TImportDto>(path);
 
            if (import == null)
                throw Oops.Oh("导入模版解析异常");
            if (import.Exception != null)
                throw Oops.Oh("导入异常:" + import.Exception);
            if (import.RowErrors.Count > 0)
                throw Oops.Oh("数据校验:" + JSON.Serialize(import.RowErrors));
 
            BeforeImportAction?.Invoke(import.Data);
 
            await Repository.InsertAsync(import.Data.Adapt<ICollection<TEntity>>());
 
            AfterImportAction?.Invoke(import.Data);
        }
 
        #endregion 导入
 
        #region 导出
 
        /// <summary>
        /// 导出搜索前
        /// </summary>
        protected Func<TSearchDto, Expression<Func<TEntity, bool>>> ExportSearchExpression = null;
 
        /// <summary>
        /// 自定义导出搜索(复杂查询)
        /// </summary>
        protected Func<TSearchDto, IQueryable<TEntity>> ExportSearchQueryable = null;
 
        /// <summary>
        /// 导出数据返回前处理
        /// </summary>
        /// <returns></returns>
        protected Action<PagedList<TEntity>> ExportHandle = null;
 
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="searchDto"></param>
        /// <returns></returns>
        [HttpGet("export")]
        public virtual async Task<FileContentResult> Export(TSearchDto searchDto)
        {
            IQueryable<TEntity> queryable;
            if (ExportSearchQueryable != null)
            {
                // 通过派生类中定义的委托方法自定义查询条件
                queryable = ExportSearchQueryable(searchDto);
            }
            else
            {
                // 动态构建查询条件
                GetSearchParameters(searchDto);
                queryable = Repository.DetachedEntities.Search(searchDto);
 
                // 有自定义的查询条件
                if (ExportSearchExpression != null)
                    queryable = queryable.Where(ExportSearchExpression(searchDto));
            }
 
            var entitys = await queryable.ToListAsync();
 
            // 创建Excel导出对象
            IExporter exporter = new ExcelExporter();
 
            // 导出文件
            var byteArray = await exporter.ExportAsByteArray(entitys.Adapt<List<TExportDto>>());
 
            // 文件名称
            var fileName = typeof(TEntity).GetDescriptionValue<CommentAttribute>() + DateTime.Now.ToString("yyyyMMddHHssmm") + ".xlsx";
 
            return await Task.FromResult(
                new FileContentResult(byteArray, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    FileDownloadName = fileName
                });
        }
 
        #endregion 导出
 
        #region 打印
 
        /// <summary>
        /// 获取打印数据 todo: 最简单的主键查询单条数据,后续实现单据打印模版模块
        /// </summary>
        /// <param name="id"></param>
        [HttpGet("print")]
        public virtual async Task<TPrintDto> Print(long id)
        {
            var entity = await Repository.DetachedEntities.FirstOrDefaultAsync(e => e.Id == id);
            return entity.Adapt<TPrintDto>();
        }
 
        #endregion 打印
 
        #region 私有方法
 
        /// <summary>
        /// 将查询dto组装成搜索参数
        /// </summary>
        /// <param name="searchDto"></param>
        /// <returns></returns>
        private void GetSearchParameters(TSearchDto searchDto)
        {
            // 如果没有复杂查询条件,把自定义查询dto中有内容的项加入查询条件
            if (searchDto.SearchParameters != null && searchDto.SearchParameters.Any()) return;
 
            // 查询dto转为字典
            var searchDictionary = searchDto.ToDictionary();
 
            // 取实体中的字段名称
            var entityPropertieNames =
                typeof(TEntity).GetProperties().Select(x => x.Name).ToList();
 
            // 将searchDto中有值的属性加入复杂查询条件
            foreach (var keyValuePair in searchDictionary)
            {
                // 跳过自定义属性和空值属性,自定义属性可在查询前委托中定义查询条件
                if (!entityPropertieNames.Contains(keyValuePair.Key) || keyValuePair.Value == null) continue;
                searchDto.SearchParameters.Add(new Condition()
                {
                    Field = keyValuePair.Key,
                    Op = QueryTypeEnum.Equals,
                    Value = keyValuePair.Value
                });
            }
        }
 
        #endregion 私有方法
    }
}