package com.ktg.quartz.task;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ktg.common.core.domain.entity.SysUser;
import com.ktg.common.utils.StringUtils;
import com.ktg.iscs.config.EmailSender;
import com.ktg.iscs.domain.IsCheckTask;
import com.ktg.iscs.domain.IsCheckTaskMail;
import com.ktg.iscs.domain.IsMailSendTaskItem;
import com.ktg.iscs.domain.IsMaterialsCabinet;
import com.ktg.iscs.domain.vo.mail.MailVO;
import com.ktg.iscs.service.*;
import com.ktg.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时发送检查物资柜提醒邮件
 *
 * @author CGJ
 */
@Slf4j
@Component("sendEmailsTask")
public class SendEmailsTask {

    @Autowired
    private IIsCheckTaskService iIsCheckTaskService;
    @Autowired
    private IIsMaterialsCabinetService iIsMaterialsCabinetService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IIsCheckTaskMailService isCheckTaskMailService;
    @Autowired
    private IIsMailSendTaskItemService iIsMailSendTaskItemService;
    @Autowired
    private IIsSystemAttributeService isSystemAttributeService;

    public void checkMaterialsCabinet(Long checkId) {
        Assert.notNull(checkId, "无效参数！");
        // 1.获取数据
        IsCheckTask checkTask = iIsCheckTaskService.getById(checkId);
        if (checkTask != null && StringUtils.isNotBlank(checkTask.getCabinetIdStr()) && StringUtils.isNotBlank(checkTask.getUserIdStr())) {
            // 开始解析参数
            List<Long> cabinetIds = Arrays.stream(checkTask.getCabinetIdStr().split(","))
                    .map(Long::parseLong) // 将每个字符串转换为Long
                    .collect(Collectors.toList());
            List<Long> userIds = Arrays.stream(checkTask.getUserIdStr().split(","))
                    .map(Long::parseLong) // 将每个字符串转换为Long
                    .collect(Collectors.toList());
            List<IsMaterialsCabinet> isMaterialsCabinets = iIsMaterialsCabinetService.listByIds(cabinetIds);
            List<SysUser> sysUsers = iSysUserService.listByIds(userIds);
            String text = isMaterialsCabinets.stream().map(IsMaterialsCabinet::getCabinetName).collect(Collectors.toList()).toString();
            for (SysUser sysUser : sysUsers) {
                if (StringUtils.isNotBlank(sysUser.getEmail())) {
                    MailVO mailVo = isSystemAttributeService.getMailVo();
                    EmailSender.sendLocalMail(sysUser.getEmail(), mailVo,
                            "定期检查物资柜提醒！", "物资柜：" + text);
                    IsCheckTaskMail isCheckTaskMail = new IsCheckTaskMail();
                    isCheckTaskMail.setChackId(checkId);
                    isCheckTaskMail.setUserId(sysUser.getUserId());
                    isCheckTaskMail.setEmailSendState(1);
                    isCheckTaskMail.setEmailContent("物资柜：" + text);
                    isCheckTaskMailService.save(isCheckTaskMail);
                }
            }

        }
    }

    /**
     * 扫描邮件任务，如果未取消，未发送并且已经到达发送时间的邮件则进行发送
     */
    public void scanSendMails() {
        // 1.获取当前时间
        Date date = new Date();
        // 2.查询符合条件的数据
        List<IsMailSendTaskItem> sendTaskItems = iIsMailSendTaskItemService.list(Wrappers.<IsMailSendTaskItem>lambdaQuery()
                .eq(IsMailSendTaskItem::getSendStatus, 0)
                .eq(IsMailSendTaskItem::getIsCancelled, 0)
                .le(IsMailSendTaskItem::getScheduledSendTime, date)
                .orderByAsc(IsMailSendTaskItem::getSendTime));
        if (!sendTaskItems.isEmpty()) {
            for (IsMailSendTaskItem sendTaskItem : sendTaskItems) {
                // 3.查询接收人的邮箱
                SysUser user = iSysUserService.getById(sendTaskItem.getSendToUserId());
                if (user == null) {
                    iIsMailSendTaskItemService.update(Wrappers.<IsMailSendTaskItem>lambdaUpdate()
                            .eq(IsMailSendTaskItem::getMailId, sendTaskItem.getMailId())
                            .set(IsMailSendTaskItem::getIsCancelled, 2)
                            .set(IsMailSendTaskItem::getCancelTime, date)
                            .set(IsMailSendTaskItem::getRemark, "[该用户不存在！]"));
                    continue;
                }
                if (StringUtils.isBlank(user.getEmail())) {
                    iIsMailSendTaskItemService.update(Wrappers.<IsMailSendTaskItem>lambdaUpdate()
                            .eq(IsMailSendTaskItem::getMailId, sendTaskItem.getMailId())
                            .set(IsMailSendTaskItem::getIsCancelled, 2)
                            .set(IsMailSendTaskItem::getCancelTime, date)
                            .set(IsMailSendTaskItem::getRemark, "[该用户邮箱信息缺失！]"));
                    continue;
                }
                // 4.开始发送
                try {
                    MailVO mailVo = isSystemAttributeService.getMailVo();
                    EmailSender.sendLocalMail(user.getEmail(), mailVo, sendTaskItem.getTitle(), sendTaskItem.getContent());
                    // 4.1 修改成已发送
                    iIsMailSendTaskItemService.update(Wrappers.<IsMailSendTaskItem>lambdaUpdate()
                            .eq(IsMailSendTaskItem::getMailId, sendTaskItem.getMailId())
                            .set(IsMailSendTaskItem::getSendStatus, 1)
                            .set(IsMailSendTaskItem::getSendTime, date));
                } catch (Exception e) {
                    log.error("发送邮件位置异常-----" + e);
                    // 4.2如果发送出现异常，取消当前邮箱，标记取消原因
                    iIsMailSendTaskItemService.update(Wrappers.<IsMailSendTaskItem>lambdaUpdate()
                            .eq(IsMailSendTaskItem::getMailId, sendTaskItem.getMailId())
                            .set(IsMailSendTaskItem::getIsCancelled, 3)
                            .set(IsMailSendTaskItem::getCancelTime, date)
                            .set(IsMailSendTaskItem::getRemark, sendTaskItem.getRemark() + e));
                }
            }
        }
        log.info("扫描邮件发送任务完成！");
    }



}
