/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */

package com.qunzhixinxi.hnqz.daemon.quartz.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qunzhixinxi.hnqz.daemon.quartz.constants.HnqzQuartzEnum;
import com.qunzhixinxi.hnqz.daemon.quartz.entity.SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth;
import com.qunzhixinxi.hnqz.daemon.quartz.entity.SingleMemberSettleAmountOverrunInSeveralMonths;
import com.qunzhixinxi.hnqz.daemon.quartz.entity.SingleMemberSettleSameAmountInSeveralMonths;
import com.qunzhixinxi.hnqz.daemon.quartz.entity.SingleMemberWithoutSuchTaskTypesInSeveralMonths;
import com.qunzhixinxi.hnqz.daemon.quartz.entity.WmTask;
import com.qunzhixinxi.hnqz.daemon.quartz.mapper.SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonthMapper;
import com.qunzhixinxi.hnqz.daemon.quartz.mapper.SingleMemberSettleAmountOverrunInSeveralMonthsMapper;
import com.qunzhixinxi.hnqz.daemon.quartz.mapper.SingleMemberSettleSameAmountInSeveralMonthsMapper;
import com.qunzhixinxi.hnqz.daemon.quartz.mapper.SingleMemberWithoutSuchTaskTypesInSeveralMonthsMapper;
import com.qunzhixinxi.hnqz.daemon.quartz.service.*;
import com.qunzhixinxi.hnqz.daemon.quartz.zhuqu.ZhuaquTest;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 郑健楠
 */
@Slf4j
@Component("demo")
@AllArgsConstructor
public class SpringBeanTaskDemo {
	private final WmScorePackageStatusService wmScorePackageStatusService;
	private final WmScorePackageSettleNoteService scorePackageSettleNoteService;
	private final WmScorePackageService wmScorePackageService;
	private final ZhuaquTest zhuaquTest;
	private final WmTaskTypeService wmTaskTypeService;
	private final WmTaskService wmTaskService;
	private final WmWkArticleService wmWkArticleService;
	private final WmStatisticsService wmStatisticsService;
	private final SingleMemberSettleSameAmountInSeveralMonthsMapper singleMemberSettleSameAmountInSeveralMonthsMapper;
	private final SingleMemberSettleAmountOverrunInSeveralMonthsMapper singleMemberSettleAmountOverrunInSeveralMonthsMapper;
	private final SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonthMapper singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonthMapper;
	private final SingleMemberWithoutSuchTaskTypesInSeveralMonthsMapper singleMemberWithoutSuchTaskTypesInSeveralMonthsMapper;

//	/**
//	 * 测试Spring Bean的演示方法
//	 */
//	@SneakyThrows
//	public String demoMethod(String para) {
//		log.info("测试于:{}，输入参数{}", LocalDateTime.now(), para);
//		wmScorePackageStatusService.changePackageStatus();
//		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
//	}

	@SneakyThrows
	public String changePackageStatusTask(String para) {
		log.info("测试于:{}，输入参数{}", LocalDateTime.now(), para);
		wmScorePackageStatusService.changePackageStatus();
		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}


	@SneakyThrows
	public String getArtileTask(String para) {
		log.info("测试于:{}，输入参数{}", LocalDateTime.now(), para);
		zhuaquTest.init_main(para);
		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}

	@SneakyThrows
	public String changeTaskRule(String para) {
		log.info("测试于:{}，输入参数{}", LocalDateTime.now(), para);
		wmTaskTypeService.changeTaskTypeInfo();
		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}

	@SneakyThrows
	public String buildTaskImg(String para) {
		log.info("测试于:{}，输入参数{}", LocalDateTime.now(), para);
		wmTaskService.buildTaskImg(para);
		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}

	/**
	 * 每日GMVs统计
	 *
	 * @param para
	 * @return
	 */
	@SneakyThrows
	public String dailyGMVsStatistic(String para) {
		log.info("dailyGMVsStatistic开始于:{}，输入参数{}", LocalDateTime.now(), para);
		wmStatisticsService.dailyGMVsStatistics(para);
		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}

	@SneakyThrows
	public String setHotArtileTask(String para) {
		log.info("setHotArtileTask开始于:{}，输入参数{}", LocalDateTime.now(), para);
		wmWkArticleService.setHotArtileTask(para);
		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}

	/**
	 * 同一用户，连续多月结算金额相同
	 *
	 * @param para 参数（月数）
	 * @return 运行结果
	 */
	@SneakyThrows
	public String singleMemberSettleSameAmountInSeveralMonths(String para) {
		// 校验参数
		if (StrUtil.isBlank(para)) {
			log.error("参数缺失");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		int period = Integer.parseInt(para.trim());

		if (period < 2) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		// 计算查询时间
		LocalDate now = LocalDateTime.now().toLocalDate().with(TemporalAdjusters.firstDayOfNextMonth());
		LocalDateTime startTime = LocalDateTime.of(now.minusMonths(period), LocalTime.MIN);
		LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MIN).minusSeconds(1);

		log.info("singleMemberSettleSameAmountInSeveralMonths开始于:{}，输入参数{}", LocalDateTime.now(), para);

		List<SingleMemberSettleSameAmountInSeveralMonths> result = scorePackageSettleNoteService.singleMemberSettleSameAmountInSeveralMonths(startTime, endTime);

		if (CollUtil.isNotEmpty(result)) {
			List<SingleMemberSettleSameAmountInSeveralMonths> history = singleMemberSettleSameAmountInSeveralMonthsMapper.selectList(Wrappers.<SingleMemberSettleSameAmountInSeveralMonths>lambdaQuery().between(SingleMemberSettleSameAmountInSeveralMonths::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN), LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
			// 删除历史记录
			log.warn("删除当期的历史记录：{}", history);
			if (CollUtil.isNotEmpty(history)) {
				List<Integer> ids = history.stream().mapToInt(SingleMemberSettleSameAmountInSeveralMonths::getRecordId).boxed().collect(Collectors.toList());
				singleMemberSettleSameAmountInSeveralMonthsMapper.deleteBatchIds(ids);
			}

			result.forEach(e -> {
				e.setPeriod(period);
				singleMemberSettleSameAmountInSeveralMonthsMapper.insert(e);
			});
		}

		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
	}

	/**
	 * 同一用户，连续多月结算金额超过限额
	 *
	 * @param para 参数（月数和限额）
	 * @return 运行结果
	 */
	@SneakyThrows
	public String singleMemberSettleAmountOverrunInSeveralMonths(String para) {
		// 校验参数
		if (StrUtil.isBlank(para)) {
			log.error("参数缺失");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		if (!para.contains(StrUtil.COMMA)) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		List<String> params = StrUtil.split(para.trim(), StrUtil.COMMA);

		if (params.size() != 2) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		int period = Integer.parseInt(params.get(0));
		BigDecimal limit = new BigDecimal(params.get(1));

		if (period < 1 || limit.doubleValue() < 0.01) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		// 计算查询时间
		LocalDate now = LocalDateTime.now().toLocalDate().with(TemporalAdjusters.firstDayOfNextMonth());
		LocalDateTime startTime = LocalDateTime.of(now.minusMonths(period), LocalTime.MIN);
		LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MIN).minusSeconds(1);

		log.info("singleMemberSettleAmountOverrunInSeveralMonths开始于:{}，输入参数{}", LocalDateTime.now(), para);

		List<SingleMemberSettleSameAmountInSeveralMonths> result = scorePackageSettleNoteService.singleMemberSettleAmountOverrunInSeveralMonths(startTime, endTime, limit);

		if (CollUtil.isNotEmpty(result)) {
			List<SingleMemberSettleAmountOverrunInSeveralMonths> history = singleMemberSettleAmountOverrunInSeveralMonthsMapper.selectList(Wrappers.<SingleMemberSettleAmountOverrunInSeveralMonths>lambdaQuery().between(SingleMemberSettleAmountOverrunInSeveralMonths::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN), LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
			// 删除历史记录
			log.warn("删除当期的历史记录：{}", history);
			if (CollUtil.isNotEmpty(history)) {
				List<Integer> ids = history.stream().mapToInt(SingleMemberSettleAmountOverrunInSeveralMonths::getRecordId).boxed().collect(Collectors.toList());
				singleMemberSettleAmountOverrunInSeveralMonthsMapper.deleteBatchIds(ids);
			}

			result.forEach(e -> {
				SingleMemberSettleAmountOverrunInSeveralMonths singleMemberSettleAmountOverrunInSeveralMonths
						= BeanUtil.copyProperties(e, SingleMemberSettleAmountOverrunInSeveralMonths.class);
				singleMemberSettleAmountOverrunInSeveralMonths.setPeriod(period);
				singleMemberSettleAmountOverrunInSeveralMonths.setPlatformLimit(limit);
				singleMemberSettleAmountOverrunInSeveralMonths.setCreateTime(LocalDateTime.now());
				singleMemberSettleAmountOverrunInSeveralMonthsMapper.insert(singleMemberSettleAmountOverrunInSeveralMonths);
			});
		}

		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();

	}


	/**
	 * 同一企业，当前月给多个用户支付相同金额
	 *
	 * @param para 参数（统计人数）
	 * @return 运行结果
	 */
	@SneakyThrows
	public String singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth(String para) {

		// 校验参数
		if (StrUtil.isBlank(para)) {
			log.error("参数缺失");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		int memberCount = Integer.parseInt(para.trim());

		if (memberCount <= 1) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		// 计算查询时间
		int period = 1;
		LocalDate now = LocalDateTime.now().toLocalDate().with(TemporalAdjusters.firstDayOfNextMonth());
		LocalDateTime startTime = LocalDateTime.of(now.minusMonths(period), LocalTime.MIN);
		LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MIN).minusSeconds(1);

		log.info("singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth开始于:{}，输入参数{}", LocalDateTime.now(), para);

		List<SingleMemberSettleSameAmountInSeveralMonths> result = scorePackageSettleNoteService.singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth(startTime, endTime, memberCount);

		if (CollUtil.isNotEmpty(result)) {
			List<SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth> history = singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonthMapper.selectList(Wrappers.<SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth>lambdaQuery().between(SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN), LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
			// 删除历史记录
			log.warn("删除当期的历史记录：{}", history);
			if (CollUtil.isNotEmpty(history)) {
				List<Integer> ids = history.stream().mapToInt(SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth::getRecordId).boxed().collect(Collectors.toList());
				singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonthMapper.deleteBatchIds(ids);
			}

			result.forEach(e -> {
				SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth
						= BeanUtil.copyProperties(e, SingleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth.class);
				singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth.setPeriod(period);
				singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth.setMemberCount(memberCount);
				singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth.setCreateTime(LocalDateTime.now());
				singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonthMapper.insert(singleEnterpriseSettleSameAmountForSeveralMembersInCurrentMonth);
			});
		}

		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();

	}


	/**
	 * 同一用户，连续多月没有指定任务类型
	 *
	 * @param para 参数（周期和任务类型）
	 * @return 运行结果
	 */
	@SneakyThrows
	public String singleMemberWithoutSuchTaskTypesInSeveralMonths(String para) {

		// 校验参数
		if (StrUtil.isBlank(para)) {
			log.error("参数缺失");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		if (!para.contains(StrUtil.COMMA)) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		List<String> params = StrUtil.split(para, StrUtil.COMMA);

		if (params.size() < 2) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		int period = Integer.parseInt(params.get(0));
		if (period < 2) {
			log.error("参数错误");
			return HnqzQuartzEnum.JOB_LOG_STATUS_FAIL.getType();
		}

		List<String> typeList = params.subList(1, params.size());

		// 计算查询时间
		LocalDate now = LocalDateTime.now().toLocalDate().with(TemporalAdjusters.firstDayOfNextMonth());
		LocalDateTime startTime = LocalDateTime.of(now.minusMonths(period), LocalTime.MIN);
		LocalDateTime endTime = LocalDateTime.of(now, LocalTime.MIN).minusSeconds(1);

		log.info("singleMemberWithoutSuchTaskTypesInSeveralMonths开始于:{}，输入参数{}", LocalDateTime.now(), para);

		List<Map<String, Object>> result = wmTaskService.singleMemberWithoutSuchTaskTypesInSeveralMonths(startTime, endTime, typeList);

		if (CollUtil.isNotEmpty(result)) {
			List<SingleMemberWithoutSuchTaskTypesInSeveralMonths> history = singleMemberWithoutSuchTaskTypesInSeveralMonthsMapper.selectList(Wrappers.<SingleMemberWithoutSuchTaskTypesInSeveralMonths>lambdaQuery().between(SingleMemberWithoutSuchTaskTypesInSeveralMonths::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN), LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
			// 删除历史记录
			log.warn("删除当期的历史记录：{}", history);
			if (CollUtil.isNotEmpty(history)) {
				List<Integer> ids = history.stream().mapToInt(SingleMemberWithoutSuchTaskTypesInSeveralMonths::getRecordId).boxed().collect(Collectors.toList());
				singleMemberWithoutSuchTaskTypesInSeveralMonthsMapper.deleteBatchIds(ids);
			}

			String types = String.join(StrUtil.COMMA, typeList.toArray(new String[0]));

			result.forEach(e -> {
				SingleMemberWithoutSuchTaskTypesInSeveralMonths singleMemberWithoutSuchTaskTypesInSeveralMonths
						= BeanUtil.mapToBean(e, SingleMemberWithoutSuchTaskTypesInSeveralMonths.class,true, new CopyOptions());

				List<WmTask> list = wmTaskService.list(Wrappers.<WmTask>lambdaQuery().eq(WmTask::getScorePackageId, e.get(singleMemberWithoutSuchTaskTypesInSeveralMonths.getPackageId())).orderByDesc(WmTask::getCreateTime));

				if (CollUtil.isNotEmpty(list)){
					singleMemberWithoutSuchTaskTypesInSeveralMonths.setFirstTaskTime(list.get(0).getCreateTime());
				}
				singleMemberWithoutSuchTaskTypesInSeveralMonths.setPeriod(period);
				singleMemberWithoutSuchTaskTypesInSeveralMonths.setTypeList(types);
				singleMemberWithoutSuchTaskTypesInSeveralMonths.setCreateTime(LocalDateTime.now());
				singleMemberWithoutSuchTaskTypesInSeveralMonthsMapper.insert(singleMemberWithoutSuchTaskTypesInSeveralMonths);
			});
		}

		return HnqzQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();

	}


}
