package com.mortals.xhx.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.busiz.req.SmsThirdPartyReq;
import com.mortals.xhx.busiz.rsp.ApiSmsResp;
import com.mortals.xhx.common.code.SendStatusEnum;
import com.mortals.xhx.module.alarm.model.AlarmSmsSendEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static com.mortals.framework.util.HttpUtil.HEADER_CONTENT_TYPE;

/**
 * 短信发送任务
 *
 * @author: zxfei
 * @date: 2022/4/28 10:56
 * @description:
 **/
@Slf4j
@AllArgsConstructor
public class SendSmsTask implements Runnable {

    /**
     * 短信消息
     */
    private SmsThirdPartyReq smsThirdPartyReq;

    /**
     * 接口地址
     */
    private String sendUrl;

    @Override
    public void run() {
        String resp = null;
        AlarmSmsSendEntity alarmSmsSendEntityResp = new AlarmSmsSendEntity();
        alarmSmsSendEntityResp.setId(smsThirdPartyReq.getAlarmSmsSendId());
        try {
            Map<String, String> header = new HashMap<>();
            header.put(HEADER_CONTENT_TYPE, "application/json");
            resp = HttpUtil.doPost(sendUrl, header, JSON.toJSONString(smsThirdPartyReq));
            ApiSmsResp<Void> apiSmsResp = JSON.parseObject(resp, new TypeReference<ApiSmsResp<Void>>() {
            });
            if (apiSmsResp.getCode() == 1) {
                alarmSmsSendEntityResp.setSendStatus(SendStatusEnum.发送成功.getValue());
            } else {
                alarmSmsSendEntityResp.setSendStatus(SendStatusEnum.发送失败.getValue());
                log.info("短信提交失败,req:{}, resp:{}",JSON.toJSONString(smsThirdPartyReq), resp);
            }
            //发送成功添加到响应队列，由线程批量更新
            SmsQueueManager.offerRespQueue(alarmSmsSendEntityResp);
            log.debug("resp:{}", resp);
        } catch (Exception e) {
            alarmSmsSendEntityResp.setSendStatus(SendStatusEnum.发送失败.getValue());
            SmsQueueManager.offerRespQueue(alarmSmsSendEntityResp);
            log.error("异常:", e);
        }
    }
}
