package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yeejoin.equipmanage.common.entity.SourceFile;
import com.yeejoin.equipmanage.common.vo.SourceFileVo;
import com.yeejoin.equipmanage.mapper.SourceFileMapper;
import com.yeejoin.equipmanage.service.ISourceFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;

/**
 * @author DELL
 */
@Slf4j
@Service
public class SourceFileServiceImpl extends ServiceImpl<SourceFileMapper, SourceFile> implements ISourceFileService {

    @Autowired
    private Sequence sequence;

    @Autowired
    private SourceFileMapper sourceFileMapper;

    /**
     * @param sourceId 所属者ID
     * @Description 根据所属者ID查询所属文件
     * @Return Map<String, List < SourceFile>>
     * @Date 2020/12/18 14:12
     */
    @Override
    public List<SourceFile> findBySourceId(Long sourceId) {
        List<SourceFile> sourceFiles = this.list(new QueryWrapper<SourceFile>()
                .lambda().eq(SourceFile::getSourceId, sourceId));
        Optional.ofNullable(sourceFiles).orElseThrow(() -> new BadRequest("所属文件为空"));
        return sourceFiles;
    }

    /**
     * @param sourceFiles
     * @Description 批量保存文件
     * @Return List<SourceFile>
     * @Date 2020/12/18 14:27
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SourceFile> saveSourceFile(Long sourceId, List<SourceFile> sourceFiles) {
        this.baseMapper.delete(new QueryWrapper<SourceFile>()
                .lambda()
                .eq(SourceFile::getSourceId, sourceId));
        sourceFiles.forEach(s -> {
            s.setSourceId(sourceId);
            s.setId(sequence.nextId());
            s.setCreateDate(new Date());
        });
        if (CollectionUtils.isEmpty(sourceFiles)) {
            return new ArrayList<>();
        }
        boolean flag = this.saveOrUpdateBatch(sourceFiles);
        return flag ? sourceFiles : Collections.EMPTY_LIST;
    }

    @Override
    public List<SourceFileVo> findImgByFileCategory(Long id, String fileCategory) {
        List<SourceFileVo> list = sourceFileMapper.findImgByFileCategory(id, fileCategory);
        if (!CollectionUtils.isEmpty(list)) {
            return list;
        }
        return Lists.newArrayList();
    }
}
