package com.jeequan.jeepay.core.sms;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.smsconfig.AbstractSmsConfig;
import com.jeequan.jeepay.core.model.smsconfig.JeepaydxSmsConfig;
import com.jeequan.jeepay.core.model.smsconfig.SmsBizDiyContentModel;
import com.jeequan.jeepay.core.model.smsconfig.SmsBizVercodeModel;
import com.jeequan.jeepay.core.utils.JeepayKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 计全短信配置
 **/
@Slf4j
@Service
public class JeepaydxSmsHandler implements ISmsHandler {

    @Override
    public void sendVercode(SmsBizVercodeModel smsBizVercodeModel, AbstractSmsConfig smsConfig) {
        JeepaydxSmsConfig jeepaydxSmsConfig = (JeepaydxSmsConfig)smsConfig;
        // 生成短信验证码
        String verifyCode = smsBizVercodeModel.getSmsVercode();
        // 短信内容
        String templateVal = "";
        if (CS.SMS_TYPE_API_ENUM.TYPE_AUTH.equals(smsBizVercodeModel.getSmsBizType())) {
            templateVal = "您正在进行登录， 验证码为：" + verifyCode + "，该验证码 " + smsBizVercodeModel.getExpiredMin() + " 分钟内有效，请勿泄漏于他人。";
        }else if (CS.SMS_TYPE_API_ENUM.TYPE_REGISTER.equals(smsBizVercodeModel.getSmsBizType())) {
            templateVal = "您正在进行注册， 验证码为：" + verifyCode + "，该验证码 " + smsBizVercodeModel.getExpiredMin() + " 分钟内有效，请勿泄漏于他人。";
        }else if (CS.SMS_TYPE_API_ENUM.TYPE_RETRIEVE.equals(smsBizVercodeModel.getSmsBizType())) {
            templateVal = "您正在找回密码操作， 验证码为：" + verifyCode + "，该验证码 " + smsBizVercodeModel.getExpiredMin() + " 分钟内有效，请勿泄漏于他人。";
        }else if (CS.SMS_TYPE_API_ENUM.TYPE_MBR_TEL_BIND.equals(smsBizVercodeModel.getSmsBizType())) {
            templateVal = "您正在进行会员绑定操作， 验证码为：" + verifyCode + "，该验证码 " + smsBizVercodeModel.getExpiredMin() + " 分钟内有效，请勿泄漏于他人。";
        }
        this.callInterface(jeepaydxSmsConfig, smsBizVercodeModel.getPhoneNo(), templateVal);

    }

    @Override
    public void sendDiyContent(SmsBizDiyContentModel smsBizDiyContentModel, AbstractSmsConfig smsConfig) {
        JeepaydxSmsConfig jeepaydxSmsConfig = (JeepaydxSmsConfig)smsConfig;
        String templateVal = "";
        if (CS.SMS_TYPE_API_ENUM.TYPE_ACCOUNT_OPEN.equals(smsBizDiyContentModel.getSmsBizType())) {
            templateVal = "账号：" + smsBizDiyContentModel.getString(SmsBizDiyContentModel.FIELD_LOGIN_NAME) +
                    "，密码：" + smsBizDiyContentModel.getString(SmsBizDiyContentModel.FIELD_USER_PWD) + "，您的账户已开通成功，请勿泄漏于他人。";
        }
        this.callInterface(jeepaydxSmsConfig, smsBizDiyContentModel.getPhoneNo(), templateVal);
    }

    public boolean callInterface(JeepaydxSmsConfig smsConfig, String phone, String templateVal){
        String logPrefix = "[计全短信发送]";
        try {
            JSONObject reqJson = new JSONObject();
            // 用户名
            reqJson.put("userName", smsConfig.getUserName());
            // 手机号
            reqJson.put("mobile", phone);
            // 发送内容（必填），不超过1000字
            reqJson.put("content", templateVal);
            // 签名 MD5(userName+password+mobile+content) password为明文密码
            String signStr = JeepayKit.md5(smsConfig.getUserName() + smsConfig.getAccountPwd() + phone + templateVal, CharsetUtil.UTF_8);
            reqJson.put("sign", signStr);

            // 发起请求
            String reqUrl = JeepaydxSmsConfig.getSmsUrl(JeepaydxSmsConfig.SMS_SEND);
            log.info("{}请求地址[post]：{}，请求参数：params={}", logPrefix, reqUrl, reqJson);
            HttpResponse response = HttpRequest.post(reqUrl)
                    .header("Content-type", "application/json")
                    .charset("UTF-8")
                    .body(reqJson.toJSONString())
                    .execute();
            log.info("{}响应结果response={}", logPrefix, response.body());
            // 判断提交状态
            JSONObject resJson = JSONObject.parseObject(response.body());
            if (resJson == null) {
                throw new BizException("短信发送失败");
            }
            String resultCode = resJson.getString("resultCode");
            // 1 是提交成功
            if ("1".equals(resultCode)) {
                return true;
            }else {
                throw new BizException("短信发送失败，失败原因:" + resJson.getString("resultMsg"));
            }
        } catch (Exception e) {
            log.info("{}短信异常：", logPrefix, e);
            throw new BizException("短信发送失败");
        }
    }


    @Override
    public String querySmsInfo(AbstractSmsConfig smsConfig, String bizQueryType) {
        JeepaydxSmsConfig jeepaydxSmsConfig = (JeepaydxSmsConfig)smsConfig;
        return this.queryBalance(jeepaydxSmsConfig);

    }

    /** 查询短信余额（条数） **/
    public String queryBalance(JeepaydxSmsConfig smsConfig){
        String logPrefix = "[计全短信余额查询]";
        try {
            JSONObject reqJson = new JSONObject();
            // 用户名
            reqJson.put("userName", smsConfig.getUserName());
            // token 每次请求时可以使用时间戳或者uuid值
            String uuid = UUID.randomUUID().toString();
            reqJson.put("token", uuid);
            // 签名 MD5(username+password+token)
            String signStr = JeepayKit.md5(smsConfig.getUserName() + smsConfig.getAccountPwd() + uuid, CharsetUtil.UTF_8);
            reqJson.put("sign", signStr);

            // 发起请求
            String reqUrl = JeepaydxSmsConfig.getSmsUrl(JeepaydxSmsConfig.SMS_BALANCE_QUERY);
            log.info("{}请求地址[post]：{}，请求参数：params={}", logPrefix, reqUrl, reqJson);
            HttpResponse response = HttpRequest.post(reqUrl)
                    .header("Content-type", "application/json")
                    .charset("UTF-8")
                    .body(reqJson.toJSONString())
                    .execute();
            log.info("{}响应结果response={}", logPrefix, response.body());
            // 判断提交状态
            JSONObject resJson = JSONObject.parseObject(response.body());
            if (resJson == null) {
                throw new BizException("短信余额查询失败");
            }
            String resultCode = resJson.getString("resultCode");
            // 1 是查询成功
            if ("1".equals(resultCode)) {
                return resJson.getString("balance");
            }else {
                log.info("{}查询失败，失败原因：{}", logPrefix, resJson.getString("resultMsg"));
                return null;
            }
        } catch (Exception e) {
            log.info("{}查询异常：", logPrefix, e);
            return null;
        }
    }

}
