package com.xjrsoft.common.sms;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.config.CtccSmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 电信三网短信
 */
@Component
public class SmsCtcc {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 发送短信
     *
     * @param mobile  手机号
     * @param content 短信内容
     * @return {"message":"提交成功","taskId":7103189661382795265,"status":1} || {"message":"提交数据错误","status":2}
     */
    public JSONObject send(String mobile, String content) {
        CtccSmsConfig config = SpringUtil.getBean(CtccSmsConfig.class);

        Map<String, Object> params = new HashMap<>();
        params.put("appKey", config.getAppKey());
        params.put("timestamp", System.currentTimeMillis());
        params.put("mobile", mobile);
        params.put("content", config.getSignature() + content);

        String str = params.get("appKey").toString()
                + params.get("timestamp").toString()
                + params.get("mobile").toString()
                + params.get("content").toString()
                + config.getAppSecret();

        params.put("sign", SaSecureUtil.md5(str));

        String result = HttpUtil.post("http://182.92.7.106:7892/api/sms/air/send", params);

        return JSONUtil.parseObj(result);
    }

    /**
     * 发送验证码
     *
     * @param mobile 手机号
     * @param code   验证码
     * @return {"message":"提交成功","taskId":7103189661382795265,"status":1} || {"message":"提交数据错误","status":2}
     */
    public JSONObject sendCaptcha(String mobile, String code, boolean isSend) {
        String key = GlobalConstant.CAPTCHA + mobile;
        if (redisUtil.containsKey(key)) {
            throw new MyException("验证码发送频繁，请稍后再试！");
        }
        if (isSend) {
            String content = String.format("验证码为%s，有效时间为%d分钟，请勿将验证码泄露给其他人。", code, 2);
            JSONObject result = send(mobile, content);
            if (result.getInt("status") == 1) {
                redisUtil.set(key, code, 120L);
            }else{
                throw new MyException("验证码发送失败！");
            }
            return result;
        }else{
            redisUtil.set(key, code, 120L);
        }
        return null;
    }

    /**
     * 用户验证码验证
     *
     * @param mobile 手机号
     * @param code   验证码
     * @return
     */
    public boolean captchaVerify(String mobile, String code) {
        String key = GlobalConstant.CAPTCHA + mobile;
        String rCode = redisUtil.get(key, 0);
        if (rCode != null && rCode.equals(code)) {
            return true;
        }
        return false;
    }
}
