tuiwucarrer/Admin.NET/Admin.NET.Application/Service/SysWeChatUserExtend/WeChatUserExService.cs

359 lines
14 KiB
C#

using Admin.NET.Core.Service;
using Aliyun.OSS;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using MongoDB.Bson;
using MongoDB.Driver;
using NewLife.Net.Handlers;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Flurl.Http;
namespace Admin.NET.Application.Service;
[ApiDescriptionSettings(ApplicationConst.ZYGroupName, Order = 800)]
public class WeChatUserExService : IDynamicApiController, ITransient
{
private readonly SqlSugarRepository<SysWeChatUserExtend> _rep;
private readonly SqlSugarRepository<SysWechatUser> _sysWechatUserRep;
private readonly UserManager _userManager;
private readonly IMongoDBRepository _mongoRepository;
private readonly IDistributedCache _distributed;
private readonly SqlSugarRepository<BusProvince> _busProvince;
private readonly SqlSugarRepository<SysAreaConfig> _sysAreaConfig;
private readonly SqlSugarRepository<BusSpecialistGroup> _specialist;
public WeChatUserExService(SqlSugarRepository<SysWeChatUserExtend> rep, UserManager userManager,
SqlSugarRepository<SysWechatUser> sysWechatUserRep, IMongoDBRepository mongoDBRepository, IDistributedCache distributed,
SqlSugarRepository<SysAreaConfig> sysAreaConfig, SqlSugarRepository<BusSpecialistGroup> specialist, SqlSugarRepository<BusProvince> buProvince)
{
_rep = rep;
_userManager = userManager;
_sysWechatUserRep = sysWechatUserRep;
_mongoRepository = mongoDBRepository;
_distributed = distributed;
_sysAreaConfig = sysAreaConfig;
_specialist = specialist;
_busProvince = buProvince;
}
/// <summary>
/// 保存用户获取的手机号
/// </summary>
/// <param name="userDto"></param>
/// <returns></returns>
[HttpPost]
[DisplayName("保存用户获取的手机号")]
public async Task<bool> UpdateWxInfo([FromBody] WeChatUserDto userDto)
{
var single = await _sysWechatUserRep.GetSingleAsync(c => c.Id == _userManager.UserId);
single.Mobile = userDto.Mobile;
single.UpdateTime = DateTime.Now;
single.UpdateUserName = _userManager.RealName;
single.UpdateUserId = _userManager.UserId;
return await _sysWechatUserRep.AsUpdateable(single).IgnoreColumns(true).ExecuteCommandAsync() > 0;
}
//[DisplayName("用户注销")]
//[HttpPost]
//public async Task<bool> AccountCancel()
//{
// var single = await _rep.GetSingleAsync(c => c.WxId == _userManager.UserId);
// if (single == null)
// {
// throw Oops.Oh("不存在该用户");
// }
// single.IsDelete = true;
// single.UpdateTime = DateTime.Now;
// single.UpdateUserName = _userManager.RealName;
// single.UpdateUserId = _userManager.UserId;
// return await _rep.UpdateAsync(single);
//}
/// <summary>
/// 获取用户拓展字段表
/// </summary>
/// <returns></returns>
[HttpGet]
[DisplayName("获取用户拓展字段表")]
public async Task<WeChatUserExResponseDto> UserInfo()
{
if (_userManager == null || _userManager.UserId <= 0)
{
throw Oops.Oh("用户token无效");
}
var result = new WeChatUserExResponseDto();
await PerfectInfo(new WeChatUserExRequestDto()
{
className = "test",
provinceCode = "310000",
provinceName = "上海",
schoolName = "上海中学",
score = 660,
sp = 0,
subjectGroup = "物,化,地",
Year = 2021
});
var userext = await _rep.GetFirstAsync(u => u.WxId == _userManager.UserId);
var wechatinfo = await _sysWechatUserRep.GetFirstAsync(u => u.Id == _userManager.UserId);
result.nickName = MarkPhoneUtil.MaskPhoneNumber(wechatinfo.Mobile);
// result.mobile = wechatinfo.Mobile;不给手机号
result.avatar = wechatinfo.Avatar;
result.customerType = wechatinfo.CustomerType;
//if (result.customerType == CustomerTypeEnum.Enterprise)
//{
// var spInfo = await _specialist.AsQueryable().FirstAsync(e => e.Phone == wechatinfo.Mobile && e.IsDelete == false);
// if (spInfo != null)
// {
// result.cartId = spInfo?.MajorType.ToString();
// result.nickName = spInfo?.Name;
// }
//}
//if (userext != null && !string.IsNullOrWhiteSpace(userext.ProvinceCode))
//{
// try
// {
// var province = await _busProvince.AsQueryable().FirstAsync(u => u.Code == userext.ProvinceCode);
// userext.ProvinceName = province?.Name;
// result.BatchDataUrl = string.Format("https://api.static.ycymedu.com/api/v1/batch/s/{0}.json", userext.ProvinceCode);
// //var response = await result.BatchDataUrl.SetJsonSerialization<NewtonsoftJsonSerializerProvider>().GetAsAsync<batchobject>();
// var response = await result.BatchDataUrl.GetJsonAsync<batchobject>() ;
// var batches = response.result.OrderByDescending(e => e.year).FirstOrDefault().batches;
// result.batchName = batches.Where(e => userext.expectedScore >= e.score).Any() ? batches.Where(e => userext.expectedScore >= e.score).OrderByDescending(c => c.score).FirstOrDefault().batch : "";
// result.batchScore = batches.Where(e => userext.expectedScore >= e.score).Any() ? batches.Where(e => userext.expectedScore >= e.score).OrderByDescending(c => c.score).FirstOrDefault().score : 0;
// }
// catch (Exception ex)
// {
// result.batchName = "";
// }
//}
if (userext != null)
{
result.userExtend = userext;
}
var ylist = new List<YearRule>();
DateTime dt = DateTime.Now;
DateTime fixedDate = new DateTime(dt.Year, 6, 10); // 创建当前年份的9月10日
int showdt = dt > fixedDate ? dt.Year : dt.Year - 1; // 比较当前日期与固定日期
ylist.Add(new YearRule()
{
IsDefault = true,
Year = showdt,
});
showdt--;
ylist.Add(new YearRule()
{
IsDefault = false,
Year = showdt,
});
showdt--;
ylist.Add(new YearRule()
{
IsDefault = false,
Year = showdt,
});
result.yearRules = ylist;
if (userext != null)
{
//var batchcache = await _distributed.GetAsync(CacheConst.KeyProvinceBatch + userext.ProvinceCode);
//if (batchcache == null)// 判断缓存是否存在,存在就直接返回,不存在就重新获取
//{
// var areaconfig = await _sysAreaConfig.AsQueryable().Where(e => e.IsDelete == false && e.LocationCode == userext.ProvinceCode)
// .Select(s => new ZyBatchRule()
// {
// batchName = s.BatchName,
// Count = s.Count,
// ItemCount = s.ItemCount,
// })
// .ToListAsync();
// _distributed.Set($"{CacheConst.KeyProvinceBatch}{userext.ProvinceCode}", Encoding.UTF8.GetBytes(areaconfig.ToJson()), new DistributedCacheEntryOptions()
// .SetSlidingExpiration(TimeSpan.FromHours(24)));
// result.zyBatches = areaconfig;
//}
//else
//{
// result.zyBatches = JsonConvert.DeserializeObject<List<ZyBatchRule>>(Encoding.UTF8.GetString(_distributed.Get($"{CacheConst.KeyProvinceBatch}{userext.ProvinceCode}")));
//}
}
return result;
}
[HttpPost]
[DisplayName("注销用户")]
public async Task<bool> AccountCancel()
{
var single = await _sysWechatUserRep.GetSingleAsync(c => c.Id == _userManager.UserId);
if (single == null)
{
throw Oops.Oh("不存在该用户");
}
var extend = await _rep.GetSingleAsync(c => c.WxId == _userManager.UserId);
single.IsDelete = true;
extend.IsDelete = true;
await _rep.UpdateAsync(extend);
single.UpdateTime = DateTime.Now;
single.UpdateUserName = _userManager.RealName;
single.UpdateUserId = _userManager.UserId;
return await _sysWechatUserRep.UpdateAsync(single);
}
/// <summary>
/// 修改用户头像和名字
/// </summary>
/// <returns></returns>
[HttpPost]
[DisplayName("修改用户头像和名字")]
public async Task<bool> UpdateUserAvatar([FromBody] WeChatUserAvatarDto dto)
{
var single = await _sysWechatUserRep.GetSingleAsync(c => c.Id == _userManager.UserId);
if (single == null)
{
throw Oops.Oh("不存在该用户");
}
single.Avatar = dto.Avatar;
single.NickName = dto.NickName;
single.UpdateTime = DateTime.Now;
single.UpdateUserName = _userManager.RealName;
single.UpdateUserId = _userManager.UserId;
return await _sysWechatUserRep.UpdateAsync(single);
}
/// <summary>
/// 完善用户信息
/// </summary>
/// <param name="requestDto"></param>
/// <returns></returns>
[HttpPost]
[DisplayName("完善用户信息")]
public async Task<bool> PerfectInfo([FromBody] WeChatUserExRequestDto requestDto)
{
var single = await _sysWechatUserRep.GetSingleAsync(c => c.Id == _userManager.UserId);
if (single == null)
{
throw Oops.Oh("不存在该用户");
}
DateTime dt = DateTime.Now;
DateTime fixedDate = new DateTime(dt.Year, 7, 20); // 创建当前年份的7月20日
int year = dt > fixedDate ? dt.Year : dt.Year - 1; // 比较当前日期与固定日期
// var db_client = _mongoRepository.Context.GetDatabase("zhiyuan");
// var be_json = db_client.GetCollection<ZYOneScoreOneSection>(string.Format("scoresection_{0}_{1}", requestDto.provinceCode, year));
// 动态条件列表
//var filterBuilders = new List<FilterDefinition<ZYOneScoreOneSection>>();
//if (requestDto.score.HasValue && requestDto.score > 0)
//{
// filterBuilders.Add(Builders<ZYOneScoreOneSection>.Filter.Lte(e => e.Score.Value, requestDto.score.Value));
//}
//FilterDefinition<ZYOneScoreOneSection> filter = filterBuilders.Count > 0
// ? Builders<ZYOneScoreOneSection>.Filter.And(filterBuilders)
// : new BsonDocument(); // 如果没有条件,则使用空过滤器
// var limit = await be_json.Find(filter).Sort(Builders<ZYOneScoreOneSection>.Sort.Descending(s => s.Score)).Limit(1).FirstOrDefaultAsync();
var model = await _rep.GetSingleAsync(e => e.WxId == _userManager.UserId);
if (model == null)
{
model = new SysWeChatUserExtend();
if (!string.IsNullOrWhiteSpace(requestDto.schoolName))
{
model.SchoolName = requestDto.schoolName;
}
if (!string.IsNullOrWhiteSpace(requestDto.className))
{
model.ClassName = requestDto.className;
}
if (!string.IsNullOrWhiteSpace(requestDto.provinceCode))
{
model.ProvinceCode = requestDto.provinceCode;
}
if (!string.IsNullOrWhiteSpace(requestDto.provinceName))
{
model.ProvinceName = requestDto.provinceName;
}
if (!string.IsNullOrWhiteSpace(requestDto.subjectGroup))
{
model.subjectGroup = requestDto.subjectGroup;
}
if (requestDto.Year.HasValue)
{
model.Year = requestDto.Year.Value;
}
//if (requestDto.score.HasValue)
//{
// model.expectedScore = requestDto.score.Value;
// model.Rank = limit != null ? limit.CumulativeCount : 0;
//}
if (requestDto.sp.HasValue)
{
model.sp = requestDto.sp.Value;
}
//model.CreateUserId = _userManager.UserId;
model.CreateTime = DateTime.Now;
model.CreateUserName = _userManager.RealName;
model.CreateUserId = _userManager.UserId;
model.WxId = _userManager.UserId;
return await _rep.InsertAsync(model);
}
else
{
if (!string.IsNullOrWhiteSpace(requestDto.schoolName))
{
model.SchoolName = requestDto.schoolName;
}
if (!string.IsNullOrWhiteSpace(requestDto.className))
{
model.ClassName = requestDto.className;
}
if (!string.IsNullOrWhiteSpace(requestDto.subjectGroup))
{
model.subjectGroup = requestDto.subjectGroup;
}
if (!string.IsNullOrWhiteSpace(requestDto.provinceCode))
{
model.ProvinceCode = requestDto.provinceCode;
}
if (requestDto.Year.HasValue)
{
model.Year = requestDto.Year.Value;
}
//if (requestDto.score.HasValue)
//{
// model.expectedScore = requestDto.score.Value;
// model.Rank = limit != null ? limit.CumulativeCount : 0;
//}
if (requestDto.sp.HasValue)
{
model.sp = requestDto.sp.Value;
}
model.UpdateTime = DateTime.Now;
model.UpdateUserName = _userManager.RealName;
model.UpdateUserId = _userManager.UserId;
return await _rep.UpdateAsync(model);
}
}
}