You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

378 lines
19 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
  1. package com.example.demo.serviceImpl;
  2. import com.example.demo.domain.entity.Statistics;
  3. import com.example.demo.domain.vo.WorkbenchCard;
  4. import com.example.demo.domain.vo.WorkbenchFullStatistics;
  5. import com.example.demo.domain.vo.WorkbenchMarketCard;
  6. import com.example.demo.domain.vo.WorkbenchMarketGraph;
  7. import com.example.demo.mapper.StatisticsMapper;
  8. import com.example.demo.mapper.WorkBenchMapper;
  9. import com.example.demo.service.GeneralService;
  10. import com.example.demo.service.StatisticsService;
  11. import com.example.demo.service.WorkbenchService;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.cache.annotation.Cacheable;
  16. import org.springframework.data.redis.core.RedisTemplate;
  17. import org.springframework.stereotype.Service;
  18. import java.time.LocalDate;
  19. import java.time.DayOfWeek;
  20. import java.time.LocalDateTime;
  21. import java.time.LocalTime;
  22. import java.time.ZoneId;
  23. import java.util.*;
  24. import java.util.function.Function;
  25. import java.util.stream.Collectors;
  26. /**
  27. * @program: gold-java
  28. * @ClassName WorkbenchServiceImpl
  29. * @description:
  30. * @author: Ethan
  31. * @create: 202506-18 10:47
  32. * @Version 1.0
  33. **/
  34. @Service
  35. public class WorkbenchServiceImpl implements WorkbenchService {
  36. private static final Logger log = LoggerFactory.getLogger(GeneralServiceImpl.class);
  37. private final RedisTemplate<String, WorkbenchCard> redisTemplate;
  38. @Autowired
  39. private WorkBenchMapper workBenchMapper;
  40. @Autowired
  41. private StatisticsMapper statisticsMapper;
  42. @Autowired
  43. public WorkbenchServiceImpl(RedisTemplate<String, WorkbenchCard> redisTemplate, StatisticsMapper statisticsMapper) {
  44. this.redisTemplate = redisTemplate;
  45. this.statisticsMapper = statisticsMapper;
  46. }
  47. private static final String CACHE_KEY = "workbench_card_cache";
  48. @Override
  49. public List<String> getAdminMarket(String account) {
  50. try {
  51. String market = workBenchMapper.getAdminMarket(account);
  52. if (market == null) {
  53. throw new Exception("没有地区权限");
  54. }
  55. List<String> list = Arrays.asList(market.split(","));
  56. //判断是否是总部
  57. if (list != null && list.contains("总部")) {
  58. List<String> allMarkets = workBenchMapper.getMarket(); // 获取所有地区
  59. allMarkets.remove("总部"); // 先移除可能存在的总部
  60. allMarkets.add(0, "总部"); // 将总部添加到列表第一位
  61. list = allMarkets; // 更新list
  62. }
  63. return list;
  64. } catch (Exception e) {
  65. // 记录日志
  66. log.error("获取地区权限失败", e);
  67. // 重新抛出异常,或者根据需要返回一个默认值或空列表
  68. throw new RuntimeException("获取地区权限失败", e);
  69. }
  70. }
  71. @Override
  72. public WorkbenchCard getCard( List<String> markets) {
  73. Date date=new Date();
  74. // 获取开始时间和结束时间(当天)
  75. LocalDateTime startOfDay = LocalDateTime.now().with(LocalTime.MIN);
  76. LocalDateTime endOfDay = startOfDay.plusDays(1).minusSeconds(1);
  77. // 获取开始时间和结束时间(昨天)
  78. LocalDateTime startOfYday = startOfDay.minusDays(1);
  79. LocalDateTime endOfYday = endOfDay.minusDays(1);
  80. // 批量获取统计数据
  81. //当天的统计数据
  82. List<Statistics> currentStatsList = statisticsMapper.selectByMarketsAndDate(markets,
  83. Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()),
  84. Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant()));
  85. //昨天的统计数据
  86. List<Statistics> ydayStatsList = statisticsMapper.selectByMarketsAndDate(markets,
  87. Date.from(startOfYday.atZone(ZoneId.systemDefault()).toInstant()),
  88. Date.from(endOfYday.atZone(ZoneId.systemDefault()).toInstant()));
  89. // 将 List<Statistics> 转换为 Map<String, Statistics>,以market为键,保留第一个出现的数据
  90. Map<String, Statistics> currentStatsMap = currentStatsList.stream()
  91. .collect(Collectors.toMap(Statistics::getMarket, Function.identity(), (existing, replacement) -> existing));
  92. //转换昨日统计数据为Map<>
  93. Map<String, Statistics> ydayStatsMap = ydayStatsList.stream()
  94. .collect(Collectors.toMap(Statistics::getMarket, Function.identity(), (existing, replacement) -> existing));
  95. // 并行处理市场列表,创建市场卡片列表
  96. List<WorkbenchMarketCard> marketCards = markets.parallelStream()
  97. .filter(Objects::nonNull)
  98. .map(market -> createWorkbenchMarketCard(
  99. market,
  100. currentStatsMap.getOrDefault(market, null),
  101. ydayStatsMap.getOrDefault(market, null),
  102. new Date()))
  103. .collect(Collectors.toList());
  104. Integer sumWow= calculateAllWeekOverWeek(date,markets);
  105. Integer sumDaily=calculateAllDayOverDay(date, markets);
  106. Date updateTime = findLatestUpdateTime(currentStatsList);
  107. return new WorkbenchCard(marketCards, new ArrayList<>(), markets, new Date(), new Date(),sumWow,sumDaily,updateTime);
  108. }
  109. @Override
  110. public WorkbenchCard getCardCache(List<String> markets) {
  111. //从缓存中获取工作台数据
  112. WorkbenchCard cached = redisTemplate.opsForValue().get(CACHE_KEY);
  113. //有缓存直接返回缓存数据
  114. if (cached != null) {
  115. System.out.println("读取缓存数据: " + new Date());
  116. return cached;
  117. }
  118. //没缓存获取新数据并存入缓存
  119. try {
  120. //获取新的工作台数据
  121. WorkbenchCard freshData = getCard(markets);
  122. //存入缓存,一小时后过期(与统计表更新时间对应)
  123. redisTemplate.opsForValue().set(CACHE_KEY, freshData, 1, java.util.concurrent.TimeUnit.HOURS);
  124. System.out.println("刷新缓存并存储新数据: " + new Date());
  125. return freshData;
  126. } catch (Exception e) {
  127. System.err.println("查询数据库失败,尝试使用旧缓存数据或抛出异常:" + e.getMessage());
  128. throw e; // 或者你可以选择返回上次的缓存数据(如果有)
  129. }
  130. }
  131. /*
  132. 获取卡片数据
  133. */
  134. @Override
  135. public WorkbenchMarketCard createWorkbenchMarketCard(String market,Statistics currentStatistics, Statistics ydayStatistics, Date currentDate) {
  136. WorkbenchMarketCard card = new WorkbenchMarketCard();
  137. card.setMarket(market);
  138. if (currentStatistics != null&& ydayStatistics != null) {
  139. // 卡片一:当前金币相关
  140. card.setCurrentPermanent(currentStatistics.getCurrentPermanent());//余量-永久金币
  141. card.setCurrentFreeJune(currentStatistics.getCurrentFreeJune()); //余量-免费六月金币
  142. card.setCurrentFreeDecember(currentStatistics.getCurrentFreeDecember()); //余量-免费十二月金币
  143. card.setCurrentTask(currentStatistics.getCurrentTask()); //余量-任务金币
  144. card.setCurrentFree(card.getCurrentFreeJune() + card.getCurrentFreeDecember()); //余量-免费金币
  145. card.setCurrentGold(card.getCurrentPermanent() + card.getCurrentFree() + card.getCurrentTask()); //余量-总金币
  146. card.setDailyChange(currentStatistics.getDailyChange()); //较前一日变化
  147. // 卡片二:充值相关
  148. card.setRecharge(ydayStatistics.getRecharge()); //充值-昨日充值
  149. card.setMoney(ydayStatistics.getMoney()); //充值-昨日金额(永久)
  150. card.setYearlyRecharge(currentStatistics.getYearlyRecharge()); // 充值-全年累计充值
  151. card.setYearlyMoney(currentStatistics.getYearlyMoney()); // 充值-全年累计金额(永久)//充值-全年累计金额(永久)
  152. // 卡片三:消费与退款
  153. card.setConsumePermanent(ydayStatistics.getConsumePermanent());//昨日消费-永久金币
  154. card.setConsumeFreeJune(ydayStatistics.getConsumeFreeJune());//昨日消费-免费六月金币
  155. card.setConsumeFreeDecember(ydayStatistics.getConsumeFreeDecember());//昨日消费-免费十二月金币
  156. card.setConsumeTask(ydayStatistics.getConsumeTask());//昨日消费-任务金币
  157. card.setRefundPermanent(ydayStatistics.getRefundPermanent());//昨日退款-永久金币
  158. card.setRefundFreeJune(ydayStatistics.getRefundFreeJune());//昨日退款-免费六月金币
  159. card.setRefundFreeDecember(ydayStatistics.getRefundFreeDecember());//昨日退款-免费十二月金币
  160. card.setRefundTask(ydayStatistics.getRefundTask());//昨日退款-任务金币
  161. //昨日总消费
  162. int totalConsume = card.getConsumePermanent() + card.getConsumeFreeJune() + card.getConsumeFreeDecember() + card.getConsumeTask();
  163. //昨日总退款
  164. int totalRefund = card.getRefundPermanent() + card.getRefundFreeJune() + card.getRefundFreeDecember() + card.getRefundTask();
  165. card.setDailyReduce(totalConsume - totalRefund);//昨日总消耗
  166. card.setYearlyConsume(currentStatistics.getYearlyConsume()); // 年累计消费
  167. card.setYearlyRefund(currentStatistics.getYearlyRefund()); // 年累计退款
  168. card.setYearlyReduce(card.getYearlyConsume() - card.getYearlyRefund());//年累计消耗
  169. // 卡片四:人头数相关
  170. card.setRechargeNum(currentStatistics.getRechargeNum());//当天充值人数
  171. card.setYdayRechargeNum(ydayStatistics.getRechargeNum()); //昨日充值人数
  172. card.setFirstRecharge(ydayStatistics.getFirstRecharge()); //昨日充值人数中首充的数量
  173. card.setYearlyRechargeNum(ydayStatistics.getYearlyRechargeNum()); //年累计充值人数-至昨天
  174. // 周环比、日同比
  175. card.setWow(calculateWeekOverWeek(market, currentDate));
  176. card.setDaily(calculateDayOverDay(market, currentDate));
  177. //更新时间
  178. card.setUpdateTime(currentStatistics.getUpdateTime());
  179. }
  180. return card;
  181. }
  182. @Override
  183. public WorkbenchCard getGraph( Date startDate, Date endDate, List<String> markets) {
  184. if (markets == null || markets.isEmpty()) {
  185. return new WorkbenchCard(new ArrayList<>(), new ArrayList<>(), markets, startDate, endDate,0,0,new Date());
  186. }
  187. // 单次批量查询
  188. List<WorkbenchFullStatistics> statsList = workBenchMapper.getFullStatisticsByMarketAndDate1(markets, startDate, endDate);
  189. // 构建 map: market -> statistics
  190. Map<String, WorkbenchFullStatistics> statMap = statsList.stream()
  191. .collect(Collectors.toMap(WorkbenchFullStatistics::getMarket, Function.identity()));
  192. // 构建最终结果
  193. List<WorkbenchMarketGraph> marketGraphs = new ArrayList<>();
  194. for (String market : markets) {
  195. WorkbenchFullStatistics stats = statMap.getOrDefault(market, new WorkbenchFullStatistics());
  196. Map<String, Integer> sums = new HashMap<>();
  197. sums.put("recharge", stats.getTotalRecharge() != null ? stats.getTotalRecharge() : 0);
  198. sums.put("money", stats.getTotalMoney() != null ? stats.getTotalMoney() : 0);
  199. sums.put("rFree", sums.get("recharge") - sums.get("money"));
  200. sums.put("cPermanent", stats.getTotalConsumePermanent() != null ? stats.getTotalConsumePermanent() : 0);
  201. sums.put("cFree", stats.getTotalConsumeFree() != null ? stats.getTotalConsumeFree() : 0);
  202. sums.put("cTask", stats.getTotalConsumeTask() != null ? stats.getTotalConsumeTask() : 0);
  203. sums.put("consume", sums.get("cPermanent") + sums.get("cFree") + sums.get("cTask"));
  204. WorkbenchMarketGraph graph = new WorkbenchMarketGraph();
  205. graph.setMarket(market);
  206. graph.setSumRechargePermanent(sums.get("money"));
  207. graph.setSumRechargeFree(sums.get("rFree"));
  208. graph.setSumConsumePermanent(sums.get("cPermanent"));
  209. graph.setSumConsumeFree(sums.get("cFree"));
  210. graph.setSumConsumeTask(sums.get("cTask"));
  211. graph.setSumConsume(sums.get("consume"));
  212. marketGraphs.add(graph);
  213. }
  214. return new WorkbenchCard(new ArrayList<>(), marketGraphs, markets, startDate, endDate,0,0,new Date());
  215. }
  216. /*
  217. 获取该日期该市场的日环比
  218. */
  219. @Override
  220. public Integer calculateDayOverDay(String market, Date date) {
  221. //传入日期的数据
  222. LocalDateTime startTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().with(LocalTime.MIN);
  223. LocalDateTime endTime= startTime.plusDays(1).minusSeconds(1);
  224. Statistics currentStatistics = statisticsMapper.selectByMarketAndDate(market,
  225. Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant()),
  226. Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant()));
  227. //空数据或数量为零,为避免0除数错误,返回增长率为0
  228. if (currentStatistics == null || currentStatistics.getRechargeNum() == null) {
  229. return 0;
  230. }
  231. Date yesterday = addDays(date, -1); //传入日期减一,昨天
  232. Statistics yesterdayStatistics = statisticsMapper.selectByMarketAndDate(market,
  233. Date.from(yesterday.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().with(LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant()),
  234. Date.from(yesterday.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().with(LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant()));
  235. //空数据或数量为零,为避免0除数错误,返回增长率为0
  236. if (yesterdayStatistics == null || yesterdayStatistics.getRechargeNum() == null || yesterdayStatistics.getRechargeNum() == 0) {
  237. return 0;
  238. }
  239. //计算增长率
  240. double rate = ((double) (currentStatistics.getRechargeNum() - yesterdayStatistics.getRechargeNum()) / yesterdayStatistics.getRechargeNum()) * 100;
  241. return (int) Math.round(rate);
  242. }
  243. // 计算所有市场总体日环比
  244. @Override
  245. public Integer calculateAllDayOverDay(Date date,List<String> markets) {
  246. //获取今天的开始时间和结束时间
  247. LocalDateTime startTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().with(LocalTime.MIN);
  248. LocalDateTime endTime= startTime.plusDays(1).minusSeconds(1);
  249. //获取地区列表
  250. // List<String> markets = generalService.getMarket();
  251. int currentTotal = 0; //今日所有地区总的充值人数
  252. int yesterdayTotal = 0; //昨日所有地区总的充值人数
  253. Date yesterday = addDays(date, -1);
  254. //过去昨天的开始时间和结束时间
  255. LocalDateTime ydayStartTime = yesterday.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().with(LocalTime.MIN);
  256. LocalDateTime ydayEndTime= ydayStartTime.plusDays(1).minusSeconds(1);
  257. for (String market : markets) {
  258. currentTotal += statisticsMapper.countRechargeNum(market,
  259. Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant()),
  260. Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant()));
  261. yesterdayTotal += statisticsMapper.countRechargeNum(market,
  262. Date.from(ydayStartTime.atZone(ZoneId.systemDefault()).toInstant()),
  263. Date.from(ydayEndTime.atZone(ZoneId.systemDefault()).toInstant()));
  264. }
  265. if (yesterdayTotal == 0) return 0; // 避免除以零的情况
  266. double rate = ((double)(currentTotal - yesterdayTotal) / yesterdayTotal) * 100;
  267. return (int)Math.round(rate);
  268. }
  269. /*
  270. 获取该日期该市场的周环比
  271. */
  272. @Override
  273. public Integer calculateWeekOverWeek(String market, Date date) {
  274. //获取传入日期所在周的周一
  275. Date thisWeekStart = getStartOfWeek(date);
  276. //获取传入日期上一周的周一
  277. Date lastWeekStart = addDays(thisWeekStart, -7);
  278. // 获取本周周一至今天的充值人数总和
  279. int thisWeekTotal = statisticsMapper.countRechargeNum(market, thisWeekStart, date);
  280. // 获取上周同一时间段的充值人数总和
  281. int lastWeekTotal = statisticsMapper.countRechargeNum(market, lastWeekStart, addDays(date, -7));
  282. if (lastWeekTotal == 0) {
  283. return 0; // 避免除以零的情况
  284. }
  285. double rate = ((double) (thisWeekTotal - lastWeekTotal) / lastWeekTotal) * 100;
  286. return (int) Math.round(rate);
  287. }
  288. /*
  289. 获取该天总体的的周环比
  290. */
  291. @Override
  292. public Integer calculateAllWeekOverWeek( Date date,List<String> markets) {
  293. int thisWeekTotal = 0; //本周至当天充值人数
  294. int lastWeekTotal = 0; //上周至当天充值人数
  295. //获取本周周一
  296. Date thisWeekStart = getStartOfWeek(date);
  297. //获取传入日期上一周的周一
  298. Date lastWeekStart = addDays(thisWeekStart, -7);
  299. for (String market : markets) {
  300. // 获取本周周一至今天的充值人数总和
  301. thisWeekTotal += statisticsMapper.countRechargeNum(market, thisWeekStart, date);
  302. // 获取上周同一时间段的充值人数总和
  303. lastWeekTotal += statisticsMapper.countRechargeNum(market, lastWeekStart, addDays(date, -7));
  304. }
  305. if (lastWeekTotal == 0) {
  306. return 0; // 避免除以零的情况
  307. }
  308. double rate = ((double) (thisWeekTotal - lastWeekTotal) / lastWeekTotal) * 100;
  309. return (int) Math.round(rate);
  310. }
  311. @Override
  312. public Date addDays(Date date, int days) {
  313. Calendar cal = Calendar.getInstance();
  314. cal.setTime(date); //设置日期为传入的日期
  315. cal.add(Calendar.DATE, days); //传入日期加上多少天
  316. return cal.getTime(); //返回处理后的日期
  317. }
  318. @Override
  319. public Date getStartOfWeek(Date date) {
  320. // 将 Date 转换为 LocalDate
  321. LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
  322. // 获取周一作为一周的第一天
  323. DayOfWeek firstDayOfWeek = DayOfWeek.MONDAY;
  324. // 返回所在周的第一天,转换回Date格式
  325. return Date.from(localDate.with(firstDayOfWeek)
  326. .atStartOfDay(ZoneId.systemDefault())
  327. .toInstant());
  328. }
  329. //获取最近的更新时间
  330. private Date findLatestUpdateTime(List<Statistics> statsList) {
  331. // 使用流式处理来找到最新的 updateTime
  332. Optional<Date> latestUpdateTime = statsList.stream()
  333. .map(Statistics::getUpdateTime)
  334. .filter(Objects::nonNull)
  335. .max(Date::compareTo);
  336. return latestUpdateTime.orElse(new Date(0)); // 如果没有找到,则返回一个较早的时间点
  337. }
  338. }