package cn.cslg.report.service.business;

import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.CompareFiles;
import cn.cslg.report.entity.CompareRecords;
import cn.cslg.report.entity.Features;
import cn.cslg.report.entity.asso.AssoRecordsFeature;
import cn.cslg.report.entity.asso.AssoTaskPersonel;
import cn.cslg.report.mapper.CompareRecordsMapper;
import cn.cslg.report.mapper.FeatureMapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
@SuppressWarnings({"all"})
public class CompareRecordsService extends ServiceImpl<CompareRecordsMapper, CompareRecords> {
    public final CompareRecordsMapper compareRecordsMapper;
    public final FeatureMapper featureMapper;
    public final LoginUtils loginUtils;
    public final FeatureService featureService;
    public final AssoRecordsFeatureService assoRecordsFeatureService;
    public final CompareFilesService compareFilesService;
    private final ReportFileService reportFileService;
    private final  AssoTaskPersonelService assoTaskPersonelService;

    @Transactional(rollbackFor = Exception.class)
    public String addCompareRecord(CompareRecords compareRecord,List<MultipartFile> files) throws IOException {
        if (files != null && files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<String> fileNames = reportFileService.uploadFilesGetName(files);
            compareRecord.setFilePath(fileNames.get(0));
        }
        compareRecord.insert();
        //对比方案与对比记录关联表对比文件添加
        List<AssoRecordsFeature> assoRecordsFeatures = compareRecord.getAssoRecordsFeatures();
        assoRecordsFeatures.forEach(item -> item.setRecordsId(compareRecord.getId()));
        assoRecordsFeatureService.saveBatch(assoRecordsFeatures);
        //已读状态
        LambdaQueryWrapper<AssoTaskPersonel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AssoTaskPersonel::getTaskId,compareRecord.getTaskId()).eq(AssoTaskPersonel::getPatentNo,compareRecord.getPatentNo());
        AssoTaskPersonel assoTaskPersonel = assoTaskPersonelService.list(queryWrapper).get(0);
        assoTaskPersonel.setState(1);
        assoTaskPersonel.updateById();
        return Response.success();

    }

    /**
     * @function: 根据对比记录的id删除对比记录
     * @param id CompareRecords实体类的id
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    public String deleCompareRecords(List<Integer> ids) throws IOException {
        // 根据对比记录Id 获得对比记录特征关联Id
        LambdaQueryWrapper<AssoRecordsFeature> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.in(AssoRecordsFeature::getRecordsId,ids);
        List<AssoRecordsFeature> assoRecordsFeatures = assoRecordsFeatureService.list(queryWrapper);
        List<Integer> assoIds=assoRecordsFeatures.stream().map(AssoRecordsFeature::getId).collect(Collectors.toList());
        //删除关联信息
        assoRecordsFeatureService.deleleAssos(assoIds);
        //根据对比记录Id 删除对比记录
        this.removeByIds(ids);
        //
        return Response.success();
    }

    /**
     *
     * @param compareRecord
     * @param files
     * @return
     * @throws IOException
     * @autor lrj
     */
    @Transactional(rollbackFor = Exception.class)
    public String updateCompareRecords(CompareRecords compareRecord,List<MultipartFile> files) throws IOException {
        if (files != null && files.size() != 0) {
            //将文档上传并返回文件入库的Id
            List<String> fileNames = reportFileService.uploadFilesGetName(files);
            compareRecord.setFilePath(fileNames.get(0));
        }
        if(compareRecord.getFilePath() == null){
            compareRecord.setFilePath("");
        }
        List<AssoRecordsFeature> assoRecordsFeatures = compareRecord.getAssoRecordsFeatures();
        List<Integer> nowIds =assoRecordsFeatures.stream().filter(item->item.getId()!=null).map(AssoRecordsFeature::getId).collect(Collectors.toList());
        //删除原本的记录-特征关联关系
        LambdaQueryWrapper<AssoRecordsFeature> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(AssoRecordsFeature::getRecordsId,compareRecord.getId());
        List<AssoRecordsFeature> assoRecordsFeature  = assoRecordsFeatureService.list(queryWrapper);
        List<Integer> assoIds=assoRecordsFeature.stream().map(AssoRecordsFeature::getId).collect(Collectors.toList());
        assoIds.removeAll(nowIds);
        assoRecordsFeatureService.deleleAssos(assoIds);
        //添加新的特征记录关联关系
        assoRecordsFeatures.forEach(item -> item.setRecordsId(compareRecord.getId()));
        assoRecordsFeatureService.saveOrUpdateBatch(assoRecordsFeatures);
        compareRecord.updateById();
        return Response.success();
    }
    /**
     * @function: 根据对比记录的报告id，任务
     * @param compareRecord
     * @return 对比文件 对应实体：compareFiles 对比记录 对应实体：compareRecord
     * @throws IOException
     */
    public String getCompareRecords(CompareRecords compareRecord) throws IOException {
        //根据报告id查询对比文件
        LambdaQueryWrapper<CompareRecords> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompareRecords::getReportId, compareRecord.getReportId());
        //根据标的专利号获取对比文件
        if (compareRecord.getPatentNo() != null) {
            wrapper.eq(CompareRecords::getPatentNo, compareRecord.getPatentNo());
        }
        //根据任务id查询对比文件
        if(compareRecord.getTaskId()!=null){
           wrapper.eq(CompareRecords::getTaskId,compareRecord.getTaskId());
        }
        List<CompareRecords> list = new ArrayList<>();
        List<CompareRecords> compareRecords = this.list(wrapper);
        if (compareRecords.size() == 0 || compareRecords == null) {
            return Response.success(list);
        }
        //获取对比文件的id
        List<Integer> ids = compareRecords.stream().map(CompareRecords::getId).collect(Collectors.toList());
        if (ids.size() == 0) {
            return Response.success(compareRecords);
        }
        //根据任务id获取获取对比方案与对比记录关联表
        LambdaQueryWrapper<AssoRecordsFeature> assoWrapper = new LambdaQueryWrapper<>();
        assoWrapper.in(AssoRecordsFeature::getRecordsId, ids);
        List<AssoRecordsFeature> assoRecordsFeatures = assoRecordsFeatureService.list(assoWrapper);
        //获取特征id
        List<Integer> featureIds = assoRecordsFeatures.stream().map(AssoRecordsFeature::getFeatureId).collect(Collectors.toList());
        List<Features> features = new ArrayList<>();
        if (featureIds.size() != 0 && featureIds != null) {
            LambdaQueryWrapper<Features> featuresLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //获取标的专利的特征
            featuresLambdaQueryWrapper.in(Features::getId, featureIds);
            features = featureService.list(featuresLambdaQueryWrapper);

        }
        List<String> headerPatentNos = new ArrayList<>();
        for (CompareRecords records : compareRecords) {
            List<AssoRecordsFeature> assoRecordsFeatures1 = assoRecordsFeatures.stream().filter(item -> item.getRecordsId().equals(records.getId())).collect(Collectors.toList());
            //获取特征id
            List<Integer> featureId = assoRecordsFeatures1.stream().map(AssoRecordsFeature::getFeatureId).collect(Collectors.toList());
            records.setAssoRecordsFeatures(assoRecordsFeatures1);
            //根据获取的过滤
            List<Features> featuresList = features.stream().filter(item -> featureId.contains(item.getId())).collect(Collectors.toList());
            records.setFeaturesIdList(featureId);
            records.setFeatures(featuresList);
            if(!headerPatentNos.contains(records.getPatentNo())){
            headerPatentNos.add(records.getPatentNo());}
}
        List<CompareFiles> compareFiles =new ArrayList<>();
        if(headerPatentNos.size()!=0){
            LambdaQueryWrapper<CompareFiles> lambdaQueryWrapper =new LambdaQueryWrapper<>();
            //获取对比文件
            lambdaQueryWrapper.in(CompareFiles::getPatentNo,headerPatentNos).eq(CompareFiles::getReportId,compareRecord.getReportId());
             compareFiles =compareFilesService.list(lambdaQueryWrapper);

        }
        Map<String,Object> map =new HashMap<>();
        map.put("tableHeader",compareFiles);
        map.put("records",compareRecords);
        return Response.success(map);
    }

    /**
     * @function： 根据对比方案的id查询对比方案
     * @param ：对比方案的id；
     * @return 对比方案，对应实体：CompareRecords
     */
    public CompareRecords get(int id){
        LambdaQueryWrapper<CompareRecords> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(CompareRecords::getId,id);
        List<CompareRecords> list = this.list(lambdaQueryWrapper);
        if(list.size()==0){
            return null;
        }
        return list.get(0);

    }
    /**
     * funtion: 删除报告时删除
     */
    public String deleteByTaskId(Integer id){
        LambdaQueryWrapper<CompareRecords> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CompareRecords::getTaskId,id);
        remove(lambdaQueryWrapper);
        return Response.success();
    }

    /**
     * 获得排序列表
     * @param reportId
     * @return
     */



}
