using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Education.Interfaces.TbMemCode;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Education.Entitys;
using NCC.Education.Entitys.Dto.TbMemCode;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
using NCC.System.Interfaces.System;
using NCC.System.Entitys.Permission;
using Microsoft.Extensions.Logging;
using NPOI.HPSF;
namespace NCC.Education.TbMemCode
{
///
/// 会员码管理服务
///
[ApiDescriptionSettings(Tag = "会员码管理",Name = "TbMemCode", Order = 200)]
[Route("api/Education/[controller]")]
public class TbMemCodeService : ITbMemCodeService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository _tbMemCodeRepository;
private readonly IDbLinkService _dbLinkService;
private readonly IDataBaseService _dataBaseService;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
private readonly ILogger _logger;
///
/// 初始化一个类型的新实例
///
public TbMemCodeService(
ISqlSugarRepository tbMemCodeRepository,
IDbLinkService dbLinkService,
IDataBaseService dataBaseService,
IUserManager userManager,
ILogger logger)
{
_tbMemCodeRepository = tbMemCodeRepository;
_db = _tbMemCodeRepository.Context;
_dbLinkService = dbLinkService;
_dataBaseService = dataBaseService;
_userManager = userManager;
_logger = logger;
}
///
/// 获取时间戳
///
///
public static long getTime()
{
return (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
}
///
/// 批量生成会员码入参
///
public class mutineCreateCodeOptions
{
///
/// 个数
///
public int numbers { get; set; }
///
/// 过期时间
///
public DateTime? expire { get; set; }
}
///
/// 批量生成会员码
///
///
[HttpPost("MutinueCreateCode")]
public async Task MutinueCreateCode(mutineCreateCodeOptions query)
{
List list = new List();
for(var i=0;i< query.numbers; i++)
{
list.Add(new TbMemCodeEntity
{
Id = YitIdHelper.NextId().ToString(),
Code =Guid.NewGuid().ToString().Replace("-","").ToLower().Substring(0,10),
Expire = query.expire,
Type = "2",
CreatorTime = DateTime.Now
});
}
var result = _db.Insertable(list).ExecuteCommand();
if (!(result > 0)) throw NCCException.Oh($"批量生成失败!");
}
///
/// 批量更改会员截至日期入参
///
public class MutineUpdateExpireOptions
{
///
/// IDS
///
public string ids { get; set; }
///
/// 会员截至日期
///
public DateTime? expire { get; set; }
}
///
/// 批量更改会员截至日期
///
///
///
[HttpPost("MutinueUpdateDaysNumber")]
public async Task MutinueUpdateDaysNumber(MutineUpdateExpireOptions query)
{
if (query.ids.IsNullOrEmpty()) throw NCCException.Oh($"参数错误");
List list = new List();
if (!query.ids.Contains(","))
{
list.Add(query.ids);
}
else
{
list = query.ids.Split(",").ToList();
}
var result = _db.Updateable().SetColumns(it => new TbMemCodeEntity { Expire = query.expire }).Where(o => list.Contains(o.Id)).ExecuteCommand();
if (!(result > 0)) throw NCCException.Oh($"批量更改失败!");
}
///
/// 普通用户根据会员码转会员参数
///
public class ShiftToMemOptions
{
///
/// 用户ID
///
public string UserId { get; set; }
///
/// 会员码
///
public string Code { get; set; }
}
///
/// 普通用户根据会员码转会员
///
///
///
[HttpPost("UserShiftToMem")]
public async Task UserShiftToMem(ShiftToMemOptions query)
{
var user = _db.Queryable().Where(o => o.Id == query.UserId).First();
if (user == null) throw NCCException.Oh($"暂无此用户哦!");
var model = _db.Queryable().Where(o => o.Code == query.Code&&o.Type=="2").First();
if (model == null) throw NCCException.Oh($"暂无此会员码哦!");
try
{
_db.BeginTran();
user.Type = "2";
user.MemDate = model.Expire;
var result = _db.Updateable(user).ExecuteCommand();
model.Type = "1";
var dataResult = _db.Updateable(model).ExecuteCommand();
var userResult = _db.Queryable().Where(o => o.Id == user.Id).First();
_db.CommitTran();
return userResult;
}
catch (Exception ex)
{
_db.RollbackTran();
_logger.LogInformation($"转换会员失败:{ex.Message}");
throw NCCException.Oh($"转换会员失败:{ex.Message}");
}
}
///
/// 获取会员码管理
///
/// 参数
///
[HttpGet("{id}")]
public async Task GetInfo(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable().FirstAsync(p => p.Id == id);
var output = entity.Adapt();
return output;
}
///
/// 获取会员码管理列表
///
/// 请求参数
///
[HttpGet("")]
public async Task GetList([FromQuery] TbMemCodeListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
List queryExpire = input.expire != null ? input.expire.Split(',').ToObeject>() : null;
DateTime? startExpire = queryExpire != null ? Ext.GetDateTime(queryExpire.First()) : null;
DateTime? endExpire = queryExpire != null ? Ext.GetDateTime(queryExpire.Last()) : null;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrEmpty(input.code), p => p.Code.Contains(input.code))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.WhereIF(queryExpire != null, p => p.Expire >= new DateTime(startExpire.ToDate().Year, startExpire.ToDate().Month, startExpire.ToDate().Day, 0, 0, 0))
.WhereIF(queryExpire != null, p => p.Expire <= new DateTime(endExpire.ToDate().Year, endExpire.ToDate().Month, endExpire.ToDate().Day, 23, 59, 59))
.Select(it=> new TbMemCodeListOutput
{
id = it.Id,
code=it.Code,
type=it.Type,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
expire = it.Expire,
}).MergeTable().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult.SqlSugarPageResult(data);
}
///
/// 新建会员码管理
///
/// 参数
///
[HttpPost("")]
public async Task Create([FromBody] TbMemCodeCrInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt();
entity.Id = YitIdHelper.NextId().ToString();
entity.CreatorTime = DateTime.Now;
if (entity.Expire <= DateTime.Now) throw NCCException.Oh($"到期时间不能小于当前时间!");
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
///
/// 获取会员码管理无分页列表
///
/// 请求参数
///
[NonAction]
public async Task GetNoPagingList([FromQuery] TbMemCodeListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
List queryExpire = input.expire != null ? input.expire.Split(',').ToObeject>() : null;
DateTime? startExpire = queryExpire != null ? Ext.GetDateTime(queryExpire.First()) : null;
DateTime? endExpire = queryExpire != null ? Ext.GetDateTime(queryExpire.Last()) : null;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrEmpty(input.code), p => p.Code.Contains(input.code))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.WhereIF(queryExpire != null, p => p.Expire >= new DateTime(startExpire.ToDate().Year, startExpire.ToDate().Month, startExpire.ToDate().Day, 0, 0, 0))
.WhereIF(queryExpire != null, p => p.Expire <= new DateTime(endExpire.ToDate().Year, endExpire.ToDate().Month, endExpire.ToDate().Day, 23, 59, 59))
.Select(it=> new TbMemCodeListOutput
{
id = it.Id,
code=it.Code,
type=it.Type,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
expire=it.Expire,
}).MergeTable().OrderBy(sidx+" "+input.sort).ToListAsync();
return data;
}
///
/// 导出会员码管理
///
/// 请求参数
///
[HttpGet("Actions/Export")]
public async Task Export([FromQuery] TbMemCodeListQueryInput input)
{
var userInfo = await _userManager.GetUserInfo();
var exportData = new List();
if (input.dataType == 0)
{
var data = Clay.Object(await this.GetList(input));
exportData = data.Solidify>().list;
}
else
{
exportData = await this.GetNoPagingList(input);
}
List paramList = "[{\"value\":\"会员码\",\"field\":\"code\"},{\"value\":\"状态\",\"field\":\"type\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"修改时间\",\"field\":\"lastModifyTime\"},]".ToList();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "会员码管理.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List();
List selectKeyList = input.selectKey.Split(',').ToList();
foreach (var item in selectKeyList)
{
var isExist = paramList.Find(p => p.field == item);
if (isExist != null)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
}
}
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("batchRemove")]
public async Task BatchRemove([FromBody] List ids)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entitys = await _db.Queryable().In(it => it.Id, ids).ToListAsync();
if (entitys.Count > 0)
{
try
{
//开启事务
_db.BeginTran();
//批量删除会员码管理
await _db.Deleteable().In(d => d.Id,ids).ExecuteCommandAsync();
//关闭事务
_db.CommitTran();
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw NCCException.Oh(ErrorCode.COM1002);
}
}
}
///
/// 更新会员码管理
///
/// 主键
/// 参数
///
[HttpPut("{id}")]
public async Task Update(string id, [FromBody] TbMemCodeUpInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = input.Adapt();
entity.LastModifyTime = DateTime.Now;
if (entity.Expire <= DateTime.Now) throw NCCException.Oh($"到期时间不能小于当前时间!");
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
}
///
/// 删除会员码管理
///
///
[HttpDelete("{id}")]
public async Task Delete(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var isOk = await _db.Deleteable().Where(d => d.Id == id).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
}
}
}