package com.cyksj.service.phone.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.PhoneCodeMapper;
import com.cyksj.model.entity.PhoneCode;
import com.cyksj.service.phone.PhoneCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/*
 *项目名: netflix
 *文件名: PhoneCodeServiceImpl
 *创建者: JavaZou
 *创建时间:2022/12/29 14:03
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PhoneCodeServiceImpl implements PhoneCodeService {
	private final PhoneCodeMapper phoneCodeMapper;

	@Override
	public void checkPhone(String phone, String code) {
		if (StrUtil.isEmpty(phone)) {
			throw BusinessRuntimeException.getInstance("请输入正确的手机号码");
		}
		DateTime now = DateTime.now();
		PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, phone).last("limit 1"));
		if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) {
			throw BusinessRuntimeException.getInstance("请重新获取手机验证码");
		}
		//3分钟失效
		Date updateTime = phoneCode.getUpdateTime();
		DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3);
		if (now.isAfter(afterFiveMinutes)) {
			throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取");
		}
		if (!StrUtil.equals(code, phoneCode.getCode())) {
			throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入");
		}
	}
}
