package cn.pluss.platform.service;

import cn.pluss.platform.entitiy.ReqRecords;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.ReqRecordsMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author DJH
 */
@Service
public class ReqRecordsService extends ServiceImpl<ReqRecordsMapper, ReqRecords> {

    /**
     * 检查请求限制
     * @param reqRecords    请求相关参数, 手机号, 用户id, ip等
     * @param duringTime    请求限制间隔时间
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void checkLimit(ReqRecords reqRecords, long duringTime) {
        LambdaQueryWrapper<ReqRecords> qWrapper = Wrappers.lambdaQuery();

        boolean andFlag = StringUtils.isNotEmpty(reqRecords.getIp())
                || (reqRecords.getUserId() != null)
                || StringUtils.isNotEmpty(reqRecords.getPhone())
                || StringUtils.isNotEmpty(reqRecords.getLoginName());
        qWrapper.eq(ReqRecords::getUri, reqRecords.getUri())
                .and(andFlag, wrapper -> wrapper
                        .or(StringUtils.isNotEmpty(reqRecords.getIp()), wrapper2 -> wrapper2.eq(ReqRecords::getIp, reqRecords.getIp()))
                        .or(reqRecords.getUserId() != null, wrapper2 -> wrapper2.eq(ReqRecords::getUserId, reqRecords.getUserId()))
                        .or(StringUtils.isNotEmpty(reqRecords.getPhone()), wrapper2 -> wrapper2.eq(ReqRecords::getPhone, reqRecords.getPhone()))
                        .or(StringUtils.isNotEmpty(reqRecords.getLoginName()), wrapper2 -> wrapper2.eq(ReqRecords::getLoginName, reqRecords.getLoginName())))
                .orderByDesc(ReqRecords::getCreateTime)
                .last("limit 1");

        long nextLimitTime = System.currentTimeMillis() - duringTime;

        ReqRecords lastReqRecords = getBaseMapper().selectOne(qWrapper);
        if (lastReqRecords != null && lastReqRecords.getCreateTime().getTime() > nextLimitTime) {
            throw new MsgException("请求过于频繁，请稍后再试");
        }

        save(reqRecords);
    }
}
