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

import cn.wisenergy.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "发送手机验证码 codeType 0注册/登录验证   1修改密码 2订单通知信息")
@Slf4j
@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 = "验证码类型用途 0注册/登录验证   1修改密码 2订单通知信息", dataType = "Integer")})
    @RequestMapping("/verifyCode")
    @ResponseBody
    public Result verifyCode(@RequestParam String phone, @RequestParam Integer codeType)  {
        Map map=new HashMap();
        //判断phone和codeType是否符合输入类型
        if(!phone.matches(Constants.RegConstant.PHONE_REGSTR)){

            return ResultUtils.returnFail ("手机号码格式不正确","1009") ;

        }
        if(codeType!=Constants.Sms.CodeType.LOGIN_OR_REGISTER && codeType!=Constants.Sms.CodeType.PASS_UPDATE && codeType!=Constants.Sms.CodeType.ORDER_NOTICE){

            return ResultUtils.returnFail ("输入codeType不正确！","1008") ;


        }
        String key= StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.SMS_PRIFIX,phone,codeType+"");

        //生成随机数
        String code= MathUtils.random();
        //保存至Redis   MINUTE_INT
        redisUtils.set(key,code,Constants.Duration.HALF_HOUR_INT);

        boolean flag=smsUtils.sendMessage(phone,Constants.Sms.TemplateCode.LOGIN_SF_REGISTER,code);
        return  (flag? ResultUtils.returnSuccess():ResultUtils.returnFail());
    }
}