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.Setter;
import lombok.extern.slf4j.Slf4j;
import org.agt.framework.common.pojo.CommonResult;
import org.agt.module.license.dal.dataobject.alert.AlertDO;
import org.agt.module.license.dal.dataobject.customer.CustomerDO;
import org.agt.module.license.dal.dataobject.license.LicenseDO;
import org.agt.module.license.dal.dataobject.project.ProjectDO;
import org.agt.module.license.dal.mysql.alert.AlertMapper;
import org.agt.module.license.dal.mysql.customer.CustomerMapper;
import org.agt.module.license.dal.mysql.license.LicenseMapper;
import org.agt.module.license.dal.mysql.project.ProjectMapper;
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.agt.module.system.api.user.AdminUserApi;
import org.agt.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * @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 ProjectMapper projectMapper;

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private MailSendApi mailSendApi;

    @Resource
    private NotifyMessageSendApi notifySendApi;

    @Resource
    private AdminUserApi adminUserApi;

    /**
     * 邮件的开关，默认为 true
     */
    @Value("${agt.domain:http://192.168.9.50}")
    @Setter
    private String domain;

    @Scheduled(cron = "*/5 * * * * ?")
    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();
            String templateCode = alertDO.getTemplateCode();

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

            Map<Long, List<Map<String, Object>>> userMap = new HashMap<>();
            for (LicenseDO licenseDO : licenseList) {

                ProjectDO projectDO = projectMapper.selectById(licenseDO.getProjectId());
                CustomerDO customerDO = customerMapper.selectById(projectDO.getCustomerId());
                Set<Long> users = new HashSet<>();
                if (projectDO.getBusinessOwner() != null) {
                    users.add(projectDO.getBusinessOwner());
                }
                if (projectDO.getTechnicalOwnerA() != null) {
                    users.add(projectDO.getTechnicalOwnerA());
                }
                if (licenseDO.getApprover() != null) {
                    users.add(licenseDO.getApprover());
                }
                for (Integer day : days) {
                    long between = LocalDateTimeUtil.between(LocalDateTime.now(), licenseDO.getExpiryDate(), ChronoUnit.DAYS) + 1;
                    if (between == day) {
                        for (Long userId : users) {
                            // 1. 准备参数
                            Map<String, Object> templateParams = new HashMap<>();
                            templateParams.put("sn", licenseDO.getSerialNo());
                            templateParams.put("days", day);
                            templateParams.put("url", "http://192.168.9.50#/license");
                            templateParams.put("id", licenseDO.getId());

                            try {
                                templateParams.put("expiryDate", licenseDO.getExpiryDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                                if (projectDO.getBusinessOwner() != null) {
                                    CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(projectDO.getBusinessOwner());
                                    templateParams.put("businessOwner", user.getData().getNickname());
                                }
                                if (projectDO.getTechnicalOwnerA() != null) {
                                    CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(projectDO.getTechnicalOwnerA());
                                    templateParams.put("technicalOwnerA", user.getData().getNickname());
                                }
                            } catch (Exception e) {
                                log.error("到期提醒邮件的到期时间和负责人查询错误", e);
                            }

                            templateParams.put("customer", customerDO.getName());
                            templateParams.put("project", projectDO.getName());
                            log.info("已发送到期提醒邮件：{}", licenseDO.getSerialNo());

                            if (userMap.containsKey(userId)) {
                                userMap.get(userId).add(templateParams);
                            } else {
                                List<Map<String, Object>> userList = new ArrayList<>();
                                userList.add(templateParams);
                                userMap.put(userId, userList);
                            }

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

                    }

                }
            }

            String text = "    <tr>\n" +
                    "      <td>%s</td>\n" +
                    "      <td>%s</td>\n" +
                    "      <td><a href=\""+ domain +"/#/license/detail?id=%s\">%s</a></td>\n" +
                    "      <td>%s</td>\n" +
                    "      <td>%s</td>\n" +
                    "      <td>%s</td>\n" +
                    "      <td>%s天</td>\n" +
                    "    </tr>";

            userMap.forEach((k, v) -> {
                v.sort(Comparator.comparingInt(c -> Integer.parseInt(c.get("days").toString())));

                StringBuilder stringBuilder = new StringBuilder("    <style>\n" +
                        "        th {\n" +
                        "            border: 2px solid black;\n" +
                        "        }\n" +
                        "        td {\n" +
                        "            border: 1px solid black;\n" +
                        "        }\n" +
                        "    </style><table border=\"1\" style=\"border-collapse: collapse; width: 100%;\">\n" +
                        "  <thead>\n" +
                        "    <tr>\n" +
                        "      <th>客户</th>\n" +
                        "      <th>项目</th>\n" +
                        "      <th>SN</th>\n" +
                        "      <th>到期时间</th>\n" +
                        "      <th>业务负责人</th>\n" +
                        "      <th>技术负责人1</th>\n" +
                        "      <th>距离到期</th>\n" +
                        "    </tr>\n" +
                        "  </thead>\n" +
                        "  <tbody>");
                for (Map<String, Object> map : v) {
                    String formatText = String.format(text, map.get("customer"), map.get("project"), map.get("id"), map.get("sn"), map.get("expiryDate"), map.get("businessOwner"), map.get("technicalOwnerA"), map.get("days"));
                    stringBuilder.append(formatText);
                }
                stringBuilder.append("  </tbody>\n" +
                        "</table>");

                mailSendApi.sendSingleMailToAdmins(new MailSendSingleToUserReqDTO()
                        .setUserId(k).setTemplateCode(templateCode).setContent(stringBuilder.toString()));
            });
        }

        licenseService.genLicenseTask();
    }

}
