using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Myshipping.Application.Entity;
using Myshipping.Application.Helper;
using Myshipping.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Myshipping.Application
{
///
/// 状态管理
///
[ApiDescriptionSettings("Application", Name = "StatusSkuBase", Order = 10)]
public class StatusSkuBaseService : IStatusSkuBaseService, IDynamicApiController, ITransient
{
private readonly SqlSugarRepository _statusSkuBaseInfoRepository;
private readonly SqlSugarRepository _serviceWorkFlowActivitiesInfoRepository;
private readonly ILogger _logger;
public StatusSkuBaseService(SqlSugarRepository statusSkuBaseInfoRepository,
ILogger logger,
SqlSugarRepository serviceWorkFlowActivitiesInfoRepository)
{
_statusSkuBaseInfoRepository = statusSkuBaseInfoRepository;
_logger = logger;
_serviceWorkFlowActivitiesInfoRepository = serviceWorkFlowActivitiesInfoRepository;
}
#region 保存
///
/// 保存
///
/// 状态详情
/// 返回回执
[HttpPost("/StatusSkuBase/Save")]
public async Task Save([FromBody] StatusSkuBaseDto info)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
var id = await InnerSave(info);
result.succ = true;
result.msg = "保存成功";
result.ext = id;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"保存服务项目异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 保存内部方法
///
/// 保存内部方法
///
/// 服务项目详情
/// 是否启用
/// 返回派车Id
[SqlSugarUnitOfWork]
private async Task InnerSave(StatusSkuBaseDto info, bool isSetEnable = false)
{
StatusSkuBaseInfo entity = info.Adapt();
if (isSetEnable)
{
entity.IS_ENABLE = 1;
}
if (entity == null)
throw Oops.Oh($"服务项目不能为空", typeof(InvalidOperationException));
_logger.LogInformation($"服务项目保存 JSON={JSON.Serialize(entity)} user={UserManager.UserId}");
if (string.IsNullOrWhiteSpace(entity.PK_ID))
{
entity.PK_ID = IDGen.NextID().ToString();
_statusSkuBaseInfoRepository.Insert(entity);
}
else
{
var model = InnerGetInfo(entity.PK_ID);
_logger.LogInformation($"更新状态前,获取原始记录 JSON={JSON.Serialize(model)}");
ValidateServiceStatus(entity, OperateTypeEnum.Save);
entity.UpdatedTime = DateTime.Now;
entity.UpdatedUserId = UserManager.UserId;
entity.UpdatedUserName = UserManager.Name;
await _statusSkuBaseInfoRepository.AsUpdateable(entity).IgnoreColumns(it => new
{
it.TenantId,
it.TenantName,
it.CreatedTime,
it.CreatedUserId,
it.CreatedUserName,
it.IsDeleted,
}).ExecuteCommandAsync();
}
return entity.PK_ID;
}
#endregion
#region 单票查询
///
/// 单票查询
///
/// 状态主键
private StatusSkuBaseInfo InnerGetInfo(string pkId)
{
if (string.IsNullOrWhiteSpace(pkId))
{
throw Oops.Oh($"状态主键不能为空", typeof(InvalidOperationException));
}
var model = _statusSkuBaseInfoRepository.AsQueryable().First(a => a.PK_ID == pkId);
if (model == null)
throw Oops.Oh($"状态获取失败,状态信息不存在或已作废", typeof(InvalidOperationException));
return model;
}
#endregion
#region 校验
///
/// 校验
///
/// 服务状态详情
/// 操作类型枚举
///
private void ValidateServiceStatus(StatusSkuBaseInfo entity, OperateTypeEnum opTypeEnum)
{
/*
1、状态名称不能低于2个字符。
2、状态修改,需要判断当前状态是否关联服务的活动。已关联的不能修改状态代码。
3、取消启用时,需要判断当前状态是否关联服务的活动。已关联的不能取消启用。
*/
if (opTypeEnum == OperateTypeEnum.Save)
{
if(_serviceWorkFlowActivitiesInfoRepository.AsQueryable().Any(a=>a.STATUS_SKU_ID == entity.PK_ID))
{
throw Oops.Oh($"当前状态已关联服务流程活动,不能修改", typeof(InvalidOperationException));
}
if (entity.STATUS_SKU_CODE.Length < 2 || entity.STATUS_SKU_NAME.Length < 2)
throw Oops.Oh($"状态代码和状态名称不能小于2个字符,不能修改", typeof(InvalidOperationException));
}
if (opTypeEnum == OperateTypeEnum.SetUnEnable)
{
if (_serviceWorkFlowActivitiesInfoRepository.AsQueryable().Any(a => a.STATUS_SKU_ID == entity.PK_ID))
{
throw Oops.Oh($"当前状态已关联服务流程活动,不能取消启用", typeof(InvalidOperationException));
}
}
}
#endregion
#region 保存并启用
///
/// 保存并启用
///
/// 状态详情
/// 返回回执
[HttpPost("/StatusSkuBase/SaveAndEnable")]
public async Task SaveAndEnable([FromBody] StatusSkuBaseDto info)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
var id = await InnerSave(info, true);
result.succ = true;
result.msg = "执行成功";
result.ext = id;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"保存并启用状态异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 处理状态内部方法
///
/// 处理状态内部方法
///
/// 状态详情
/// 操作类型
/// 返回回执
private async Task InnerExcuteServiceStatus(StatusSkuBaseInfo model, OperateTypeEnum opTypeEnum)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
result.bno = model?.STATUS_SKU_NAME;
try
{
if (model == null)
throw Oops.Oh($"状态获取失败,状态信息不存在或已作废", typeof(InvalidOperationException));
_logger.LogInformation($"更新状态前,获取原始记录 JSON={JSON.Serialize(model)}");
model.UpdatedTime = DateTime.Now;
model.UpdatedUserId = UserManager.UserId;
model.UpdatedUserName = UserManager.Name;
if (opTypeEnum == OperateTypeEnum.SetEnable)
{
model.IS_ENABLE = 1;
await _statusSkuBaseInfoRepository.AsUpdateable(model).UpdateColumns(it => new
{
it.IS_ENABLE,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
else if (opTypeEnum == OperateTypeEnum.SetUnEnable)
{
ValidateServiceStatus(model, opTypeEnum);
model.IS_ENABLE = 0;
await _statusSkuBaseInfoRepository.AsUpdateable(model).UpdateColumns(it => new
{
it.IS_ENABLE,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
else if (opTypeEnum == OperateTypeEnum.Delete)
{
ValidateServiceStatus(model, opTypeEnum);
model.IsDeleted = true;
await _statusSkuBaseInfoRepository.AsUpdateable(model).UpdateColumns(it => new
{
it.IsDeleted,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
result.succ = true;
result.msg = "执行成功";
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"执行状态异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 启用
///
/// 启用
///
/// 状态主键数组
/// 返回回执
[HttpPost("/StatusSkuBase/SetEnable")]
public async Task SetEnable([FromBody] string[] pkIds)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (pkIds.Length == 0)
{
throw Oops.Oh($"状态主键数组不能为空", typeof(InvalidOperationException));
}
var list = _statusSkuBaseInfoRepository.AsQueryable()
.Where(a => pkIds.Contains(a.PK_ID)).ToList();
if (list.Count == 0)
throw Oops.Oh($"状态获取失败,请服务项目信息是否存在", typeof(InvalidOperationException));
if (list.Count != pkIds.Length)
throw Oops.Oh($"部分状态获取失败,请服务项目信息是否存在", typeof(InvalidOperationException));
List rltList = new List();
list.ForEach(pr => {
rltList.Add(InnerExcuteServiceStatus(pr, OperateTypeEnum.SetEnable).GetAwaiter().GetResult());
});
result.succ = true;
result.msg = rltList.FirstOrDefault().msg;
result.ext = rltList;
var succ = rltList.Count(x => x.succ);
var fail = rltList.Count(x => !x.succ);
if (succ > 0)
{
result.batchTotal = succ.ToString();
}
else
{
result.batchTotal = "- ";
}
if (fail > 0)
{
result.batchTotal += "/" + fail.ToString();
}
else
{
result.batchTotal += " -";
}
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"启用状态异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 取消启用
///
/// 取消启用
///
/// 状态主键数组
/// 返回回执
[HttpPost("/StatusSkuBase/SetUnEnable")]
public async Task SetUnEnable([FromBody] string[] pkIds)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (pkIds.Length == 0)
{
throw Oops.Oh($"状态主键数组不能为空", typeof(InvalidOperationException));
}
var list = _statusSkuBaseInfoRepository.AsQueryable()
.Where(a => pkIds.Contains(a.PK_ID)).ToList();
if (list.Count == 0)
throw Oops.Oh($"状态获取失败,请服务项目信息是否存在", typeof(InvalidOperationException));
if (list.Count != pkIds.Length)
throw Oops.Oh($"部分状态获取失败,请服务项目信息是否存在", typeof(InvalidOperationException));
List rltList = new List();
list.ForEach(pr => {
rltList.Add(InnerExcuteServiceStatus(pr, OperateTypeEnum.SetUnEnable).GetAwaiter().GetResult());
});
result.succ = true;
result.msg = rltList.FirstOrDefault().msg;
result.ext = rltList;
var succ = rltList.Count(x => x.succ);
var fail = rltList.Count(x => !x.succ);
if (succ > 0)
{
result.batchTotal = succ.ToString();
}
else
{
result.batchTotal = "- ";
}
if (fail > 0)
{
result.batchTotal += "/" + fail.ToString();
}
else
{
result.batchTotal += " -";
}
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"启用服务项目异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 删除
///
/// 删除
///
/// 状态主键数组
/// 返回回执
[HttpPost("/StatusSkuBase/Delete")]
public async Task Delete([FromBody] string[] pkIds)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (pkIds.Length == 0)
{
throw Oops.Oh($"状态主键数组不能为空", typeof(InvalidOperationException));
}
var list = _statusSkuBaseInfoRepository.AsQueryable()
.Where(a => pkIds.Contains(a.PK_ID)).ToList();
if (list.Count == 0)
throw Oops.Oh($"状态获取失败,请服务项目信息是否存在", typeof(InvalidOperationException));
if (list.Count != pkIds.Length)
throw Oops.Oh($"部分状态获取失败,请服务项目信息是否存在", typeof(InvalidOperationException));
List rltList = new List();
list.ForEach(pr => {
rltList.Add(InnerExcuteServiceStatus(pr, OperateTypeEnum.Delete).GetAwaiter().GetResult());
});
result.succ = true;
result.msg = rltList.FirstOrDefault().msg;
result.ext = rltList;
var succ = rltList.Count(x => x.succ);
var fail = rltList.Count(x => !x.succ);
if (succ > 0)
{
result.batchTotal = succ.ToString();
}
else
{
result.batchTotal = "- ";
}
if (fail > 0)
{
result.batchTotal += "/" + fail.ToString();
}
else
{
result.batchTotal += " -";
}
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"启用服务项目异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 获取状态详情
///
/// 获取状态详情
///
/// 状态主键
/// 返回回执
[HttpGet("/StatusSkuBase/GetInfo")]
public async Task GetInfo([FromQuery]string pkId)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
var model = InnerGetInfo(pkId);
var showModel = model.Adapt();
result.succ = true;
result.ext = showModel;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"获取状态详情异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 检索状态列表
///
/// 检索状态列表
///
/// 检索值
/// 最大返回行数(默认15)
/// 返回回执
[HttpGet("/StatusSkuBase/QueryList")]
public async Task QueryList(string queryItem, int topNum = 15)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
var list = await _statusSkuBaseInfoRepository.AsQueryable().Where(a =>
a.IS_ENABLE == 1 && !a.IsDeleted && (string.IsNullOrWhiteSpace(queryItem) || (a.STATUS_SKU_CODE.Contains(queryItem) || a.STATUS_SKU_NAME.Contains(queryItem))))
.Take(topNum).ToListAsync();
result.succ = true;
result.ext = list.Adapt>();
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"检索状态列表异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 状态台账查询
///
/// 状态台账查询
///
/// 状态台账查询请求
/// 返回结果
[HttpPost("/StatusSkuBase/GetPage")]
public async Task> GetPageAsync([FromBody]QueryStatusSkuBaseDto QuerySearch)
{
//制单日期
DateTime createBegin = DateTime.MinValue;
DateTime createEnd = DateTime.MinValue;
//更新日期
DateTime updateBegin = DateTime.MinValue;
DateTime updateEnd = DateTime.MinValue;
//制单日期
if (!string.IsNullOrWhiteSpace(QuerySearch.CreateBegin))
{
if (!DateTime.TryParse(QuerySearch.CreateBegin, out createBegin))
throw Oops.Oh($"创建起始日期格式错误,{QuerySearch.CreateBegin}");
}
if (!string.IsNullOrWhiteSpace(QuerySearch.CreateEnd))
{
if (!DateTime.TryParse(QuerySearch.CreateEnd, out createEnd))
throw Oops.Oh($"创建结束日期格式错误,{QuerySearch.CreateEnd}");
createEnd = createEnd.AddDays(1);
}
//更新日期
if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateBegin))
{
if (!DateTime.TryParse(QuerySearch.UpdateBegin, out updateBegin))
throw Oops.Oh($"更新起始日期格式错误,{QuerySearch.UpdateBegin}");
}
if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateEnd))
{
if (!DateTime.TryParse(QuerySearch.UpdateEnd, out updateEnd))
throw Oops.Oh($"更新结束日期格式错误,{QuerySearch.UpdateEnd}");
updateEnd = updateEnd.AddDays(1);
}
string entityOrderCol = "CreatedTime";
//这里因为返回给前端的台账数据是DTO,所以这里排序时候需要转换成Entity对应的字段
if (!string.IsNullOrWhiteSpace(QuerySearch.SortField))
entityOrderCol = MapsterExtHelper.GetAdaptProperty(QuerySearch.SortField);
var entities = await _statusSkuBaseInfoRepository.AsQueryable()
.WhereIF(createBegin != DateTime.MinValue, t => t.CreatedTime >= createBegin)
.WhereIF(createEnd != DateTime.MinValue, t => t.CreatedTime < createEnd)
.WhereIF(updateBegin != DateTime.MinValue, t => t.UpdatedTime.HasValue && t.UpdatedTime.Value >= updateBegin)
.WhereIF(updateEnd != DateTime.MinValue, t => t.UpdatedTime.HasValue && t.UpdatedTime.Value < updateEnd)
.WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.IsEnable) && QuerySearch.IsEnable == "1", t => t.IS_ENABLE == 1)
.WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.IsEnable) && QuerySearch.IsEnable == "2", t => t.IS_ENABLE == 0)
.WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.StatusSKUName), t => t.STATUS_SKU_NAME.Contains(QuerySearch.StatusSKUName) ||
t.STATUS_SKU_CODE.Contains(QuerySearch.StatusSKUName))
.WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.StatusSKUNote), t => t.STATUS_SKU_NOTE.Contains(QuerySearch.StatusSKUNote))
.WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.CreateUser), t => t.CreatedUserName.Contains(QuerySearch.CreateUser))
.WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.UpdateUser), t => t.UpdatedUserName.Contains(QuerySearch.UpdateUser))
.OrderBy(entityOrderCol + (QuerySearch.descSort ? " asc " : " desc "))
.ToPagedListAsync(QuerySearch.PageNo, QuerySearch.PageSize);
return entities.Adapt>();
}
#endregion
}
}