package org.agt.module.license.service.license;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.agt.module.license.dal.dataobject.alert.AlertDO;
import org.agt.module.license.dal.dataobject.license.LicenseDO;
import org.agt.module.license.dal.mysql.alert.AlertMapper;
import org.agt.module.license.dal.mysql.license.LicenseMapper;
import org.agt.module.license.enums.LicenseStatusEnum;
import org.agt.module.system.api.mail.MailSendApi;
import org.agt.module.system.api.mail.dto.MailSendSingleToUserReqDTO;
import org.agt.module.system.api.notify.NotifyMessageSendApi;
import org.agt.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @description: License 定时任务
 * @author: cyc
 * @since: 2025-07-28
 */
@Slf4j
@Component
public class LicenseTask {

    @Resource
    private LicenseServiceImpl licenseService;

    @Resource
    private AlertMapper alertMapper;

    @Resource
    private LicenseMapper licenseMapper;

    @Resource
    private MailSendApi mailSendApi;

    @Resource
    private NotifyMessageSendApi notifySendApi;

    @Scheduled(cron = "*/6 * * * * ?")
    public void task() {
        licenseService.genLicenseTask();
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void remind() {
        log.info("开始查询马上到期提醒的License");
        List<AlertDO> alertList = alertMapper.selectList(Wrappers.<AlertDO>lambdaQuery().eq(AlertDO::getStatus, 1));
        Optional<AlertDO> alertOptional = alertList.stream().findFirst();
        if (alertOptional.isPresent()) {
            AlertDO alertDO = alertOptional.get();

            List<Integer> days = alertDO.getDays();
            List<Long> users = alertDO.getUsers();
            String templateCode = alertDO.getTemplateCode();

            List<LicenseDO> licenseList = licenseMapper.selectList(Wrappers.<LicenseDO>lambdaQuery()
                    .eq(LicenseDO::getStatus, LicenseStatusEnum.COMPLETED.getCode())
                    .gt(LicenseDO::getExpiryDate, LocalDateTime.now()));

            for (LicenseDO licenseDO : licenseList) {
                for (Integer day : days) {
                    long between = LocalDateTimeUtil.between(LocalDateTime.now(), licenseDO.getExpiryDate(), ChronoUnit.DAYS);
                    if (between == day) {
                        for (Long userId : users) {
                            // 1. 准备参数
                            Map<String, Object> templateParams = new HashMap<>();
                            templateParams.put("sn", licenseDO.getSerialNo());
                            templateParams.put("days", day);

                            log.info("已发送到期提醒邮件：{}", licenseDO.getSerialNo());
                            // 2. 发送邮件
                            mailSendApi.sendSingleMailToAdmin(new MailSendSingleToUserReqDTO()
                                    .setUserId(userId).setTemplateCode(templateCode).setTemplateParams(templateParams));

                            // 发送站内信
                            notifySendApi.sendSingleMessageToAdmin(new NotifySendSingleToUserReqDTO()
                                    .setUserId(userId).setTemplateCode(templateCode).setTemplateParams(templateParams));
                        }

                    }

                }
            }
        }

        licenseService.genLicenseTask();
    }
}
