package com.ym.mec.biz.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.entity.SysConfig;
import com.ym.mec.biz.dal.entity.SysMessage;
import com.ym.mec.biz.dal.enums.MessageSendMode;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.service.SmsCodeService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;

@Service
public class SmsCodeServiceImpl implements SmsCodeService {

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

	@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();
		}
		SysConfig sysConfig = sysConfigService.findByParamName(SysConfigService.SMS_MAX_TIMES);
		int times = 3;
		if (sysConfig != null) {
			times = Integer.parseInt(sysConfig.getParanValue());
		}
		// 十分钟内只能发3条
		List<SysMessage> list = sysMessageService.queryUserInRecentMinList(mobile, 10, MessageSendMode.SMS);
		if (list != null && list.size() >= times) {
			throw new BizException("对不起，您发送太频繁请稍后重试！");
		}
		sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_LOGIN, mobile);
		return true;
	}

}
