package com.zcxk.controller;


import com.zcxk.entity.User;
import com.zcxk.entity.ValidateCode;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.UserService;
import com.zcxk.util.ByteArrayUtils;
import com.zcxk.util.VerifyCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zcxk.util.RedisUtil;

import java.time.LocalDate;

@Controller
@Api(tags = "短信")
@RequestMapping("sms")
public class SmsController {


    @Autowired
    private RedisUtil redisUtil;
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private UserService userService;
    @Value("${maxSendCodeNum}")
    private Integer maxSendCodeNum;
    @Value("${getSendCodeMax}")
    private Integer getSendCodeMax;

    @PostMapping("/send")
    @ResponseBody
    @ApiOperation(value = "发送短信")
    public AjaxMessage getCode(
            @ApiParam(value = "手机号码", required = true) @RequestParam(required = true) String phone
    ) {
        if (StringUtils.equals(phone, "18800000000") || StringUtils.equals(phone, "18800000001")) {
            return new AjaxMessage(ResultStatus.OK);
        }

        //检验该手机号码是否注册
        String key = "smsValidTime:" + phone;

        int user = getUser(phone, key);
        if(user==1){
            return  new AjaxMessage(ResultStatus.PHONE_NUMBER_NOT_FOUND_ERROR);

        }else if(user==2){
            return  new AjaxMessage(ResultStatus.UNABLE_SEND_ERROR);
        }
        verifyCode(phone,key);


        return countVerify(phone);
    }
    @PostMapping("/v2/send")
    @ResponseBody
    @ApiOperation(value = "发送短信")
    public AjaxMessage getCode(
            @ApiParam(value = "手机号码", required = true) @RequestParam(required = true) String mobile,
            @ApiParam(value = "验证码", required = true) @RequestParam(required = true) String code,
            @ApiParam(value = "随机数 uuid", required = true) @RequestParam String random
    ) {

        String validKey = "smsValidTime:" + mobile;
        int user = getUser(mobile, validKey);
        if(user==1){
             return  new AjaxMessage(ResultStatus.PHONE_NUMBER_NOT_FOUND_ERROR);

        }else if(user==2){
            return  new AjaxMessage(ResultStatus.UNABLE_SEND_ERROR);
        }


        String key = "validateCode:" + random;
        byte[] redisValidateCodeByte = redisUtil.get(key.getBytes());
        if (redisValidateCodeByte == null) {
            return  new AjaxMessage(ResultStatus.VALIDATE_CODE_EXPIRED_ERROR);

        } else {
            ValidateCode validateCode = (ValidateCode) ByteArrayUtils.bytesToObject(redisValidateCodeByte).get();
            if (validateCode.isExpried() || !StringUtils.equals(validateCode.getCode(), code)) {
                return  new AjaxMessage(ResultStatus.VALIDATE_CODE_ERROR);
            }
        }
        verifyCode(mobile,validKey);
        //清除验证码
        redisUtil.del(key.getBytes());
        return new AjaxMessage(ResultStatus.OK);
    }
  /*  @PostMapping("test")
    @ResponseBody
    @ApiOperation(value = "发送短信")
    public void test(String phone){
        countVerify(phone);
    }*/
    private AjaxMessage countVerify(String phone){
        LocalDate now = LocalDate.now();
        AjaxMessage ajaxMessage=new AjaxMessage(ResultStatus.OK);
        String key = "countVerify:" + phone+":"+now.toString();
        String countVerify = redisUtil.get(key);

        if(countVerify!=null){
            Integer count = Integer.parseInt(countVerify);
            if(count==getSendCodeMax){
                ajaxMessage=new AjaxMessage(ResultStatus.SMS_CODE_COUNT);
            }else if(count==maxSendCodeNum){
                ajaxMessage=new AjaxMessage(ResultStatus.SMS_CODE_LIMIT);
            }
        }else{
            redisUtil.set(key,"0");
        }
        redisUtil.incr(key);
        redisUtil.setExpire(key,60*60*24);

        return ajaxMessage;
    }
    private  void verifyCode(String mobile,String validKey){

        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);
        //保存redis
        String smsKey = "smsCode:" + mobile;
        redisUtil.setExpire(smsKey.getBytes(), ByteArrayUtils.objectToBytes(verifyCode).get(), 900);//15分钟过期
        VerifyCodeUtil.sendVerificationCodeSms(mobile, verifyCode);
        redisUtil.setExpire(validKey.getBytes(), "".getBytes(), 60);//60秒
    }
    private int getUser(String phone,String key){
        if (StringUtils.equals(phone, "18800000000") || StringUtils.equals(phone, "18800000001")) {
            return 0;
        }

        //检验该手机号码是否注册
        User userQuery=new User();
        userQuery.setPhone(phone);
        User user =  userService.findUser(userQuery);
        if (user == null) {
            return 1;

        }


        byte[] redisValidateCodeByte = redisUtil.get(key.getBytes());
        if (redisValidateCodeByte != null) {
            return 2;
        }
        return 0;
    }


}
