package com.ruoyi.sms.core;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sms.config.properties.SmsChineseProperties;
import com.ruoyi.sms.entity.SmsResult;
import com.ruoyi.sms.exception.SmsException;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class ChineseSmsTemplate implements SmsTemplate {
    private final SmsChineseProperties properties;

    /**
     * - 异常编号对应消息
     */
    private final Map<Integer, String> exceptionMessage = new HashMap<>();

    public ChineseSmsTemplate(SmsChineseProperties properties) {
        this.properties = properties;
        exceptionMessage.put(-1, "没有该用户账户");
        exceptionMessage.put(-2, "接口密钥不正确");
        exceptionMessage.put(-21, "MD5接口密钥加密不正确");
        exceptionMessage.put(-3, "短信数量不足");
        exceptionMessage.put(-11, "该用户被禁用");
        exceptionMessage.put(-14, "短信内容出现非法字符");
        exceptionMessage.put(-4, "手机号格式不正确");
        exceptionMessage.put(-41, "手机号码为空");
        exceptionMessage.put(-42, "短信内容为空");
        exceptionMessage.put(-51, "短信签名格式不正确");
        exceptionMessage.put(-52, "短信签名太长");
        exceptionMessage.put(-6, "IP限制");
        if (log.isInfoEnabled()) {
            try {
                log.info("正在创建[smschinese.com.cn]短信bean:\n{}",
                    JsonUtils.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(BeanCopyUtils.copy(properties, SmsChineseProperties.class)));
            } catch (Exception e) {
                log.warn("格式化短信配置异常", e);
            }
        }

    }

    @Override
    public SmsResult send(String phones, String templateId, Map<String, String> param) {
        if (StringUtils.isBlank(phones)) {
            throw new SmsException("手机号不能为空");
        }
        if (StringUtils.isBlank(templateId)) {
            throw new SmsException("模板ID不能为空");
        }
        String template = properties.getTemplates().get(templateId);
        if (template == null) {
            throw new SmsException("未知的模板ID");
        }
        String sms = template;
        if (param != null) {
            for (String name : param.keySet()) {
                sms = sms.replace("{" + name + "}", param.get(name));
            }
        }

        Map<String, Object> formMap = new HashMap<>(4);
        formMap.put("Uid", properties.getUid());
        formMap.put("Key", properties.getKey());
        formMap.put("smsMob", phones);
        formMap.put("smsText", sms);

        try (HttpResponse response = HttpUtil.createPost(properties.getApi()).form(formMap).execute()) {
            if (!response.isOk()) {
                throw new SmsException("访问短信发送接口失败");
            } else {
                int ret = Integer.parseInt(response.charset("utf-8").body());
                log.info("短信调用结果:{}", ret);
                if (ret <= 0) {
                    String msg = exceptionMessage.getOrDefault(ret, "发送短信失败！");
                    return SmsResult.builder().isSuccess(false).message(msg).response(Integer.toString(ret)).build();
                } else {
                    return SmsResult.builder().isSuccess(true).message("发送成功").response(Integer.toString(ret)).build();
                }
            }
        }
    }
}
