package org.jeecg.modules.xxl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.adweb.common.util.AdwebRedisUtil;
import org.jeecg.modules.adweb.enquiry.constant.EnquirySendStatus;
import org.jeecg.modules.adweb.enquiry.entity.EnquiryEmailMessage;
import org.jeecg.modules.adweb.enquiry.service.IEnquiryEmailMessageService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.stereotype.Component;

/** 询盘邮件发送失败后重新发送任务 */
@Slf4j
@Component
public class EnquiryEmailSenderJob {

  @Resource private IEnquiryEmailMessageService enquiryEmailMessageService;

  @Resource private AdwebRedisUtil adwebRedisUtil;

  @Resource private ISysDictService sysDictService;

  @XxlJob("EnquiryEmailSenderJobHandler")
  public void EnquiryEmailSenderJobHandler() throws Exception {
    log.info("询盘邮件发送 EnquiryEmailSenderJob !  时间:{}", DateUtils.getTimestamp());

    String keyName = CommonConstant.ADWEB_PREFIX + this.getClass().getSimpleName();
    if (!adwebRedisUtil.lock(keyName, 60 * 60 * 1000)) {
      log.info("定时任务 {} 正在执行", this.getClass().getSimpleName());
      return;
    }

    try {

      // 重发邮件数量,默认数量
      String param = "50";

      List<DictModel> dictItems = sysDictService.queryDictItemsByCode("enquiry_email_timeout");
      int sendEmailTimeout = 30;
      int waitSendTimeout = 300;
      for (DictModel model : dictItems) {
        if ("send_email_timeout".equals(model.getText())) {
          sendEmailTimeout = Integer.parseInt(model.getValue());
        }
        if ("wait_send_timeout".equals(model.getText())) {
          waitSendTimeout = Integer.parseInt(model.getValue());
        }
      }

      // 将超过30分钟未完成发送的记录改为待发送
      Date thirtyMinBefore = DateUtil.offsetMinute(new Date(), -sendEmailTimeout);
      UpdateWrapper<EnquiryEmailMessage> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("send_status", EnquirySendStatus.SENDING);
      updateWrapper.lt("send_start_time", thirtyMinBefore);
      updateWrapper.set("send_status", EnquirySendStatus.WAIT_SEND);
      updateWrapper.set("send_start_time", null);
      enquiryEmailMessageService.update(updateWrapper);

      List<EnquiryEmailMessage> messages =
          enquiryEmailMessageService.getWaitSendEmail(waitSendTimeout, Integer.parseInt(param));

      log.info("询盘邮件发送任务,待发送邮件数量:{}", messages.size());

      if (CollUtil.isNotEmpty(messages)) {
        UpdateWrapper<EnquiryEmailMessage> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.in(
            "id", messages.stream().map(EnquiryEmailMessage::getId).collect(Collectors.toList()));
        updateWrapper1.set("send_status", EnquirySendStatus.SENDING);
        updateWrapper1.set("send_start_time", new Date());
        enquiryEmailMessageService.update(updateWrapper1);
        for (EnquiryEmailMessage message : messages) {
          enquiryEmailMessageService.sendEmailByMessage(message);
        }
      }

    } catch (Exception e) {
      log.error("询盘邮件发送任务出错", e);
    }

    adwebRedisUtil.unlock(keyName);
  }
}
