package com.jeequan.jeepay.core.sms;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.smsconfig.JuhedxSmsConfig;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletException;
import java.util.Map;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JuhedxSmsProcessKit {

    public static boolean callInterface(JuhedxSmsConfig smsConfig, String templateId, Map<String, Object> param){
        try {
            if (smsConfig == null || StringUtils.isEmpty(templateId)) {
                return false;
            }

            String response = HttpUtil.post(JuhedxSmsConfig.getSmsUrl(JuhedxSmsConfig.SMS_SEND), param);

            if(response == null){
                throw new ServletException("短信接口异常！");
            }

            JSONObject respParam = JSON.parseObject(response);
            if (JuhedxSmsConfig.SUCCESS_CODE != respParam.getIntValue("error_code")) {
                throw new ServletException(respParam.getString("reason"));
            }

        } catch (Exception e) {

            log.info("短信异常：", e);
            throw new BizException("短信发送失败");
        }

        return true;
    }
}
