package com.qmth.paper.library.common.util;

import com.qmth.boot.api.exception.ApiException;
import com.qmth.boot.core.sms.model.SmsSendRequest;
import com.qmth.boot.core.sms.model.SmsSendResponse;
import com.qmth.boot.core.sms.service.SmsService;
import com.qmth.paper.library.common.config.DictionaryConfig;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 短信发送工具类
 */
@Component
public class SmsSendUtil {

    private static final Logger log = LoggerFactory.getLogger(SmsSendUtil.class);

    @Resource
    private SmsService smsService;

    @Resource
    DictionaryConfig dictionaryConfig;


    /**
     * 短信发送接口
     *
     * @param phoneNumber   发送手机号
     * @param templateCode  短信模版编号
     * @param templateParam 模版变量
     * @return bizId 本次操作业务标识
     */
    public String sendSms(String phoneNumber, String templateCode, Map<String, Object> templateParam) throws UnsupportedEncodingException {
        validDictionaryConfig(dictionaryConfig);
        SmsSendRequest smsSendRequest = new SmsSendRequest();
        // 必填，发送手机号
        smsSendRequest.setPhoneNumber(phoneNumber);
        // 必填，短信签名
        String signName = dictionaryConfig.smsDomain().getSmsSignName();
        smsSendRequest.setSignName(signName);
        // 必填，短信模版编号
        smsSendRequest.setTemplateCode(templateCode);
        //模版变量，可选
        if (templateParam != null && !templateParam.isEmpty()) {
            smsSendRequest.setTemplateParam(templateParam);
        }

        try {
            SmsSendResponse smsSendResponse = smsService.sendSms(smsSendRequest);
            if (smsSendResponse == null) {
                throw ExceptionResultEnum.ERROR.exception("短信发送失败");
            }
            return smsSendResponse.getBizId();
        } catch (ApiException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 校验文件存储配置参数
     *
     * @param dictionaryConfig dictionaryConfig
     */
    private void validDictionaryConfig(DictionaryConfig dictionaryConfig) {
        if (dictionaryConfig != null) {
            if (StringUtils.isBlank(dictionaryConfig.smsDomain().getSmsSignName())) {
                throw ExceptionResultEnum.SIGN_NAME_NOT_SETTING.exception();
            }
        }
    }

}
