package com.szxgl.nft.controller;

import com.aliyuncs.exceptions.ClientException;
import com.szxgl.nft.entity.RedisKeyName;
import com.szxgl.nft.utils.AliyunSmsUtils;
import com.szxgl.nft.utils.CookieUtil;
import com.szxgl.nft.utils.R;
import com.szxgl.nft.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/code")
@Slf4j
public class VerificationCodeController {

    @Autowired
    private RedisUtil redisUtil;

    private static final String openidCode = RedisKeyName.getOpenidCode();

    /**
     * 获取验证码
     * @param seed 手机号
     * @return
     */
    @PostMapping("/getCode")
    public R getCode(String seed, HttpServletRequest request){
        String openid = CookieUtil.getCookie(request.getCookies());
        if(StringUtils.isBlank(openid)){
            log.error("openid为空："+openid);
            return R.error("openid为空");
        }
        //判断手机号是否为空
        if(StringUtils.isBlank(seed)){
            log.error("手机号为空："+seed);
            return R.error("手机号为空");
        }
        //获取验证码
        String code = Integer.toString(AliyunSmsUtils.getNewcode());
        log.info("发送的验证码为："+code);
//        try {
//            //使用阿里云发送短信
//            AliyunSmsUtils.sendSms(seed,code);
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
        //把验证码存入redis中
        redisUtil.set(openidCode + openid, code, 300);
        return R.ok(code);
    }


}
