package com.storlead.sales.task.dispatch;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.encryptor.AccessKeyEncryptor;
import com.storlead.mail.pojo.entity.EmailsEntity;
import com.storlead.mail.pojo.entity.SmtpPopSettingsEntity;
import com.storlead.mail.enums.EmailBoxEnum;
import com.storlead.mail.service.EmailsService;
import com.storlead.mail.service.SmtpPopSettingsService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-11-01 15:27
 */
@Slf4j
@Component
@NoArgsConstructor
@DisallowConcurrentExecution
public class AutoSendDelayEmailTaskJob implements Job {
    @Resource
    private EmailsService emailsService;

    @Resource
    private Environment environment;

    @Resource
    private SmtpPopSettingsService smtpPopSettingsService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String active = environment.getProperty("spring.profiles.active");
        if("dev".equals(active)) {
            return ;
        }
        log.info("定时发送邮件任务开始");
        LambdaQueryWrapper<EmailsEntity> wrapper = new LambdaQueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime triggerTime = now;
        wrapper.select(EmailsEntity::getId,EmailsEntity::getSmtpPopId,EmailsEntity::getOwnerBy);
        wrapper.le(EmailsEntity::getDelaySendTime,triggerTime);
        wrapper.eq(EmailsEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(EmailsEntity::getStatus,-1);
        wrapper.eq(EmailsEntity::getFolder, EmailBoxEnum.SENTING.code);
        wrapper.isNotNull(EmailsEntity::getDelaySendTime);
        List<EmailsEntity> emailsls = emailsService.list(wrapper);
        if (CollectionUtils.isEmpty(emailsls)) {
            return;
        }
        LambdaUpdateWrapper<EmailsEntity> upEntity = new LambdaUpdateWrapper<>();
        upEntity.set(EmailsEntity::getStatus,0);
        upEntity.in(EmailsEntity::getId,emailsls.stream().map(EmailsEntity::getId).collect(Collectors.toList()));
        emailsService.update(upEntity);

        List<SmtpPopSettingsEntity> smtpPopls = smtpPopSettingsService.listByIds(emailsls.stream().map(EmailsEntity::getSmtpPopId).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(smtpPopls)) {
            return;
        }
        Map<Long,SmtpPopSettingsEntity> smtpPopMap = smtpPopls.stream().collect(Collectors.toMap(SmtpPopSettingsEntity::getId, a ->a));
        log.info("定时发送邮件任务，共{}条",emailsls.size());
        for (EmailsEntity emailVal : emailsls) {
            EmailsEntity email = emailsService.getById(emailVal.getId());
            SmtpPopSettingsEntity smtpPop = smtpPopMap.get(email.getSmtpPopId());
            AccessKeyEncryptor accessKeyEncryptor = AccessKeyEncryptor.getAccessKeyEncryptor("");
            String pass = accessKeyEncryptor.decrypt(smtpPop.getEmailPassword());
            smtpPop.setEmailPassword(pass);
            emailsService.sendEmail(email,smtpPop);
        }
    }

    public static void main(String[] args) {
        String env = System.getProperty("app.env");

        log.error("env ="+env);
    }
}
