package com.jeequan.jeepay.mch.ctrl.anon;

import com.jeequan.jeepay.bizcommons.manage.sms.SmsManager;
import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.service.impl.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/*
* 短信验证
*
* @author xiaoyu
*
* @date 2021/6/8 17:09
*/
@RestController
@RequestMapping("/api/anon/sms")
public class SmsCodeController extends CommonCtrl {

	@Autowired private SysUserService sysUserService;
	@Autowired private SysConfigService sysConfigService;
	@Autowired private SmsManager smsManager;

	/** 发送短信验证码  **/
	@RequestMapping(value = "/code", method = RequestMethod.POST)
	public ApiRes code() throws BizException {
		// 验证参数 手机号, 已做base64处理
		String phone = getValStringRequired("phone");
		String smsType = getValStringRequired("smsType");
		String vercodeToken = getValStringRequired("vercodeToken");
		String vercode = getValStringRequired("vercode");

		String redisVercode = RedisUtil.getString(CS.getCacheKeyImgCode(vercodeToken));
		if (!vercode.equalsIgnoreCase(redisVercode)) {
			throw new BizException("验证码错误");
		}

		// 校验用户
		checkUser(phone, smsType);

		smsManager.sendSmsVercode(phone, smsType);
		return ApiRes.ok();
	}

	/**
	 * @author: xiaoyu
	 * @date: 2022/1/14 9:01
	 * @describe: 校验用户是否存在
	 */
	private void checkUser(String phone, String smsType) {
		SysUserEntity dbUser = sysUserService.getOne(SysUserEntity.gw().eq(SysUserEntity::getTelphone, phone).eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.MCH));
		if (CS.SMS_TYPE_API_ENUM.TYPE_REGISTER.equals(smsType)) {
			if (dbUser != null) {
				throw new BizException("当前用户已存在");
			}
		} else {
			if (dbUser == null) {
				throw new BizException("用户不存在");
			}
		}

	}
}
