package com.yeejoin.amos.boot.module.common.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.dto.SourceFileDto;
import com.yeejoin.amos.boot.module.common.api.entity.SourceFile;
import com.yeejoin.amos.boot.module.common.api.mapper.SourceFileMapper;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 公共附件服务实现类
 *
 * @author system_generator
 * @date 2021-07-16
 */
@Service
public class SourceFileServiceImpl extends BaseService<SourceFileDto, SourceFile, SourceFileMapper> implements ISourceFileService {

    @Autowired
    private Sequence sequence;

    /**
     * 分页查询
     */
    public Page<SourceFileDto> queryForSourceFilePage(Page<SourceFileDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<SourceFileDto> queryForSourceFileList() {
        return this.queryForList("", false);
    }

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

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

    /**
     * 保存附件
     */
    @Override
    public void saveAttachments(Long sequenceNbr, Map<String, List<AttachmentDto>> attachmentMap) {
        if (!ValidationUtil.isEmpty(attachmentMap)) {
            List<SourceFile> sourceFiles = Lists.newArrayList();
            attachmentMap.forEach((key, attachments) -> sourceFiles.addAll(attachment2SourceFile(key, attachments)));
            saveSourceFile(sequenceNbr, sourceFiles);
        }
    }

    private List<SourceFile> attachment2SourceFile(String type, List<AttachmentDto> attachmentDtoList) {
        List<SourceFile> sourceFiles = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(attachmentDtoList)) {
            attachmentDtoList.forEach(a -> {
                SourceFile s = new SourceFile();
                s.setFilePath(a.getUrl());
                s.setFileName(a.getName());
                s.setFileCategory(type);
                sourceFiles.add(s);
            });
        }
        return sourceFiles;
    }

    /**
     * 获取附件
     *
     * @param sourceId
     * @return
     */
    @Override
    public Map<String, List<AttachmentDto>> getAttachments(Long sourceId) {
        Map<String, List<AttachmentDto>> attachmentMap = Maps.newHashMap();
        List<SourceFile> sourceFileList = findBySourceId(sourceId);
        if (!ValidationUtil.isEmpty(sourceFileList)) {
            List<AttachmentDto> attachmentList = sourceFile2AttachmentList(sourceFileList);
            attachmentMap = attachmentList.stream().collect(Collectors.groupingBy(AttachmentDto::getType));
        }
        return attachmentMap;
    }

    private List<AttachmentDto> sourceFile2AttachmentList(List<SourceFile> sourceFileList) {
        List<AttachmentDto> attachmentDtoList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(sourceFileList)) {
            sourceFileList.forEach(s -> {
                AttachmentDto a = new AttachmentDto();
                a.setName(s.getFileName());
                a.setUrl(s.getFilePath());
                a.setType(s.getFileCategory());
                attachmentDtoList.add(a);
            });
        }
        return attachmentDtoList;
    }
}