package com.ruoyi.cai.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.LowHeightRisk;
import com.ruoyi.cai.domain.UserErrorLog;
import com.ruoyi.cai.dto.admin.vo.LowHeightRiskAdminVo;
import com.ruoyi.cai.enums.user.UserErrorLogType;
import com.ruoyi.cai.mapper.LowHeightRiskMapper;
import com.ruoyi.cai.service.LowHeightRiskService;
import com.ruoyi.common.core.domain.PageQuery;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 高风险用户记录Service业务层处理
 *
 * @author 77
 * @date 2023-12-22
 */
@Service
public class LowHeightRiskServiceImpl extends ServiceImpl<LowHeightRiskMapper, LowHeightRisk> implements LowHeightRiskService {

    @Override
    public Page<LowHeightRiskAdminVo> pageAdmin(PageQuery pageQuery, LowHeightRiskAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(),bo);
    }

    @Override
    public void incsNum(UserErrorLog log){
        if(log == null || log.getUserId() == null){
            return;
        }
        LowHeightRisk one = this.getOne(Wrappers.lambdaQuery(LowHeightRisk.class)
                .eq(LowHeightRisk::getUserId, log.getUserId()));
        if(one == null){
            ReentrantLock lock = new ReentrantLock();
            try {
                lock.lock();
                one = this.getOne(Wrappers.lambdaQuery(LowHeightRisk.class)
                        .eq(LowHeightRisk::getUserId, log.getUserId()));
                if(one == null){
                    one = new LowHeightRisk();
                    one.setUserId(log.getUserId());
                    this.save(one);
                }
            }finally {
                lock.unlock();
            }
        }
        if(UserErrorLogType.SCREEN_SHOT.getCode().equals(log.getType())){
            baseMapper.incsScreenShot(one.getId());
        }else if(UserErrorLogType.SCREEN_RECORDING.getCode().equals(log.getType())){
            baseMapper.incsScreenRecording(one.getId());
        }
    }
}
