package com.zfire.jiasm.syncdata.sendmessage;


import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.dao.mapper.SendGreeSmsMapper;
import com.zfire.jiasm.syncdata.plus.entity.FaOrderSms;
import com.zfire.jiasm.syncdata.plus.entity.SmsRecord;
import com.zfire.jiasm.syncdata.plus.service.SmsRecordService;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.SMSSelfManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 发短信 - 自建工单发短信 - 联通
 * fa_order_sms
 */
@Slf4j
@Component
public class SendMessage {
    @Value("${SMSSelf_templateId}")
    private String templateId;
    @Value("${zjgdmsgsendc}")
    private String zjgdmsgsendc = "";

    @Autowired
    private SMSSelfManager smsSelfManager;
    @Resource
    SendGreeSmsMapper sendGreeSmsMapper;
    @Resource
    SmsRecordService smsRecordService;
    @Resource
    PublicService publicService;





    @Scheduled(fixedDelayString = "${zjgdmsgsend}")
    public void processXQDLTask() throws Exception {
        if (zjgdmsgsendc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 提取数据
        List<FaOrderSms> records = sendGreeSmsMapper.getData();
        log.info("开始自建工单短信发送: \uF0B7{}",sdf.format(new Date()));
        for (FaOrderSms item : records){
            Integer synTimes = item.getSynTimes();
            // 9:登陆 10:注册 11:修改信息  短信类型限制时间段
            if (!(item.getYhlb() != null && (item.getYhlb() == 9 || item.getYhlb() == 10 || item.getYhlb() == 11))) {
                if (!smsSelfManager.checkCanSend()) {
                    log.info("自建工单短信不到发送时间段[syn_task_no=" + item.getSynTaskNo() + "]");
                    return;
                }
            }
            if (synTimes == null) {
                synTimes = 0;
            }
            try {
                String[] datas = new String[1];
                datas[0] = item.getFsnr();
                // 用户手机号，？，自生成主键，随机发送码，发送的内容
                smsSelfManager.templateSMS(item.getSjid(), templateId,item.getSynTaskNo(),
                        item.getFsma(), datas);
                // sendSuccess(item);
                publicService.upSmsRecordSendTime(item.getSynTaskNo(),item.getSjid(),new Date());
            } catch (Exception ex) {
                log.error("自建工单短信发送失败[syn_task_no=" + item.getSynTaskNo() + "]", ex);
                sendError(item, synTimes, ex);
            }
        }
        log.info("自建工单短信发送结束: \uF0B7{}",sdf.format(new Date()));
    }

    private void sendError(FaOrderSms item, Integer synTimes, Exception ex) {
        synTimes++;
        FaOrderSms up = new FaOrderSms();
        up.setSynTaskNo(item.getSynTaskNo());
        up.setSynTimes(synTimes);
        up.setSynTime(new Date());
        up.setSynErrMsg(ex.getMessage());
        up.updateById();
    }

    private void sendSuccess(FaOrderSms item) {
        FaOrderSms up = new FaOrderSms();
        up.setSynTaskNo(item.getSynTaskNo());
        up.setSynStatus(1);
        up.setSynTime(new Date());
        up.updateById();
        // 工单的发送时间同步
        SmsRecord record = smsRecordService.lambdaQuery()
                .eq(SmsRecord::getId,item.getSynTaskNo())
                .last("limit 1")
                .one();
        if (record !=null){
            record.setSendTime(new Date());
            record.updateById();
        }
    }


}
