package cn.cslg.report.service.business;


import cn.cslg.report.common.utils.Response;
import cn.cslg.report.entity.*;
import cn.cslg.report.entity.asso.AssoLitigationHisFile;

import cn.cslg.report.mapper.LitigationHistoryMapper;
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.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
@SuppressWarnings({"all"})
public class LitigationHistoryService extends ServiceImpl<LitigationHistoryMapper, LitigationHistory> {
    private final ReportFileService reportFileService;
    private final AssoLitigationHisFileService  assoLitigationHisFileService;

    /**
     * @function: 删除诉讼历史 （对比方案与对比记录表的内容也要删除，报告也要删除）
     * @param id 诉讼历史id
     * @return
     */
    public String deleteLitigationHistory(int id){
        LitigationHistory litigationHistory =this.getById(id);
        this.removeById(id);
        LambdaQueryWrapper<AssoLitigationHisFile> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoLitigationHisFile::getLitiHisId,litigationHistory.getId());
        List<AssoLitigationHisFile> assoes= assoLitigationHisFileService.list(wrapper);
        List<Integer> fileIds =assoes.stream().map(AssoLitigationHisFile::getFileId).collect(Collectors.toList());
        //根据对比文件id删除报告
        reportFileService.removeByIds(fileIds);
        // 根据对比文件id对比方案与对比记录
        assoLitigationHisFileService.remove(wrapper);
       return Response.success();
    }

    /**
     * @function: 增加诉讼历史
     * @param litigationHistory
     * @param files 诉讼文件
     * @return
     */
    public String addLitigationHistory(LitigationHistory litigationHistory,List<MultipartFile> files){
        // 插入诉讼历史
        litigationHistory.insert();
        if (files!=null&&files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIds = reportFileService.uploadFiles(files);
            // 对比方案与对比记录 插入
            assoLitigationHisFileService.addAsso(litigationHistory.getId(),fileIds);
        }
        return Response.success();
    }
    /**
     * @function: 修改诉讼历史
     * @param litigationHistory
     * @param files 诉讼文件
     * @return
     */
    public Boolean updateLitigationHistory(LitigationHistory litigationHistory,List<MultipartFile> files){

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

        }

        return litigationHistory.updateById();
    }

    /**
     * @function: 根据专利号查询诉讼历史
     * @param litigationHistory
     * @return
     */

    public String queryLitigationHistory(LitigationHistory litigationHistory){
        LambdaQueryWrapper<LitigationHistory> wrapper =new LambdaQueryWrapper<>();
               wrapper.eq(LitigationHistory::getPatentNo,litigationHistory.getPatentNo());
               //分页
        if (litigationHistory.getSize() != null && litigationHistory.getCurrent() != null) {
            IPage<LitigationHistory> pages = this.page(new Page<>(litigationHistory.getCurrent(), litigationHistory.getSize()), wrapper);
            pages.setRecords(this.LitigationHistory(pages.getRecords()));
            return Response.success(pages);
        } else {
            List<LitigationHistory>  histories= this.list(wrapper);
            histories =this.LitigationHistory(histories);
            return Response.success(histories);
        }
    }

    /**
     * @function:  装载诉讼历史
     * @param litigationHistories
     * @return
     */
    public List<LitigationHistory> LitigationHistory(List<LitigationHistory> litigationHistories) {
        //获得诉讼历史的Id
        List<Integer> ids = litigationHistories.stream().map(LitigationHistory::getId).collect(Collectors.toList());
        if (ids.size() != 0) {
            //根据诉讼历史的Id获得诉讼历史和文件的关联信息
            LambdaQueryWrapper<AssoLitigationHisFile> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(AssoLitigationHisFile::getLitiHisId, ids);
            List<AssoLitigationHisFile> assoLitigationHisFiles = assoLitigationHisFileService.list();
            //根据关联信息查询附件信息
            if (assoLitigationHisFiles.size() != 0) {
                List<Integer> fileIds = assoLitigationHisFiles.stream().map(AssoLitigationHisFile::getFileId).collect(Collectors.toList());
                LambdaQueryWrapper<ReportFiles> wrapper = new LambdaQueryWrapper<>();
                wrapper.in(ReportFiles::getId, fileIds);
                List<ReportFiles> reportFiles = reportFileService.list(wrapper);
                //遍历装载文件信息
                litigationHistories.forEach(item -> {
                    List<AssoLitigationHisFile> partAsso = assoLitigationHisFiles.stream().filter(tem -> tem.getLitiHisId().equals(item.getId())).collect(Collectors.toList());
                    List<ReportFiles> reportFilesList = new ArrayList<>();
                    if (partAsso.size() != 0) {
                        List<Integer> partFileIds = partAsso.stream().map(AssoLitigationHisFile::getFileId).collect(Collectors.toList());
                        List<ReportFiles> reportFiles1 = reportFiles.stream().filter(tem -> partFileIds.contains(tem.getId())).collect(Collectors.toList());
                        reportFilesList = reportFiles1;
                    }
                    item.setReportFiles(reportFilesList);
                });
            }

        }
        return litigationHistories;

    }

}
