package cn.cslg.report.service.business;

import cn.cslg.report.common.model.vo.CompareScenariosVO;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.*;
import cn.cslg.report.entity.asso.AssoRecordsFeature;
import cn.cslg.report.mapper.CompareScenariosMapper;
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 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 CompareScenariosService extends ServiceImpl<CompareScenariosMapper, CompareScenarios> {
    private final CompareScenariosAndRecordsService compareScenariosAndRecordsService;
    private final AssoScenarIOSService assoScenarIOSService;
    private final CompareFilesService compareFilesService;
    private  final LoginUtils loginUtils;
    private final CompareRecordsService compareRecordsService;
    private final FeatureService featureService;
    private final AssoRecordsFeatureService assoRecordsFeatureService;

    /**
     * @function：添加对比文件根据，关联表：同时添加对比方案与对比记录关联表
     * @param compareScenariosVO
     * @return 是否成功
     * @throws IOException
     *
     */
    public String add(CompareScenariosVO compareScenariosVO) throws IOException{
        if(compareScenariosVO.getFeaturesIDList().size()==0&&compareScenariosVO.getRecordIDList().size()==0){
            return Response.error("请至少选择一个特征");
        }
        //对比方案信息入表
        CompareScenarios compareScenarios = new CompareScenarios();
        compareScenarios.setContrastResult(compareScenariosVO.getContrastResult());
        compareScenarios.setReportId(compareScenariosVO.getReportId());
        compareScenarios.setRightName(compareScenariosVO.getRight());
        //拿到当前登录人的id
        compareScenarios.setPersonId(loginUtils.getId());
        compareScenarios.setRightId(compareScenariosVO.getRightId());
        compareScenarios.setSignPatentNo(compareScenariosVO.getSignPatentNo());
        compareScenarios.insert();
        Integer id = compareScenarios.getId();
        List<Integer> FeaturesId = compareScenariosVO.getFeaturesIDList();
        //根据特征id来插入对比方案与对比记录关联表
        for(Integer integer:FeaturesId){
            AssoScenarIOS compareScenariosAndRecords = new AssoScenarIOS();
            compareScenariosAndRecords.setScenariosID(id);
            compareScenariosAndRecords.setFeaturesID(integer);
            compareScenariosAndRecords.setFeatureRecordID(0);
            compareScenariosAndRecordsService.add(compareScenariosAndRecords);
        }
        //根据共识来插入
        List<Integer> recordIDList = compareScenariosVO.getRecordIDList();
        for(Integer integer:recordIDList) {
            AssoScenarIOS compareScenariosAndRecords = new AssoScenarIOS();
            compareScenariosAndRecords.setScenariosID(id);
            compareScenariosAndRecords.setFeatureRecordID(integer);
            compareScenariosAndRecords.setFeaturesID(0);
            compareScenariosAndRecordsService.add(compareScenariosAndRecords);
        }
       return Response.success();
    }
    /**
     * @function：根据报告id查询对比方案
     * @param reportID
     * @return：对比方案 对应实体：CompareScenariosVO
     * @throws IOException
     */
    public String select(int reportID)throws IOException{
       List<CompareScenariosVO> list=new ArrayList<>();
       //根据报告ID查询对比方案
        LambdaQueryWrapper<CompareScenarios> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompareScenarios::getReportId, reportID);
        List<CompareScenarios> CompareScenarios = this.list(wrapper);
        //根据报告ID和权要id获得特征
        LambdaQueryWrapper<Features> featuresWrapper =new LambdaQueryWrapper<>();
        featuresWrapper.eq(Features::getReportId,reportID);
        List<Features> allFeatures =featureService.list(featuresWrapper);
        //遍历对比方案
        for (CompareScenarios a:CompareScenarios){
            CompareScenariosVO compareScenariosVO=new CompareScenariosVO();
            compareScenariosVO.setRightId(a.getRightId());
            compareScenariosVO.setContrastResult( a.getContrastResult());
            compareScenariosVO.setReportId(a.getReportId());
            compareScenariosVO.setSignPatentNo(  a.getSignPatentNo());
            compareScenariosVO.setRight(a.getRightName());
            compareScenariosVO.setId(a.getId());
            //获得对比方案的特征列表
            List<Features> featuresLists =allFeatures.stream().filter(item->item.getRightId().equals(a.getRightId())).collect(Collectors.toList());

            //根据对比方案ID获得所有对比方案和对比记录关联信息
            List<AssoScenarIOS> select = assoScenarIOSService.select(a.getId());
            //获得Id不为0的对比记录和特征关联Id
            List<Integer> featureRecordIds = select.stream().filter(item->item.getFeatureRecordID()!=0).map(AssoScenarIOS::getFeatureRecordID).collect(Collectors.toList());
            //根据关联Id获得特征Id和对比记录ID
            List<AssoRecordsFeature> assoRecordsFeatures =new ArrayList<>();
            List<AssoRecordsFeature> assoRecordsFeatures1 =new ArrayList<>();
            if(featureRecordIds.size()!=0) {
                LambdaQueryWrapper<AssoRecordsFeature> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.in(AssoRecordsFeature::getId, featureRecordIds);
                assoRecordsFeatures = assoRecordsFeatureService.list(wrapper1);

            //获取特征Id
            List<Integer> featureIds= assoRecordsFeatures.stream().map(AssoRecordsFeature::getFeatureId).collect(Collectors.toList());
            //对比记录Id
            List<Integer> recordId  =assoRecordsFeatures.stream().map(AssoRecordsFeature::getRecordsId).collect(Collectors.toList());
            //根据特征Id查询特征
            LambdaQueryWrapper<Features> wrapper2 =new LambdaQueryWrapper<>();
            wrapper2.in(Features::getId,featureIds);
            List<Features> features =featureService.list(wrapper2);
            //根据记录ID查询记录
            LambdaQueryWrapper<CompareRecords> wrapper3 =new LambdaQueryWrapper<>();
            wrapper3.in(CompareRecords::getId,recordId);
            List<CompareRecords> compareRecords =compareRecordsService.list(wrapper3);

            for(Features item : featuresLists) {
                AssoRecordsFeature assoRecordsFeature = assoRecordsFeatures.stream().filter(te->te.getFeatureId().equals(item.getId())).findFirst().orElse(new AssoRecordsFeature());
                //筛选对比文件
                CompareRecords compareRecords1 = compareRecords.stream().filter(tem -> tem.getId().equals(assoRecordsFeature.getRecordsId())).findFirst().orElse(new CompareRecords());
                //根据对比记录的专利号和内容进行合并操作
                if(assoRecordsFeatures1.size()!=0){
                    //获得上一条的记录信息
                    AssoRecordsFeature assoRecordsFeature2 = assoRecordsFeatures1.get(assoRecordsFeatures1.size()-1);
                    CompareRecords compareRecords2 =assoRecordsFeature2.getCompareRecords();
                    //进行合并
                    if(compareRecords1.getId()!=null&&compareRecords1.getPatentNo().equals(compareRecords2.getPatentNo())
                            &&compareRecords1.getContent().equals(compareRecords2.getContent()))
                    {
               assoRecordsFeature2.getFeatures().setContent(assoRecordsFeature2.getFeatures().getContent()+item.getContent());
                    }
                    else{
                        assoRecordsFeature.setCompareRecords(compareRecords1);
                        assoRecordsFeature.setFeatures(item);
                        assoRecordsFeatures1.add(assoRecordsFeature);
                    }
                }
               else {
                    assoRecordsFeature.setCompareRecords(compareRecords1);
                    assoRecordsFeature.setFeatures(item);
                    assoRecordsFeatures1.add(assoRecordsFeature);
                }
            }
            }
            //过滤拿到特征id
           List<Integer> featuresIds =select.stream().filter(item->item.getFeatureRecordID().equals(0)).map(AssoScenarIOS::getFeaturesID).collect(Collectors.toList());
            //根据特征Id查询特征
            List<Features> featuresList =new ArrayList<>();
            if(featuresIds!=null&&featuresIds.size()>0) {
                LambdaQueryWrapper<Features> wrapper4 = new LambdaQueryWrapper<>();
                wrapper4.in(Features::getId,featuresIds);
                featuresList=featureService.list(wrapper4);
            }
            compareScenariosVO.setFeaturesList(featuresList);
            compareScenariosVO.setFeaturesIDList(featuresIds);
            compareScenariosVO.setAssoRecordsFeatures(assoRecordsFeatures1);
         list.add(compareScenariosVO);
        }
        return Response.success(list);

    }

    /**
     * @DESCRIPTION 根据报告ID删除对比方案
     * @param reportId 报告ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByReportId(Integer reportId){
         LambdaQueryWrapper<CompareScenarios> queryWrapper =new LambdaQueryWrapper<>();
         queryWrapper.eq(CompareScenarios::getReportId,reportId);
        return  this.remove(queryWrapper);
    }
    public Boolean deleteById(List<Integer> scenIds)throws IOException{
        List<CompareScenariosVO> list=new ArrayList<>();
        //根据报告ID查询对比方案
        LambdaQueryWrapper<AssoScenarIOS> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AssoScenarIOS::getScenariosID, scenIds);
  assoScenarIOSService.remove(wrapper);
  Boolean flag =this.removeByIds(scenIds);
        return flag;

    }

}
