using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Ewide.Core;
using Ewide.Core.Util;
using Furion;
using Furion.ClayObject.Extensions;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using Vote.Services.Dto;
using Vote.Services.Entities;
namespace Vote.Services.ApiController
{
///
/// 共赴宁波之春
///
[ApiDescriptionSettings("ningbozhichun", Order = 0)]
[Route("/gb/yjb/api/ningbozhichun")]
public class NbZhiChunService : IDynamicApiController
{
private readonly IRepository repPerson;
private readonly IRepository repSmsCode;
private readonly IMemoryCache _memoryCache;
///
///
///
///
public NbZhiChunService(IRepository _repNingbo, IRepository _repSmsCode, IMemoryCache memoryCache)
{
repPerson = _repNingbo;
this.repSmsCode = _repSmsCode;
_memoryCache = memoryCache;
}
///
/// 提交
///
///
[HttpPost]
[UnitOfWork]
[Microsoft.AspNetCore.Authorization.AllowAnonymous]
[Route("sendcode")]
public async Task SendCode(NbzcSendCodeInput args)
{
//var data = await repSmsCode.DetachedEntities.Where(p => p.phone == args.phone && !p.IsDeleted && p.expire_time > DateTime.Now)
// .FirstOrDefaultAsync();
//_ = (data != null) ? throw Oops.Oh("已存在此号码的有效发送记录,不可重复发送") : 1;
var lastSend = await repSmsCode.DetachedEntities.Where(p => p.phone == args.phone && !p.IsDeleted).OrderByDescending(a => a.CreatedTime).FirstOrDefaultAsync();
_ = lastSend != null && DateTime.Now <= lastSend.CreatedTime.Value.AddMinutes(1) ? throw Oops.Oh("发送过于频繁,请1分钟后再试") : 1;
//_ = (await repPerson.DetachedEntities.Where(a => !a.IsDeleted && (a.phone == args.phone || a.cardno == args.cardno)).CountAsync() > 0) ? throw Oops.Oh("您已提交,无需再次获取验证码") : 1;
string _timeCacheKey = "sms_token_" + args.phone;
var code = new Random().Next(1001, 9999);
if (App.GetConfig("NingboZhiChun:OpenSms") == 1)
{
var cacheTokenValue = _memoryCache.Get(_timeCacheKey);
if (string.IsNullOrEmpty(cacheTokenValue))
{
var rslt = await App.GetConfig("NingboZhiChun:SmsTokenUrl").SetBody(new { username = App.GetConfig("NingboZhiChun:SmsAccount"), password = App.GetConfig("NingboZhiChun:SmsPwd") }, "application/json").SetHttpMethod(HttpMethod.Post).SendAsStringAsync();
cacheTokenValue = Newtonsoft.Json.Linq.JObject.Parse(rslt)["data"]["token"].ToString();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(100));
_memoryCache.Set(_timeCacheKey, cacheTokenValue, cacheEntryOptions);
}
var sendrslt = await App.GetConfig("NingboZhiChun:SmsSendUrl")
.SetHttpMethod(HttpMethod.Post)
.SetHeaders(new Dictionary { { "Authorization", "Bearer " + cacheTokenValue } })
.SetBody(new { phone_number = args.phone, sms_content = $"您的验证码是:{code},10分钟内有效。" })
.SendAsStringAsync();
if (!Newtonsoft.Json.Linq.JObject.Parse(sendrslt)["issuccess"].Value())
throw Oops.Oh("验证码短信发送失败.");
}
await new Entities.nbzc_sms_code
{
code = code.ToString(),
CreatedTime = DateTime.Now,
expire_time = DateTime.Now.AddMinutes(10),
IsDeleted = false,
phone = args.phone
}.InsertOrUpdate();
return true;
}
///
/// 提交
///
///
[HttpPost]
[UnitOfWork]
[Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task SubmitSubmit(NbzcSubmitInput args)
{
var lastSend = await repSmsCode.DetachedEntities.Where(p => p.phone == args.phone && !p.IsDeleted).OrderByDescending(a => a.CreatedTime).FirstOrDefaultAsync();
_ = (lastSend == null || lastSend.code != args.code || lastSend.expire_time < DateTime.Now) ? throw Oops.Oh("验证码错误或已失效") : 1;
//var list = args.projects.Adapt>();
//删除这个专家上次提交的结果
//或者提示不能再次提交
_ = (await repPerson.DetachedEntities.Where(a => !a.IsDeleted && (a.phone == args.phone || a.cardno == args.cardno)).CountAsync() > 0) ? throw Oops.Oh("您已提交,无需再次提交") : 1;
var now = DateTime.Now;
var model = new Entities.nbzc_person
{
address = args.address,
phone = args.phone,
cardno = args.cardno,
CreatedTime = DateTime.Now,
date = args.date,
hangye = args.hangye,
IsDeleted = false,
line = args.line,
name = args.name,
weixin_number = args.weixin_number
};
model = await model.InsertOrUpdate();
lastSend.IsDeleted = true;
await repSmsCode.UpdateIncludeAsync(lastSend, new string[] { nameof(lastSend.IsDeleted) });
var token = JWTEncryption.Encrypt(new Dictionary() // 加密
{
{ "UserId", model.Id },
{ "Account",model.phone }
});
return new { success = true, token };
}
///
/// 提交
///
///
[HttpPost]
[UnitOfWork]
[Microsoft.AspNetCore.Authorization.AllowAnonymous]
[Route("getmyinfo")]
public async Task GetMyInfo(NbzcGetMyInfoInput args)
{
var newToken = args.token;
nbzc_person entity = null;
if (!string.IsNullOrEmpty(args.token))
{
var tokenData = JWTEncryption.ReadJwtToken(args.token);
_ = (tokenData == null) ? throw Oops.Oh("您还没有提交过或者手机号码填写错误") : 1;
var userId = tokenData.Claims.Where(a => a.Type == "UserId").FirstOrDefault().Value;
entity = await repPerson.DetachedEntities.Where(a => a.Id == userId).FirstOrDefaultAsync();
}
else
{
_ = (string.IsNullOrEmpty(args.code)) ? throw Oops.Oh("验证码错误或已失效") : 1;
var lastSend = await repSmsCode.DetachedEntities.Where(p => p.phone == args.phone && !p.IsDeleted).OrderByDescending(a => a.CreatedTime).FirstOrDefaultAsync();
_ = (lastSend == null || lastSend.code != args.code || lastSend.expire_time < DateTime.Now) ? throw Oops.Oh("验证码错误或已失效") : 1;
entity = await repPerson.DetachedEntities.Where(a => a.phone == args.phone && !a.IsDeleted).FirstOrDefaultAsync();
newToken = JWTEncryption.Encrypt(new Dictionary()
{
{ "UserId", entity.Id },
{ "Account",entity.phone }
});
}
return new { success = true, entity, token = newToken };
}
///
/// 获取时间线路人数
///
///
[HttpPost]
[UnitOfWork]
[Microsoft.AspNetCore.Authorization.AllowAnonymous]
[Route("getnumber")]
public async Task GetNumber(NbzcGetNumberInput args)
{
var n = await repPerson.DetachedEntities.Where(a => !a.IsDeleted && a.date == args.date).CountAsync();
return new { success = true, n = App.GetConfig("NingboZhiChun:TotalCount") - n };
}
///
/// 获取清单
///
///
[HttpPost]
[UnitOfWork]
[Route("GetPersonList")]
public async Task GetPersonList(NbzcGetListInput args)
{
var list = await repPerson.DetachedEntities.Where(a => !a.IsDeleted).OrderByDescending(a => a.CreatedTime).ToListAsync();
return list;
}
///
/// 导出Excel
///
///
[HttpPost]
[UnitOfWork]
[Route("export_excel")]
public async Task ExportExcel(NbzcGetListInput args)
{
var list = await repPerson.DetachedEntities.Where(a => !a.IsDeleted).OrderByDescending(a => a.CreatedTime).ToListAsync();
var filepath = Tools.ExcelHelper.WriteExcelNingBoZhiChun(list);
return new FileStreamResult(new FileStream(filepath, FileMode.Open), "application/octet-stream") { FileDownloadName = filepath };
}
}
}