using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqLaundrySupplier;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_laundry_supplier;
using NCC.Extend.Interfaces.LqLaundrySupplier;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;
using Yitter.IdGenerator;
namespace NCC.Extend
{
///
/// 清洗商服务
///
[ApiDescriptionSettings(Tag = "绿纤清洗商管理", Name = "LqLaundrySupplier", Order = 200)]
[Route("api/Extend/LqLaundrySupplier")]
public class LqLaundrySupplierService : IDynamicApiController, ITransient, ILqLaundrySupplierService
{
private readonly IUserManager _userManager;
private readonly ILogger _logger;
private readonly ISqlSugarClient _db;
///
/// 构造函数
///
public LqLaundrySupplierService(IUserManager userManager, ILogger logger, ISqlSugarClient db)
{
_userManager = userManager;
_logger = logger;
_db = db;
}
#region 创建清洗商
///
/// 创建清洗商
///
///
/// 创建清洗商记录,一个清洗商对应一个产品类型一条记录
///
/// 示例请求:
/// ```json
/// {
/// "supplierName": "清洗商A",
/// "productType": "毛巾",
/// "laundryPrice": 5.00,
/// "remark": "备注信息"
/// }
/// ```
///
/// 创建输入
/// 创建结果
/// 创建成功
/// 清洗商已存在或参数错误
/// 服务器错误
[HttpPost("Create")]
public async Task CreateAsync([FromBody] LqLaundrySupplierCrInput input)
{
try
{
// 检查是否已存在相同清洗商和产品类型的记录
var existing = await _db.Queryable()
.Where(x => x.SupplierName == input.SupplierName
&& x.ProductType == input.ProductType
&& x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (existing != null)
{
throw NCCException.Oh($"清洗商【{input.SupplierName}】已存在{input.ProductType}的记录");
}
// 创建清洗商记录
var entity = new LqLaundrySupplierEntity
{
Id = YitIdHelper.NextId().ToString(),
SupplierName = input.SupplierName,
ProductType = input.ProductType,
LaundryPrice = input.LaundryPrice,
Remark = input.Remark,
IsEffective = StatusEnum.有效.GetHashCode(),
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now
};
var isOk = await _db.Insertable(entity).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
catch (Exception ex)
{
_logger.LogError(ex, "创建清洗商失败");
throw NCCException.Oh($"创建失败:{ex.Message}");
}
}
#endregion
#region 更新清洗商
///
/// 更新清洗商
///
///
/// 更新清洗商信息,包括价格(更新价格不影响历史流水记录的价格)
///
/// 更新输入
/// 更新结果
/// 更新成功
/// 记录不存在或参数错误
/// 服务器错误
[HttpPut("Update")]
public async Task UpdateAsync([FromBody] LqLaundrySupplierUpInput input)
{
try
{
var existing = await _db.Queryable()
.Where(x => x.Id == input.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (existing == null)
{
throw NCCException.Oh("清洗商记录不存在或已失效");
}
// 如果清洗商名称或产品类型改变,检查是否冲突
if (existing.SupplierName != input.SupplierName || existing.ProductType != input.ProductType)
{
var conflict = await _db.Queryable()
.Where(x => x.Id != input.Id
&& x.SupplierName == input.SupplierName
&& x.ProductType == input.ProductType
&& x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (conflict != null)
{
throw NCCException.Oh($"清洗商【{input.SupplierName}】已存在{input.ProductType}的记录");
}
}
// 更新记录
existing.SupplierName = input.SupplierName;
existing.ProductType = input.ProductType;
existing.LaundryPrice = input.LaundryPrice;
existing.Remark = input.Remark;
existing.UpdateUser = _userManager.UserId;
existing.UpdateTime = DateTime.Now;
var isOk = await _db.Updateable(existing).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
catch (Exception ex)
{
_logger.LogError(ex, "更新清洗商失败");
throw NCCException.Oh($"更新失败:{ex.Message}");
}
}
#endregion
#region 获取清洗商列表
///
/// 获取清洗商列表
///
///
/// 分页查询清洗商列表,支持按清洗商名称、产品类型筛选
///
/// 查询输入
/// 清洗商列表
/// 查询成功
/// 服务器错误
[HttpGet("GetList")]
public async Task GetListAsync([FromQuery] LqLaundrySupplierListQueryInput input)
{
try
{
var sidx = string.IsNullOrEmpty(input.sidx) ? "createTime" : input.sidx;
var sort = string.IsNullOrEmpty(input.sort) ? "desc" : input.sort;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrWhiteSpace(input.SupplierName), x => x.SupplierName.Contains(input.SupplierName))
.WhereIF(!string.IsNullOrWhiteSpace(input.ProductType), x => x.ProductType == input.ProductType)
.WhereIF(input.IsEffective.HasValue, x => x.IsEffective == input.IsEffective.Value)
.Select(x => new LqLaundrySupplierListOutput
{
id = x.Id,
supplierName = x.SupplierName,
productType = x.ProductType,
laundryPrice = x.LaundryPrice,
remark = x.Remark,
isEffective = x.IsEffective,
createUser = x.CreateUser,
createUserName = "",
createTime = x.CreateTime,
updateUser = x.UpdateUser,
updateUserName = "",
updateTime = x.UpdateTime
})
.MergeTable()
.OrderBy(sidx + " " + sort)
.ToPagedListAsync(input.currentPage, input.pageSize);
// 补充用户名称信息
var userIds = data.list.SelectMany(x => new[] { x.createUser, x.updateUser })
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
if (userIds.Any())
{
var userList = await _db.Queryable()
.Where(x => userIds.Contains(x.Id))
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = userList.ToDictionary(k => k.Id, v => v.RealName);
foreach (var item in data.list)
{
item.createUserName = userDict.ContainsKey(item.createUser) ? userDict[item.createUser] : "";
item.updateUserName = !string.IsNullOrEmpty(item.updateUser) && userDict.ContainsKey(item.updateUser) ? userDict[item.updateUser] : "";
}
}
return PageResult.SqlSugarPageResult(data);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取清洗商列表失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 获取清洗商详情
///
/// 获取清洗商详情
///
///
/// 根据ID获取清洗商的详细信息
///
/// 清洗商ID
/// 清洗商详情
/// 查询成功
/// 记录不存在
/// 服务器错误
[HttpGet("{id}")]
public async Task GetInfoAsync(string id)
{
try
{
var entity = await _db.Queryable()
.Where(x => x.Id == id)
.Select(x => new LqLaundrySupplierInfoOutput
{
id = x.Id,
supplierName = x.SupplierName,
productType = x.ProductType,
laundryPrice = x.LaundryPrice,
remark = x.Remark,
isEffective = x.IsEffective,
createUser = x.CreateUser,
createUserName = "",
createTime = x.CreateTime,
updateUser = x.UpdateUser,
updateUserName = "",
updateTime = x.UpdateTime
})
.FirstAsync();
if (entity == null)
{
throw NCCException.Oh("清洗商记录不存在");
}
// 补充用户名称
if (!string.IsNullOrEmpty(entity.createUser))
{
var createUser = await _db.Queryable()
.Where(x => x.Id == entity.createUser)
.Select(x => x.RealName)
.FirstAsync();
entity.createUserName = createUser ?? "";
}
if (!string.IsNullOrEmpty(entity.updateUser))
{
var updateUser = await _db.Queryable()
.Where(x => x.Id == entity.updateUser)
.Select(x => x.RealName)
.FirstAsync();
entity.updateUserName = updateUser ?? "";
}
return entity;
}
catch (Exception ex)
{
_logger.LogError(ex, "获取清洗商详情失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 删除/作废清洗商
///
/// 删除/作废清洗商
///
///
/// 将清洗商记录标记为无效
///
/// 清洗商ID
/// 操作结果
/// 操作成功
/// 记录不存在
/// 服务器错误
[HttpDelete("{id}")]
public async Task DeleteAsync(string id)
{
try
{
var entity = await _db.Queryable()
.Where(x => x.Id == id)
.FirstAsync();
if (entity == null)
{
throw NCCException.Oh("清洗商记录不存在");
}
entity.IsEffective = StatusEnum.无效.GetHashCode();
entity.UpdateUser = _userManager.UserId;
entity.UpdateTime = DateTime.Now;
var isOk = await _db.Updateable(entity).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
catch (Exception ex)
{
_logger.LogError(ex, "删除清洗商失败");
throw NCCException.Oh($"删除失败:{ex.Message}");
}
}
#endregion
}
}