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.TbPunch;
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.TbPunch;
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;
namespace NCC.Education.TbPunch
{
///
/// 打卡记录服务
///
[ApiDescriptionSettings(Tag = "打卡记录",Name = "TbPunch", Order = 200)]
[Route("api/Education/[controller]")]
public class TbPunchService : ITbPunchService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository _tbPunchRepository;
private readonly IDbLinkService _dbLinkService;
private readonly IDataBaseService _dataBaseService;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
private readonly ILogger _logger;
///
/// 初始化一个类型的新实例
///
public TbPunchService(
ISqlSugarRepository tbPunchRepository,
IDbLinkService dbLinkService,
IDataBaseService dataBaseService,
IUserManager userManager,
ILogger logger)
{
_tbPunchRepository = tbPunchRepository;
_db = _tbPunchRepository.Context;
_dbLinkService = dbLinkService;
_dataBaseService = dataBaseService;
_userManager = userManager;
_logger= logger;
}
///
/// 查询用户会员到期时间
///
///
[HttpPost("TaskSchedulerUserType")]
public async Task TaskSchedulerUserType()
{
var list = _db.Queryable().Where(o => o.IsAdministrator == 0).ToList();
foreach (var item in list)
{
if (item.Type == "2" && item.MemDate.ToDate() < DateTime.Now)
{
item.Type = "1";
item.MemDate = null;
var result = _db.Updateable(item).ExecuteCommand();
_logger.LogInformation($"更改会员用户为普通用户:{result}----{item.ToJson()}");
}
}
}
///
/// 每天凌晨过5分判断前一天的时间有那些人没打卡 进行赋值缺卡
///
///
[HttpPost("TaskSchedulerPunch")]
public async Task TaskSchedulerPunch()
{
var userList = _db.Queryable().Where(o => o.IsAdministrator == 0).ToList();
List list = new List();
foreach (var item in userList)
{
var model = _db.Queryable().Where(o => SqlFunc.ToDate(o.CreatorTime) == SqlFunc.ToDate(DateTime.Now.AddDays(-1)) && o.UserId == item.Id).First();
if (model == null)
{
list.Add(new TbPunchEntity()
{
Id=YitIdHelper.NextId().ToString(),
UserId=item.Id,
CreatorTime=DateTime.Now,
Type="2",
});
}
}
_logger.LogInformation($"缺卡人数时间汇总为:{list.ToJson()}");
var result = _db.Insertable(list).ExecuteCommand();
_logger.LogInformation($"是否添加了缺卡信息:{result}");
}
///
/// 开始打卡入参
///
public class OutPutInfo
{
///
/// 单次打卡赠送的积分数量
///
public int SingleNum { get; set; }
///
/// 已连续打卡赠送的积分数量
///
public int BothNum { get; set; }
///
/// 已连续打卡天数
///
public int Days { get; set; }
}
///
/// 开始打卡
///
/// 参数
///
[HttpPost("StartPunch")]
public async Task StartPunch([FromBody] TbPunchCrInput 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;
entity.Type = "1";
try
{
_db.BeginTran();
//1.添加打卡记录
var isOk = _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();
//2.判断是否有单次打卡赠送对应积分
var model = _db.Queryable().First();
if (model != null)
{
AddInterateNumSinge(model, entity);
}
//3.判断是否有连续打卡赠送对应积分
int sum = ComputeContinuousDays(entity.UserId);
var bothModel = _db.Queryable().Where(o => o.BothNumber == sum).First();
if (bothModel != null)
{
AddInterateNumBoth(bothModel, entity);
}
_db.CommitTran();
return new OutPutInfo()
{
SingleNum = model.Num.ToInt(),
BothNum =bothModel!=null?bothModel.Num.ToInt():0,
Days = sum
};
}
catch(Exception ex)
{
_logger.LogInformation($"打卡失败:{ex.Message}");
_db.RollbackTran();
throw NCCException.Oh($"打卡失败:{ex.Message}");
}
}
///
/// 连续打卡增加积分流程
///
private void AddInterateNumBoth(TbBothSettingEntity model, TbPunchEntity entity)
{
//增加用户积分
var result = _db.Updateable(it => new UserEntity { IntegralNum =SqlFunc.ToInt32(it.IntegralNum) + model.Num }).Where(o => o.Id == entity.UserId).ExecuteCommand();
//增加积分日志
var logResult = _db.Insertable(new TbMoneysLogEntity()
{
Id = YitIdHelper.NextId().ToString(),
UserId = entity.UserId,
Type = "1",
Num = model.Num,
CreatorTime = DateTime.Now
}).ExecuteCommand();
}
///
/// 单次打卡增加积分流程
///
private void AddInterateNumSinge(TbSingleSettingEntity model, TbPunchEntity entity)
{
//增加用户积分
var result = _db.Updateable(it => new UserEntity { IntegralNum =SqlFunc.ToInt32(it.IntegralNum)+ model.Num }).Where(o => o.Id == entity.UserId).ExecuteCommand();
//增加积分日志
var logResult = _db.Insertable(new TbMoneysLogEntity()
{
Id = YitIdHelper.NextId().ToString(),
UserId = entity.UserId,
Type = "1",
Num = model.Num,
CreatorTime = DateTime.Now
}).ExecuteCommand();
}
public class ComputeDaysOptions
{
public string UserId { get; set; }
public string CreatorTime { get; set; }
public string date_rank { get; set; }
public string day_cha { get; set; }
}
///
/// 判断用户连续打卡多少天
///
///
///
private int ComputeContinuousDays(string UserId)
{
int sum = 0;
var list = _db.SqlQueryable($" select UserId,CreatorTime , date_rank,(DatePart(Day,CreatorTime)-date_rank) as day_cha from ( select F_UserId as UserId,F_CreatorTime as CreatorTime,ROW_NUMBER() over(partition by F_UserId order by F_CreatorTime) as date_rank from [Antis_Ncc_Education].[dbo].[tb_Punch] where F_Type='1' and F_UserId='{UserId}' ) as t1 order by CreatorTime desc").Select(it=>new ComputeDaysOptions {
UserId=it.UserId,
CreatorTime=it.CreatorTime,
date_rank=it.date_rank,
day_cha=it.day_cha,
}).ToList();
var model = list.First();
if (model == null)
{
return 0;
}
else
{
return list.Where(o => o.day_cha == model.day_cha).Count();
}
}
///
/// 获取打卡记录
///
/// 参数
///
[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] TbPunchListQueryInput 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 queryExerciseDate = input.exerciseDate != null ? input.exerciseDate.Split(',').ToObeject>() : null;
DateTime? startExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.First()) : null;
DateTime? endExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.Last()) : null;
List creatorTimeDate = input.creatorTime != null ? input.creatorTime.Split(',').ToObeject>() : null;
DateTime? startcreatorTimeDate = creatorTimeDate != null ? Ext.GetDateTime(creatorTimeDate.First()) : null;
DateTime? endcreatorTimeDate = creatorTimeDate != null ? Ext.GetDateTime(creatorTimeDate.Last()) : null;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate >= new DateTime(startExerciseDate.ToDate().Year, startExerciseDate.ToDate().Month, startExerciseDate.ToDate().Day, 0, 0, 0))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate <= new DateTime(endExerciseDate.ToDate().Year, endExerciseDate.ToDate().Month, endExerciseDate.ToDate().Day, 23, 59, 59))
.WhereIF(creatorTimeDate != null, p => p.CreatorTime >= new DateTime(startcreatorTimeDate.ToDate().Year, startcreatorTimeDate.ToDate().Month, startcreatorTimeDate.ToDate().Day, 0, 0, 0))
.WhereIF(creatorTimeDate != null, p => p.CreatorTime <= new DateTime(endcreatorTimeDate.ToDate().Year, endcreatorTimeDate.ToDate().Month, endcreatorTimeDate.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.code), p => p.Code.Contains(input.code))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.Select(it=> new TbPunchListOutput
{
id = it.Id,
userId=it.UserId,
exerciseDate=it.ExerciseDate,
code=it.Code,
totalTime=it.TotalTime,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
type=it.Type,
imgList=it.ImgList,
}).MergeTable().Mapper(p => {
p.user = _db.Queryable().Where(o => o.Id == p.userId).First();
}).OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult.SqlSugarPageResult(data);
}
///
/// 新建打卡记录
///
/// 参数
///
[HttpPost("")]
public async Task Create([FromBody] TbPunchCrInput 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;
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
///
/// 获取打卡记录无分页列表
///
/// 请求参数
///
[NonAction]
public async Task GetNoPagingList([FromQuery] TbPunchListQueryInput 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 queryExerciseDate = input.exerciseDate != null ? input.exerciseDate.Split(',').ToObeject>() : null;
DateTime? startExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.First()) : null;
DateTime? endExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.Last()) : null;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate >= new DateTime(startExerciseDate.ToDate().Year, startExerciseDate.ToDate().Month, startExerciseDate.ToDate().Day, 0, 0, 0))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate <= new DateTime(endExerciseDate.ToDate().Year, endExerciseDate.ToDate().Month, endExerciseDate.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.code), p => p.Code.Contains(input.code))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.Select(it=> new TbPunchListOutput
{
id = it.Id,
userId=it.UserId,
exerciseDate=it.ExerciseDate,
code=it.Code,
totalTime=it.TotalTime,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
type=it.Type,
}).MergeTable().OrderBy(sidx+" "+input.sort).ToListAsync();
return data;
}
///
/// 导出打卡记录
///
/// 请求参数
///
[HttpGet("Actions/Export")]
public async Task Export([FromQuery] TbPunchListQueryInput 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\":\"userId\"},{\"value\":\"练习日期\",\"field\":\"exerciseDate\"},{\"value\":\"编号\",\"field\":\"code\"},{\"value\":\"做题总时长\",\"field\":\"totalTime\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"修改时间\",\"field\":\"lastModifyTime\"},{\"value\":\"状态\",\"field\":\"type\"},]".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] TbPunchUpInput 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;
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);
}
}
}