package com.unis.detectionnum.server.message.service.impl;

import com.unis.detectionnum.server.message.common.CommonConstant;
import com.unis.detectionnum.server.message.service.SMSIdentifyCodeService;
import com.unis.detectionnum.server.message.service.SubmitDataService;
import com.unis.detectionnum.server.message.utils.CacheUtil;
import com.unis.detectionnum.server.message.utils.DateUtil;
import com.unis.detectionnum.server.message.utils.IdentifyCodeUtil;
import com.unis.detectionnum.server.message.entity.SmsDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 短信发送 服务实现类
 *
 * @author YangZR
 * @since 2020-03-10
 */
@Service
@Slf4j
@SuppressWarnings("all")
public class SMSIdentifyCodeServiceImpl implements SMSIdentifyCodeService {

	@Autowired
	private SubmitDataService submitDataService;

	/**
	 * 发送短信服务
	 *
	 * @author YangZR
	 * @date 2020-03-10
	 */
	@Override
	public boolean sendMessageAndContens(String mobile, String creater, String contents) throws Exception{
		SmsDataVO smsDataVO = new SmsDataVO();
		smsDataVO.setSdst(mobile);
		smsDataVO.setCreateBy(creater);
		smsDataVO.setCreateTime(DateUtil.now());
		smsDataVO.setSmsg(contents);

		boolean result = submitDataService.sendingSMS(smsDataVO);

		return result;
	}

	/**
	 * 发送短信服务
	 *
	 * @author YangZR
	 * @since 2020-03-10
	 */
	@Override
	public boolean sendMessage(String mobile, String creater) throws Exception {
		if (mobile.length() == 11) {
			String identifyCode = IdentifyCodeUtil.getRandom();
			//发送短信
			String contents = "您的验证码是：" + identifyCode + "，请在5分钟内输入";
			boolean flag = sendMessageAndContens(mobile, creater, contents);
			if(flag) {
				// 短信发送成功后，将验证码缓存，缓存5分钟
				CacheUtil.put(mobile, identifyCode, 300000);

				//缓存当前系统时间戳
				long timeMillis = System.currentTimeMillis();
				CacheUtil.put(CommonConstant.MOBILE_REDIS_KEY_PRE + mobile, timeMillis, 60000);
				return true;
			} else {
				throw new Exception("验证码发送失败");
			}
		} else {
			throw new Exception("手机号格式不正确");
		}
	}

	/**
	 * 判断验证码是否正确
	 *
	 * @author YangZR
	 * @date 2020-03-10
	 */
	@Override
	public boolean checkIsCorrectCode(String mobile, String identifyCode) {
		if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(identifyCode)) {
			return false;
		}
		Object codeObj = CacheUtil.get(mobile);
		if(null != codeObj) {
			String code = codeObj.toString();
			if(code.trim().equals(identifyCode.trim())) {
				CacheUtil.remove(mobile);
				return true;
			}
		}
		return false;
	}


}
