package cn.iocoder.yudao.module.server.job;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.server.controller.admin.policycommunications.vo.PolicyCommunicationsPageReqVO;
import cn.iocoder.yudao.module.server.controller.admin.smsrecord.vo.SmsRecordPageReqVO;
import cn.iocoder.yudao.module.server.controller.admin.smsrecord.vo.SmsRecordSaveReqVO;
import cn.iocoder.yudao.module.server.dal.dataobject.smsrecord.SmsRecordDO;
import cn.iocoder.yudao.module.server.service.policycommunications.PolicyCommunicationsServiceImpl;
import cn.iocoder.yudao.module.server.service.smsrecord.SmsRecordService;
import cn.iocoder.yudao.module.server.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

// PolicyCommunicationsTask.java
@Component
@Slf4j
public class SendSmsJob implements JobHandler {
    
    @Resource
    private PolicyCommunicationsServiceImpl policyCommunicationsService;

    @Resource
    private SmsRecordService smsRecordService;
    @Resource
    private SMSUtils smsUtils;

    @TenantIgnore
    public String execute(String param) throws Exception {
        SmsRecordPageReqVO reqVO = new SmsRecordPageReqVO();
        reqVO.setPageNo(1);
        reqVO.setPageSize(Integer.MAX_VALUE); // 查询所有
        reqVO.setSendStatus(0); // 待发送状态
        PageResult<SmsRecordDO> smsRecordPage = smsRecordService.getSmsRecordPage(reqVO);
        for (SmsRecordDO smsRecordDO : smsRecordPage.getList()) {
            boolean b = smsUtils.sendMsg(smsRecordDO.getMobile(), smsRecordDO.getContent());
//            boolean b = true;
            if (b) {
                SmsRecordSaveReqVO updateReqVO = new SmsRecordSaveReqVO();
                updateReqVO.setId(smsRecordDO.getId());
                updateReqVO.setSendStatus(1);
                updateReqVO.setSendTime(LocalDateTime.now());// 发送时间
                smsRecordService.updateSmsRecord(updateReqVO);
            }else {
                SmsRecordSaveReqVO updateReqVO = new SmsRecordSaveReqVO();
                updateReqVO.setId(smsRecordDO.getId());
                updateReqVO.setSendStatus(2);
                smsRecordService.updateSmsRecord(updateReqVO);
            }
        }
        return "发通知短信";
    }
}