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.Picture;
import cn.cslg.report.entity.asso.AssoRecordsFeature;
import cn.cslg.report.mapper.CompareScenariosMapper;
import cn.hutool.core.util.IdUtil;
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.apache.commons.compress.utils.IOUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
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);
        //获得所有对比方案id进而获得所有对比方案和特征-对比记录关联id
        List<Integer> scenarioIds =compareScenarios.stream().map(CompareScenarios::getId).collect(Collectors.toList());
        List<AssoScenarIOS> selects = assoScenarIOSService.select(scenarioIds);
        //遍历对比方案
        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 = selects.stream().filter(item->item.getScenariosID()==a.getId()).collect(Collectors.toList());
            //获得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查询特征
            List<Features> features = allFeatures.stream().filter(item->featureIds.contains(item.getId())).collect(Collectors.toList());
            List<CompareRecords> compareRecords =new ArrayList<>();
            if(recordId!=null&&recordId.size()>0) {
                LambdaQueryWrapper<CompareRecords> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.in(CompareRecords::getId, recordId);
                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());
                    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) {
                featuresList= allFeatures.stream().filter(item->featuresIds.contains(item.getId())).collect(Collectors.toList());
            }
            compareScenariosVO.setFeaturesList(featuresList);
            compareScenariosVO.setFeaturesIDList(featuresIds);
            compareScenariosVO.setAssoRecordsFeatures(assoRecordsFeatures1);
         list.add(compareScenariosVO);
        }
        return Response.success(list);

    }
    /**
     * @function：根据报告id查询对比方案
     * @param reportID
     * @return：对比方案 对应实体：CompareScenariosVO
     * @throws IOException
     */
    public String exportExcel (int reportID,List<Integer> scenariosIds)throws IOException, FileNotFoundException {
        String fileName = IdUtil.simpleUUID() + ".xls";
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook();
        XSSFSheet sheet = hssfWorkbook.createSheet();
        sheet.setDefaultColumnWidth(30);
        XSSFRow headerRow = sheet.createRow(0);
        headerRow.setHeight((short) 500);
        List<String> listExcel = Arrays.asList("权要", "对比组合", "特征", "公识", "对比专利", "对比内容", "对比结论/理由");
        for (int i = 0; i < listExcel.size(); i++) {
            XSSFCell cell = headerRow.createCell(i);
            cell.setCellValue(listExcel.get(i));
        }
        List<CompareScenariosVO> list=new ArrayList<>();
        //根据报告ID查询对比方案
        LambdaQueryWrapper<CompareScenarios> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompareScenarios::getReportId, reportID);
        if(scenariosIds!=null&&scenariosIds.size()>0) {
            wrapper.eq(CompareScenarios::getId,scenariosIds);
        }
        List<CompareScenarios> compareScenarios = this.list(wrapper);
        //根据报告ID和权要id获得特征
        LambdaQueryWrapper<Features> featuresWrapper =new LambdaQueryWrapper<>();
        featuresWrapper.eq(Features::getReportId,reportID);
        List<Features> allFeatures =featureService.list(featuresWrapper);
        //获得所有对比方案id进而获得所有对比方案和特征-对比记录关联id
        List<Integer> scenarioIds =compareScenarios.stream().map(CompareScenarios::getId).collect(Collectors.toList());
        List<AssoScenarIOS> selects = assoScenarIOSService.select(scenarioIds);
        int rowIndex =1;
        //遍历对比方案
        for ( int c=0;c<compareScenarios.size();c++ ){
            CompareScenarios a =compareScenarios.get(c);
            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 = selects.stream().filter(item->item.getScenariosID()==a.getId()).collect(Collectors.toList());
            //获得特征-记录关联Id不为0的对比记录和特征关联Id
            List<Integer> featureRecordIds = select.stream().filter(item->item.getFeatureRecordID()!=0).map(AssoScenarIOS::getFeatureRecordID).collect(Collectors.toList());
            //获得特征-记录关联Id为0的对比记录和特征关联Id
            List<Integer> commonFeatureIds = select.stream().filter(item->item.getFeatureRecordID()==0).map(AssoScenarIOS::getFeaturesID).collect(Collectors.toList());
            //根据关联Id获得特征Id和对比记录ID
            List<AssoRecordsFeature> assoRecordsFeatures =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查询特征
            List<Features> features = allFeatures.stream().filter(item->featureIds.contains(item.getId())).collect(Collectors.toList());
            List<CompareRecords> compareRecords =new ArrayList<>();
            if(recordId!=null&&recordId.size()>0) {
                LambdaQueryWrapper<CompareRecords> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.in(CompareRecords::getId, recordId);
                compareRecords = compareRecordsService.list(wrapper3);
            }
            XSSFCellStyle style = hssfWorkbook.createCellStyle();
            style.setWrapText(true);
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            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());
                int rowNum=sheet.getLastRowNum();
                XSSFRow row = sheet.createRow(rowNum+1);
                XSSFRow lastrow= sheet.getRow(rowNum);
                XSSFCell cell =lastrow.getCell(0);
                row.createCell(0).setCellValue(a.getRightName());
                row.createCell(1).setCellValue("对比组合"+(c+1));
                row.createCell(2).setCellValue(item.getContent());
              if(commonFeatureIds.contains(item.getId())) {
                  row.createCell(3).setCellValue("是");
              }
                if(compareRecords1!=null){
                    row.createCell(4).setCellValue(compareRecords1.getPatentNo());
                    row.createCell(5).setCellValue(compareRecords1.getContent());

                }
                String htmlString = a.getContrastResult();

                if(htmlString!=null) {
                    String base64EncodedImage = htmlString.substring(htmlString.indexOf("base64,") + 7, htmlString.lastIndexOf("\" style="));

                    byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedImage);
                    int pictureIdx = hssfWorkbook.addPicture(decodedBytes, Workbook.PICTURE_TYPE_PNG);
// 创建绘图对象和锚点
                    XSSFDrawing drawing = sheet.createDrawingPatriarch();
                    XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 5, 10);

// 插入图像
                    XSSFPicture picture = drawing.createPicture(anchor, pictureIdx);
                    picture.resize();
                    // 在单元格中写入HTML语句
                    XSSFRichTextString richString = new XSSFRichTextString();
                    richString.append("<html><head></head><body><h1>Hello World!</h1><img src='cid:image1'></body></html> ", new XSSFFont());
                    XSSFCell cell1 =row.createCell(6);
                    cell1.setCellValue(richString);
                    cell1.setCellStyle(style);
                }

              rowIndex++;
            }
            //过滤拿到特征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) {
                featuresList= allFeatures.stream().filter(item->featuresIds.contains(item.getId())).collect(Collectors.toList());
            }
            compareScenariosVO.setFeaturesList(featuresList);
            compareScenariosVO.setFeaturesIDList(featuresIds);
            list.add(compareScenariosVO);
        }

        FileOutputStream fos = new FileOutputStream("savePath" + fileName);
        try {
            hssfWorkbook.write(fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return Response.success("savePath" + fileName);
    }
    /**
     * @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;

    }

}
