package com.community.huiju.controller;

import com.community.commom.mode.ResponseBean;
import com.community.commom.utils.AccountValidatorUtil;
import com.community.huiju.common.base.BaseController;
import com.community.huiju.common.code.ICode;
import com.community.huiju.common.code.cache.AppkeyCache;
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.beans.factory.annotation.Qualifier;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author weiximei
 */
@RestController
@RequestMapping("/")
@RefreshScope
@Api(value = "获取验证码的API", description = "获取验证码的API")
@Slf4j
public class CodeController extends BaseController {

    @Autowired
    @Qualifier("phoneCodeImpl")
    private ICode iCode;

    @ApiOperation(value = "获取手机验证码", notes = "根据手机号发送验证码")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query",dataType = "String",name = "phone",value = "手机号")})
    @RequestMapping(value = "/code/sendCode",method = RequestMethod.POST)
    public ResponseBean sendCode(@RequestParam String phone, HttpSession session) {
        ResponseBean response = new ResponseBean();

        log.info("{} 手机号校验结果: {}",phone, AccountValidatorUtil.isPhone(phone));
        if (!AccountValidatorUtil.isPhone(phone)){
            response.addError("请输入正确的手机号!");
            return response;
        }

        int code = (int) ((Math.random()*9+1)*1000);
        boolean result = iCode.sendCode(phone,String.valueOf(code));
        //boolean result = true;
        if (result) {
            log.info("{} 验证码: {}",phone,code);
            // 设置缓存
            AppkeyCache.setCache(phone,String.valueOf(code));
            response.addSuccess("发送成功!");
        } else {
            response.addError("发送失败!");
        }
        return response;
    }

}
