using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using VOL.Entity.DomainModels;
using YD_WeChatApplet.Api.Entitys;
using YD_WeChatApplet.Api.SmartSportsEntitys;
using YD_WeChatApplet.Api.Utilities;
using YD_WeChatApplet.Commons.Dto;
using YD_WeChatApplet.Commons.Dto.ClientSide;
using YD_WeChatApplet.Commons.Dto.HomeWork;
using YD_WeChatApplet.Commons.Dto.Patriarch;
using YD_WeChatApplet.Commons.Dto.Resource;
using YD_WeChatApplet.Commons.Dto.School;
using YD_WeChatApplet.Commons.Dto.SportsTest;
using YD_WeChatApplet.Commons.Dto.Teacher;
using YD_WeChatApplet.Commons.Enum;
using YD_WeChatApplet.Commons.MemoryCaches;
using YD_WeChatApplet.Commons.Utils;
using YD_WeChatApplet.Context;
using YD_WeChatApplet.Services;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace YD_WeChatApplet.Api.Services.Impl
{
///
/// 用户端
///
public class ClientSideService : IClientSideService
{
public UserContext _userContext;
public SmartSportsContext _sportsContext;
private readonly IMapper _mapper;
private readonly ICaching _caching;
public ClientSideService(UserContext userContext, SmartSportsContext sportsContext, IMapper mapper, ICaching caching)
{
_userContext = userContext;
_sportsContext = sportsContext;
_mapper = mapper;
_caching = caching;
}
///
/// 获取场馆列表
///
///
///
///
public async Task> StadiumList(GetStadiumListDto dto)
{
//double centerLat = dto.Latitude;
//double centerLng = dto.Longitude;
//double radiusInKm = 10.0;
var query = _sportsContext.Stadium;
//.Where(x =>
// 6371 * 2 * Math.Asin(Math.Sqrt(
// Math.Pow(Math.Sin((x.Latitude - centerLat) * Math.PI / 180 / 2), 2) +
// Math.Cos(centerLat * Math.PI / 180) *
// Math.Cos(x.Latitude * Math.PI / 180) *
// Math.Pow(Math.Sin((x.Longitude - centerLng) * Math.PI / 180 / 2), 2)
// )) <= radiusInKm
//);
var totalCount = await query.CountAsync();
var list = await query
.Select(x => new StadiumListDto
{
Id = x.Id,
StadiumName = x.StadiumName,
Address = x.Address,
CoverImage = x.StadiumResourceList.Select(x => x.Url).FirstOrDefault(),
Latitude = x.Latitude,
Longitude = x.Longitude
})
.Skip((dto.PageIndex - 1) * dto.PageSize)
.Take(dto.PageSize)
.ToListAsync();
return new PageDataDto
{
Total = totalCount,
Datas = list
};
}
///
/// 场馆详情
///
///
///
public async Task StadiumDetails(int stadiumId)
{
var res = await _sportsContext.Stadium.Where(x => x.Id == stadiumId).Select(x => new StadiumDetailsDto()
{
Id = x.Id,
StadiumName = x.StadiumName,
Address = x.Address,
CoverImage = x.CoverImage,
Intro = x.Intro,
Latitude = x.Latitude,
Longitude = x.Longitude,
PhoneNo = x.PhoneNo,
StadiumResourceList = x.StadiumResourceList.Select(x => new StadiumResourceDto()
{
Id = x.Id,
Type = x.Type,
Url = x.Url
}).ToList()
}).FirstOrDefaultAsync();
return res;
}
///
/// 教学类别
///
///
public async Task> CurricularTaxonomyList()
{
var res = await _sportsContext.CurricularTaxonomy.Select(x => new ComboBoxDto()
{
Id = x.Id,
Name = x.TaxonomyName
}).ToListAsync();
return res;
}
///
/// 教学列表
///
///
///
public async Task> CurricularList(CurricularDto dto)
{
var query = _sportsContext.Curricular;
var totalCount = await query.CountAsync();
var list = await query
.Select(x => new CurricularListDto()
{
Id = x.Id,
TaxonomyId = x.TaxonomyId,
CurricularName = x.CurricularName,
CoverImage = x.CoverImage,
Hits = x.Hits,
Url = x.Url
}).Where(x => x.TaxonomyId == dto.TaxonomyId)
.Skip((dto.PageIndex - 1) * dto.PageSize)
.Take(dto.PageSize)
.ToListAsync();
return new PageDataDto
{
Total = totalCount,
Datas = list
};
}
///
/// 热门视频
///
///
public async Task> PopularCurricularList()
{
var res = await _sportsContext.PopularCurricular
.Join(_sportsContext.Curricular, a => a.CurricularId, s => s.Id, (a, s) => new CurricularListDto()
{
Id = a.Id,
CurricularName = s.CurricularName,
CoverImage = s.CoverImage,
Url = s.Url,
Hits = s.Hits
}).ToListAsync();
return res;
}
///
/// 视频播放
///
///
///
public async Task VideoPlay(int curricularId)
{
var entity = await _sportsContext.Curricular.Where(x => x.Id == curricularId).FirstAsync();
entity.Hits = entity.Hits + 1;
_sportsContext.Curricular.Update(entity);
await _sportsContext.SaveChangesAsync();
}
///
/// 场馆预约
///
///
///
public async Task StadiumVisiting(int stadiumId)
{
if (stadiumId == 0)
throw new Exception("场馆信息有误");
var userId = UserLoginContext.Current.UserId;
var user = await _userContext.Users.FirstAsync(x => x.User_Id == userId);
var stadiumVisiting = await _sportsContext.StadiumVisiting.FirstOrDefaultAsync(x => x.PhoneNo == user.PhoneNo && x.StadiumId == stadiumId);
if (stadiumVisiting == null)
{
var entity = new Y_StadiumVisiting()
{
StadiumId = stadiumId,
Status = 1,
PhoneNo = user.PhoneNo,
UserName = user.UserTrueName,
VisitingTime = DateTime.Now
};
await _sportsContext.StadiumVisiting.AddAsync(entity);
await _sportsContext.SaveChangesAsync();
}
}
///
/// 各项目排行
///
///
///
public async Task> Ranking(int categoryId)
{
var res = await _userContext.ExerciseData
.Where(x => x.WorkType == categoryId)
.GroupBy(x => x.UserId)
.Select(g => new RankingDto()
{
UserId = g.Key,
UserName = g.FirstOrDefault().UserName,
Value = g.Sum(x => x.Amount ?? 0)
})
.OrderByDescending(x => x.Value)
.ToListAsync();
return res;
}
///
/// 文章列表
///
///
///
public async Task> Articles(PageDto dto)
{
//try
//{
// // 获取 access_token
// var accessToken = await GetAccessTokenAsync();
// int offset = dto.PageIndex - 1 == 0 ? 0 : (dto.PageIndex - 1) * dto.PageSize - 1;
// // 获取文章列表
// var articles = await GetArticlesAsync(accessToken, offset, dto.PageSize);
// // 返回文章列表数据
// return new { articles };
//}
//catch (Exception ex)
//{
// return new { message = "Error retrieving articles", error = ex.Message };
//}
var res = new PageDataDto();
res.Total = await _sportsContext.Article.CountAsync();
var data = await _sportsContext.Article.Select(x => new ArticlesDto()
{
Id = x.Id,
Abstract = x.Abstract,
ArticleUrl = x.ArticleUrl,
CoverImage = x.CoverImage,
Title = x.Title,
UpdateDate = x.UpdateDate
})
.OrderByDescending(x => x.UpdateDate)
.Skip((dto.PageIndex - 1) * dto.PageSize)
.Take(dto.PageSize)
.ToListAsync();
res.Datas = data;
return res;
}
// 获取 access_token
public async Task GetAccessTokenAsync()
{
var userId = UserLoginContext.Current.UserId;
var key = $"access_token_{userId}";
var token = _caching.Get(key).ToString();
if (!string.IsNullOrWhiteSpace(token))
{
return token;
}
// 2. 缓存不存在,请求微信接口
var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppSettings.WeChatQA.Appid}&secret={AppSettings.WeChatQA.Secret}";
var response = await HttpManager.HttpGetAsync(url, null);
dynamic data = JsonConvert.DeserializeObject(response);
if (data?.access_token != null)
{
token = data.access_token;
// 微信官方返回中有 expires_in,一般是7200秒(2小时)
int expiresInSeconds = data.expires_in ?? 7200;
// 3. 写入缓存,提前1分钟过期
_caching.Set(key, token, expiresInSeconds);
return token;
}
throw new Exception("获取 access_token 失败");
}
// 获取文章列表
public async Task