package org.dromara.drawing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.drawing.domain.DrawingFile;
import org.dromara.drawing.domain.query.DrawingFileQuery;
import org.dromara.drawing.domain.vo.DrawingFileVo;
import org.dromara.drawing.mapper.DrawingFileMapper;
import org.dromara.drawing.service.IDrawingFileService;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图纸文件 Service 业务层处理
 *
 * @Author: Trae
 */
@RequiredArgsConstructor
@Service
public class DrawingFileServiceImpl implements IDrawingFileService {

    private final DrawingFileMapper baseMapper;

    @Override
    public List<DrawingFileVo> queryList(DrawingFileQuery query) {
        LambdaQueryWrapper<DrawingFile> lqw = buildQueryWrapper(query);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public DrawingFileVo queryById(Integer id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Map<String, String> queryImagesByNums(List<String> nums) {
        if (CollUtil.isEmpty(nums)) {
            return new HashMap<>();
        }
        LambdaQueryWrapper<DrawingFile> lqw = Wrappers.lambdaQuery();
        lqw.in(DrawingFile::getNum, nums);
        lqw.eq(DrawingFile::getEname, ".JPG");
        lqw.select(DrawingFile::getNum, DrawingFile::getFileValue);
        List<DrawingFile> list = baseMapper.selectList(lqw);
        Map<String, String> result = new HashMap<>();
        for (DrawingFile df : list) {
            if (df.getFileValue() != null && df.getFileValue().length > 0) {
                result.put(df.getNum(), Base64.getEncoder().encodeToString(df.getFileValue()));
            }
        }
        return result;
    }

    private LambdaQueryWrapper<DrawingFile> buildQueryWrapper(DrawingFileQuery query) {
        LambdaQueryWrapper<DrawingFile> lqw = Wrappers.lambdaQuery();
        if (query != null) {
            lqw.like(StrUtil.isNotBlank(query.getNum()), DrawingFile::getNum, query.getNum());
            lqw.like(StrUtil.isNotBlank(query.getName()), DrawingFile::getName, query.getName());
            lqw.like(StrUtil.isNotBlank(query.getFileClass()), DrawingFile::getFileClass, query.getFileClass());
            lqw.eq(ObjectUtil.isNotEmpty(query.getFileType()), DrawingFile::getFileType, query.getFileType());
            lqw.eq(ObjectUtil.isNotEmpty(query.getDrawingClassId()), DrawingFile::getDrawingClassId, query.getDrawingClassId());
        }
        lqw.orderByAsc(DrawingFile::getNum);
        return lqw;
    }

}
