package cn.wisenergy.web.admin.controller.app;

import cn.wisenergy.common.utils.Constants;
import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.SmsUtils;
import cn.wisenergy.common.utils.StringUtil;
import cn.wisenergy.web.sms.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/sms")
@RestController
public class SmsController {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private RedisUtils redisUtils;

    /**
     *
     * @param phone
     * @param codeType 0注册/登录验证   1修改密码 2订单通知信息
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "发送验证码", notes = "发送验证码", httpMethod = "POST", produces = "application/json; charset=UTF-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "用户手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "codeType", value = "验证码", dataType = "Integer")})
    @RequestMapping("/verifyCode")
    public Result verifyCode(String phone,Integer codeType) throws Exception {
        //判断phone和codeType是否符合输入类型
        if(!phone.matches(Constants.RegConstant.PHONE_REGSTR)){
            throw new BaseException(ResultEnum.PHONE_ERROR);
        }
        if(!codeType.equals(Constants.Sms.CodeType.LOGIN_OR_REGISTER) && !codeType.equals(Constants.Sms.CodeType.PASS_UPDATE) && !codeType.equals(Constants.Sms.CodeType.ORDER_NOTICE)){
            throw new BaseException(ResultEnum.CODETYPE_ERROR);
        }
        String key= StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.SMS_PRIFIX,phone,codeType+"");
        //判断是否超过60S
        String Codekey=redisUtils.getValue(key);
        if(!StringUtils.isBlank(Codekey)){
            throw new BaseException(ResultEnum.CODESEND_ERROR);
        }
        //生成随机数
        String code= MathUtils.random();
        //保存至Redis
        redisUtils.set(Codekey,code,Constants.Duration.MINUTE_INT);
        boolean flag=smsUtils.sendMessage(phone,Constants.Sms.TemplateCode.LOGIN_DL_REGISTER,code);
        return flag? ResultUtils.returnSuccess():ResultUtils.returnFail();
    }
}