package com.keao.edu.auth.service.impl;


import com.keao.edu.auth.api.client.SysUserFeignService;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.auth.service.SmsCodeService;
import com.keao.edu.auth.service.SysMessageService;
import com.keao.edu.common.entity.SysMessage;
import com.keao.edu.common.enums.MessageSendMode;
import com.keao.edu.common.enums.MessageTypeEnum;
import com.keao.edu.common.exception.BizException;
import com.keao.edu.thirdparty.message.MessageSenderPluginContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SmsCodeServiceImpl implements SmsCodeService {

	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private SysUserFeignService sysUserFeignService;

	@Override
	public boolean verifyValidCode(String mobile, String authCode) {
		String verifyCode = sysMessageService.getSendedVerificationCode(MessageTypeEnum.SMS_VERIFY_CODE_LOGIN, mobile);
		if (StringUtils.isNoneEmpty(verifyCode) && StringUtils.equalsIgnoreCase(verifyCode, authCode)) {
			return true;
		}
		return false;
	}

	@Override
	public boolean sendValidCode(String mobile) {
		SysUser sysUser = sysUserFeignService.queryUserByMobile(mobile);
		Integer userId = null;
		if (sysUser != null) {
			userId = sysUser.getId();
		}
		int times = 3;
		// 十分钟内只能发3条
		List<SysMessage> list = sysMessageService.queryUserInRecentMinList(mobile, 10, MessageSendMode.SMS);
		if (list != null && list.size() >= times) {
			throw new BizException("对不起，您发送太频繁请稍后重试！");
		}
		sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.YIMEI, userId, MessageTypeEnum.SMS_VERIFY_CODE_LOGIN, mobile);
		return true;
	}

}
