package cn.cslg.report.service.business;

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

import cn.cslg.report.entity.asso.AssoReviewHisFile;
import cn.cslg.report.mapper.ReviewHistoryMapper;

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 ReviewHistoryService extends ServiceImpl<ReviewHistoryMapper, ReviewHistory> {
private final   ReportFileService reportFileService;
private final AssoReviewHisFileService assoReviewHisFileService;

    /**
     * @function 删除审查历史
     * @param id
     * @return
     * @throws IOException
     */
    public String deleteReviewHistory(int id) throws IOException {
        ReviewHistory ReviewHistory =this.getById(id);
        this.removeById(id);
        LambdaQueryWrapper<AssoReviewHisFile> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoReviewHisFile::getReviewHistoryId,ReviewHistory.getId());
        List<AssoReviewHisFile> assoes= assoReviewHisFileService.list(wrapper);
        List<Integer> fileIds =assoes.stream().map(AssoReviewHisFile::getFileId).collect(Collectors.toList());
        //对应的文件也要删除
        reportFileService.removeByIds(fileIds);
        //对比方案与对比记录关联表 也要删除
        assoReviewHisFileService.remove(wrapper);
        this.removeById(id);
        return Response.success();
    }

    /**
     * @function 修改审查历史
     * @param reviewHistory 审查历史
     * @param files 文件
     * @return
     */
    public Boolean updateReviewHistory(ReviewHistory reviewHistory,List<MultipartFile> files)  {
        // 根据无效Id查询对应的附件Id
        LambdaQueryWrapper<AssoReviewHisFile> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoReviewHisFile::getReviewHistoryId,reviewHistory.getId());
        List<AssoReviewHisFile> assoes= assoReviewHisFileService.list(wrapper);
        List<Integer> fileIds =assoes.stream().map(AssoReviewHisFile::getFileId).collect(Collectors.toList());
        // 获得更新后的附件Id
        List<Integer> updateFileId =new ArrayList<>();
        if(reviewHistory.getReportFiles()!=null){
            updateFileId = reviewHistory.getReportFiles().stream().map(ReportFiles::getId).collect(Collectors.toList());
            fileIds.removeAll(updateFileId);}
        //做差获得被删除的文件Id
        if(fileIds.size()!=0){
            //根据文件Id删除报告文件关联表记录
            LambdaQueryWrapper<AssoReviewHisFile> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.in(AssoReviewHisFile::getFileId,fileIds);
            assoReviewHisFileService.remove(deleteWrapper);
            //根据文件Id删除文件表记录
            reportFileService.removeByIds(fileIds);
        }
          //添加附件
        if (files!=null&&files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIdList = reportFileService.uploadFiles(files);
            assoReviewHisFileService.addAsso(reviewHistory.getId(), fileIdList);

        }
        return reviewHistory.updateById();
    }
    /**
     * @function 增加审查历史
     * @param reviewHistory 审查历史
     * @param files 文件
     * @return
     */
    public String addReviewHistory(ReviewHistory reviewHistory,List<MultipartFile> files) throws IOException {
        reviewHistory.insert();
        if (files!=null&&files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIds = reportFileService.uploadFiles(files);
            //对比方案与对比记录关联表 增加
            assoReviewHisFileService.addAsso(reviewHistory.getId(),fileIds);
        }
        return Response.success();
    }

    /**
     * @function 根据专利号查询审查历史（分页）
     * @param reviewHistory
     * @return
     */
    public String queryReviewHistory(ReviewHistory reviewHistory){
        LambdaQueryWrapper<ReviewHistory> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(ReviewHistory::getPatentNo,reviewHistory.getPatentNo());
        if (reviewHistory.getSize() != null && reviewHistory.getCurrent() != null) {
            IPage<ReviewHistory> pages = this.page(new Page<>(reviewHistory.getCurrent(), reviewHistory.getSize()), wrapper);
            pages.setRecords(this.thisReviewHistory(pages.getRecords()));
            return Response.success(pages);
        } else {
            List<ReviewHistory> reviewHistories= this.list(wrapper);
            reviewHistories =thisReviewHistory(reviewHistories);
            return Response.success(reviewHistories);
        }
    }

    /**
     * @function:装载无效记录
     * @param reviewHistories
     * @return
     */

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

        }
        return reviewHistories;

    }

}