package com.wecloud.im.externalaccess.controller;

import io.geekidea.springbootplus.framework.common.api.ApiCode;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.controller.BaseController;
import io.geekidea.springbootplus.framework.common.enums.BaseEnum;
import io.geekidea.springbootplus.framework.common.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wecloud.im.constant.RedisKeyPrefixConstant;
import com.wecloud.im.externalaccess.entity.User;
import com.wecloud.im.externalaccess.param.SendVerifyCodeParam;
import com.wecloud.im.externalaccess.service.UserService;
import com.wecloud.im.sdk.enums.VerifySceneEnum;
import com.wecloud.im.ws.utils.RedisUtils;

/**
 * @Author wenzhida
 * @Date 2022/2/21 17:05
 * @Description 验证码相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/verify")
@Api(value = "验证码相关API", tags = {"验证码"})
public class VerifyCodeController extends BaseController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    /**
     * 发送验证码接口
     */
    @PostMapping("/sendVerifyCode")
    @ApiOperation(value = "发送验证码接口")
    public ApiResult<Boolean> sendVerifyCode(@RequestBody @Validated SendVerifyCodeParam param) {
        if (param == null) {
            return ApiResult.fail(ApiCode.PARAMETER_EXCEPTION, null);
        }
        if (BaseEnum.valueOf(VerifySceneEnum.class, param.getVerifyScene()) == null) {
            return ApiResult.fail(ApiCode.PARAMETER_EXCEPTION, null);
        }
        if (VerifySceneEnum.RESET_PWD.getCode().equals(param.getVerifyScene())) {
            // 重置密码、找回密码校验手机号码已注册
            User user = userService.getOne(new QueryWrapper<User>().lambda()
                    .eq(User::getPhone, param.getPhone()));
            if (user == null) {
                throw new BusinessException("账号不存在");
            }
        }
//        String verifyCode = RandomUtil.generateVerifyCode();
        String verifyCode = "666666";
        String key = new StringBuilder(RedisKeyPrefixConstant.VERIFY_CODE_PREFIX).append(param.getVerifyScene()).append(param.getPhone()).toString();
        redisUtils.addKey(key, verifyCode, Duration.ofSeconds(3 * 60));
        // todo 接入短信推送
        return ApiResult.ok();
    }


}

