package cn.cslg.report.service.business;

import cn.cslg.report.common.utils.Response;
import cn.cslg.report.entity.ReportFiles;

import cn.cslg.report.entity.References;

import cn.cslg.report.entity.asso.AssoReferenceFile;

import cn.cslg.report.mapper.ReferencesMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
@SuppressWarnings({"all"})
public class ReferencesService extends ServiceImpl<ReferencesMapper, References> {
  private  final ReportFileService reportFileService;
  private final AssoReferenceFileService assoReferenceFileService;

    /**
     * @function: 根据无效记录的id 删除无效记录（关联的对比方案与对比记录 文件 也要删除）
     * @param id
     * @return
     * @throws IOException
     */
    public String deleteReferences(int id) throws IOException {
        References references =this.getById(id);
        this.removeById(id);
        LambdaQueryWrapper<AssoReferenceFile> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoReferenceFile::getReferenceId,references.getId());
        List<AssoReferenceFile> assoes= assoReferenceFileService.list(wrapper);
        List<Integer> fileIds =assoes.stream().map(AssoReferenceFile::getFileId).collect(Collectors.toList());
        //删除对应的对比文件
        reportFileService.removeByIds(fileIds);
        //关联的对比方案与对比记录的删除
        assoReferenceFileService.remove(wrapper);
        return Response.success();
    }

    /**
     * @function: 修改无效记录 （关联的对比方案与对比记录 文件 也要修改）
     * @param references 无效记录
     * @param files 对比文件
     * @return
     * @throws IOException
     */

    public Boolean updateReferences(References references, List<MultipartFile> files) throws IOException {

        // 根据无效Id查询对应的附件Id
        LambdaQueryWrapper<AssoReferenceFile> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoReferenceFile::getReferenceId,references.getId());
        List<AssoReferenceFile> assoes= assoReferenceFileService.list(wrapper);
        List<Integer> fileIds =assoes.stream().map(AssoReferenceFile::getFileId).collect(Collectors.toList());
        // 获得更新后的附件Id
        List<Integer> updateFileId =new ArrayList<>();
        if(references.getReportFiles()!=null){
            updateFileId = references.getReportFiles().stream().map(ReportFiles::getId).collect(Collectors.toList());
            fileIds.removeAll(updateFileId);}
        //做差获得被删除的文件Id
        if(fileIds.size()!=0){
            //根据文件Id删除报告文件关联表记录
            LambdaQueryWrapper<AssoReferenceFile> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.in(AssoReferenceFile::getFileId,fileIds);
            assoReferenceFileService.remove(deleteWrapper);
            //根据文件Id删除文件表记录
            reportFileService.removeByIds(fileIds);
        }
            //添加附件
        if (files!=null&&files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIdList = reportFileService.uploadFiles(files);
            assoReferenceFileService.addAsso(references.getId(), fileIdList);

        }
        return references.updateById();
    }
    /**
     * @function: 增加无效记录（关联的对比方案与对比记录 文件 也要增加）
     * @param references 无效记录
     * @param files 对比文件
     * @return
     * @throws IOException
     */

    public String addReferences(References references,List<MultipartFile> files) throws IOException {
        references.insert();
        if (files!=null&&files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIds = reportFileService.uploadFiles(files);
            assoReferenceFileService.addAsso(references.getId(),fileIds);
        }
        return Response.success();
    }

    /**
     * @function: 根据专利号查询无效分析（分页）
     * @param references
     * @return
     */
    public String queryReferences(References references){
        LambdaQueryWrapper<References> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(References::getPatentNo,references.getPatentNo());
        //分页
        if (references.getSize() != null && references.getCurrent() != null) {
            IPage<References> pages = this.page(new Page<>(references.getCurrent(), references.getSize()), wrapper);
            pages.setRecords(this.thisReference(pages.getRecords()));
            return Response.success(pages);
        } else {
            List<References> referencesList= this.list(wrapper);
            referencesList =this.thisReference(referencesList);
            return Response.success(referencesList);
        }
    }

    /**
     * @function: 装载其他参考资料
     * @param references
     * @return
     */


    public List<References> thisReference(List<References> references) {
        //获得无效记录的Id
        List<Integer> ids = references.stream().map(References::getId).collect(Collectors.toList());
        if (ids.size() != 0) {
            //根据无效记录Id获得无效记录和文件的关联信息
            LambdaQueryWrapper<AssoReferenceFile> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(AssoReferenceFile::getReferenceId, ids);
            List<AssoReferenceFile> assoReferenceFiles = assoReferenceFileService.list();
            //根据关联信息查询附件信息
            if (assoReferenceFiles.size() != 0) {
                List<Integer> fileIds = assoReferenceFiles.stream().map(AssoReferenceFile::getFileId).collect(Collectors.toList());
                LambdaQueryWrapper<ReportFiles> wrapper = new LambdaQueryWrapper<>();
                wrapper.in(ReportFiles::getId, fileIds);
                List<ReportFiles> reportFiles = reportFileService.list(wrapper);
                //遍历装载文件信息
                references.forEach(item -> {
                    List<AssoReferenceFile> partAsso = assoReferenceFiles.stream().filter(tem -> tem.getReferenceId().equals(item.getId())).collect(Collectors.toList());
                    List<ReportFiles> reportFilesList = new ArrayList<>();
                    if (partAsso.size() != 0) {
                        List<Integer> partFileIds = partAsso.stream().map(AssoReferenceFile::getFileId).collect(Collectors.toList());
                        List<ReportFiles> reportFiles1 = reportFiles.stream().filter(tem -> partFileIds.contains(tem.getId())).collect(Collectors.toList());
                        reportFilesList = reportFiles1;
                    }
                    item.setReportFiles(reportFilesList);
                });
            }

        }
        return references;

    }

}