package com.wecloud.im.externalaccess.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wecloud.im.externalaccess.sms.constant.SmsConstants;
import com.wecloud.im.externalaccess.sms.sender.HwSmsSender;
import com.wecloud.im.core.util.RandomUtil;
import com.wecloud.im.core.common.api.ApiCode;
import com.wecloud.im.core.common.api.ApiResult;
import com.wecloud.im.core.common.controller.BaseController;
import com.wecloud.im.core.common.enums.BaseEnum;
import com.wecloud.im.core.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.server.utils.RedisUtils;

import javax.annotation.Resource;

/**
 * @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;

    @Resource
    private HwSmsSender hwSmsSender;

    /**
     * 发送验证码接口
     */
    @PostMapping("/sendVerifyCode")
    @ApiOperation(value = "发送验证码接口")
    public ApiResult<Boolean> sendVerifyCode(@RequestBody @Validated SendVerifyCodeParam param) {
        log.info("发送验证码入参 {}", JSON.toJSONString(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 key = new StringBuilder(RedisKeyPrefixConstant.VERIFY_CODE_PREFIX).append(param.getVerifyScene()).append(param.getPhone()).toString();
        redisUtils.addKey(key, verifyCode, Duration.ofSeconds(5 * 60));
        // 短信发送
        try {
            String[] templateParas = new String[]{verifyCode};
            hwSmsSender.sendMsg(param.getPhone(), SmsConstants.TEMPLATE_ID, JSONObject.toJSONString(templateParas));
        } catch (Exception e) {
            log.info("发送短信异常 ", e);
        }
        return ApiResult.ok();
    }


}

