package com.qmth.paper.library.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.paper.library.business.entity.PaperLibraryOther;
import com.qmth.paper.library.business.mapper.PaperLibraryOtherMapper;
import com.qmth.paper.library.business.service.PaperLibraryOtherService;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.lock.LockService;
import com.qmth.paper.library.common.lock.LockType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 其它文件库 服务实现类
 * </p>
 *
 * @author xf
 * @since 2024-03-12
 */
@Service
public class PaperLibraryOtherServiceImpl extends ServiceImpl<PaperLibraryOtherMapper, PaperLibraryOther> implements PaperLibraryOtherService {

    @Resource
    private LockService lockService;

    @Override
    public void removeByPaperScanTaskId(Long paperScanTaskId) {
        QueryWrapper<PaperLibraryOther> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PaperLibraryOther::getPaperScanTaskId, paperScanTaskId);
        this.remove(queryWrapper);
    }

    @Override
    public int getMaxSequence(Long paperScanTaskId, Long fileTypeId) {
        try {
            lockService.waitlock(LockType.GET_OTHER_SEQUENCE, paperScanTaskId, fileTypeId);
            QueryWrapper<PaperLibraryOther> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PaperLibraryOther::getPaperScanTaskId, paperScanTaskId)
                    .eq(PaperLibraryOther::getFileTypeId, fileTypeId)
                    .orderByDesc(PaperLibraryOther::getSequence)
                    .last(" limit 1");
            PaperLibraryOther paperLibraryOther = this.getOne(queryWrapper);
            if (paperLibraryOther == null || paperLibraryOther.getSequence() == null) {
                return 1;
            } else {
                return paperLibraryOther.getSequence().intValue() + 1;
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception("获取批次号失败：" + e.getMessage());
        } finally {
            lockService.unlock(LockType.GET_OTHER_SEQUENCE, paperScanTaskId, fileTypeId);
        }
    }
}
