package com.winsun.controller;

import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.smsUtils.SendSmsAndMail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiangli
 * @Date 2020/4/21
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/codesManager")
public class codeManagerController {

    @Autowired
    @Qualifier("redisStringTemplate")
    private RedisTemplate redisTemplate;

    @ResponseBody
    @RequestMapping(value = "sendCodes", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkStudent(String phone) {
        // 生成6位随机数
        String s = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        log.info("验证码:" + s);
        //MessageUtil.sent(packageUpgrade.getAccNbr(),"4","您获取的验证码为："+s+",半小时内有效。");
        redisTemplate.opsForValue().set(phone, s, 240, TimeUnit.MINUTES);
        String codes = SendSmsAndMail.sendSms(phone,s+"","7");
        return ResponseData.success(null, "已发送验证码到手机,验证码：" + s);
    }
    @ResponseBody
    @RequestMapping(value = "checkCodes", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> checkCodes(String phone, String codes) {
        if(!StringUtils.isNotEmpty(phone)){
            return ResponseData.error("手机号不正确！");
        }
        if(!StringUtils.isNotEmpty(codes)){
            return ResponseData.error("验证码不能为空！");
        }
        String ver = null;
        try {
            ver = redisTemplate.opsForValue().get(phone).toString();
        } catch (NullPointerException n) {
            return ResponseData.error("验证码已失效，请发送验证码！");
        }
        if(ver.equals(codes)){
            return ResponseData.success();
        }
        return ResponseData.error( "验证码错误" );
    }

}
