package cn.cslg.report.service.business;

import cn.cslg.report.common.utils.Response;
import cn.cslg.report.entity.*;
import cn.cslg.report.entity.asso.AssoInvalidRecordFile;
import cn.cslg.report.mapper.InvalidRecordMapper;
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.transaction.annotation.Transactional;
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 InvalidRecordService extends ServiceImpl<InvalidRecordMapper, InvalidRecord> {
    public final InvalidRecordMapper invalidRecordMapper;
    private final ReportFileService reportFileService;
    private final AssoInvalidRecordFileService assoInvalidRecordFileService;

    /**
     * @function 删除无效记录对比方案与对比记录也要删除
     * @param id
     * @return
     * @throws IOException
     */
    public String deleteInvalidRecord(int id) throws IOException {
        InvalidRecord invalidRecord =this.getById(id);
        this.removeById(id);
        LambdaQueryWrapper<AssoInvalidRecordFile> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AssoInvalidRecordFile::getInvalidId,invalidRecord.getId());
        List<AssoInvalidRecordFile> assoes= assoInvalidRecordFileService.list(wrapper);
        List<Integer> fileIds =assoes.stream().map(AssoInvalidRecordFile::getFileId).collect(Collectors.toList());
        //根据任务id 删除对比方案与对比记录
        reportFileService.removeByIds(fileIds);
        assoInvalidRecordFileService.remove(wrapper);
        return Response.success();
    }

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

        }

        return invalidRecord.updateById();
    }

    @Transactional(rollbackFor = Exception.class)
    public String addInvalidRecord(InvalidRecord invalidRecord, List<MultipartFile> files) throws IOException {
        invalidRecord.insert();
        if (files != null && files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<Integer> fileIds = reportFileService.uploadFiles(files);
            assoInvalidRecordFileService.addAsso(invalidRecord.getId(), fileIds);
        }
        return Response.success();
    }

    /**
     *@function：查找无效记录
     * @param invalidRecord
     * @return 无效记录
     */

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

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

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

        }
        return invalidRecords;

    }



}

