package com.leromro.core.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.core.redis.RedisCache;
import com.leromro.common.enums.ConstantsKey;
import com.leromro.core.utils.SendSmsUtil;
import com.leromro.framework.config.ConstantsConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Api(tags = "短信")
@RequestMapping({"/sms"})
public class SmsController {

    @Autowired
    private RedisCache redisCache;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @GetMapping({"/sendCode/{phone}"})
    @ApiOperation(value = "发送验证码", notes = "发送验证码")
    public AjaxResult sendCode(@PathVariable(name = "phone")String phone) {
        //校验是否才发过验证码
        if (ObjectUtil.isNotNull(redisCache.getCacheObject(ConstantsKey.REDIS_PHONE_CODE.getKey() + "_" + phone + "_interval"))) {
            return AjaxResult.error(-1, "验证码已发送，请稍后再试");
        }
        String code = (Math.random() + "").substring(2, 6);
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("code", code);
        String send = SendSmsUtil.send(phone, jsonObject.toString(), ConstantsConfig.SMS_TEMPLATE_TYPE_PHONE_CODE.getValue());
        if (StrUtil.isBlank(send)) {
            return AjaxResult.error(-1, "验证码发送失败");
        }
        //设置值
        redisCache.setCacheObject(ConstantsKey.REDIS_PHONE_CODE.getKey() + "_" + phone, code, Integer.parseInt(ConstantsConfig.REDIS_SHORT_TIMELONG.getValue()), TimeUnit.SECONDS);
        //设置时间间隔
        redisCache.setCacheObject(ConstantsKey.REDIS_PHONE_CODE.getKey() + "_" + phone + "_interval", System.currentTimeMillis(), Integer.parseInt(ConstantsConfig.REDIS_ONE_MIN_TIMELONG.getValue()), TimeUnit.SECONDS);
        log.info("验证码发送成功，手机号：{}，验证码：{}", phone, code);
        return AjaxResult.success("验证码发送成功");
    }

    /**
     * 校验验证码
     */
    @GetMapping({"/checkSmsCode/{phone}/{code}"})
    public AjaxResult checkSmsCode(@PathVariable(name = "phone")String phone,
                                   @PathVariable(name = "code")String code) {
        String redisCode = this.redisCache.getCacheObject(ConstantsKey.REDIS_PHONE_CODE.getKey() + "_" + phone);
        if (StrUtil.isBlank(redisCode)) {
            return AjaxResult.error(-1, "验证码已过期");
        }
        if (!redisCode.equals(code)) {
            return AjaxResult.error(-1, "验证码错误");
        }
        return AjaxResult.success("验证码校验成功");
    }
}
