package cn.cslg.report.service.business;

import cn.cslg.report.common.model.SystemMO;
import cn.cslg.report.common.model.vo.PatentVO;
import cn.cslg.report.common.model.vo.PersonnelVO;
import cn.cslg.report.common.utils.*;
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.ReportDocumentMapper;
import cn.cslg.report.mapper.TemplateMapper;
import cn.cslg.report.service.OutInterfaceService;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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 com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ReportDocumentService extends ServiceImpl<ReportDocumentMapper, ReportDocument> {

    private final OutInterfaceService outInterfaceService;
    private final CompareScenariosService compareScenariosService;
    private final CompareScenariosAndRecordsService scenariosRecordsService;
    private final CompareRecordsService compareRecordsService;
    private final AssoRecordsFeatureService assoRecordsFeatureService;
    private final FeatureService featureService;
    private final ReportService reportService;
    private final TemplateService templateService;
    private final FileUtils fileUtils;
    private final LoginUtils loginUtils;
    private final CacheUtils cacheUtils;

     public String reportDocument(ReportDocument reportDocument) {

       return  Response.success();

     }

     //根据报告Id获得报告的导出记录
    public String getExportList(ReportDocument reportDocument){
         LambdaQueryWrapper<ReportDocument> wrapper =new LambdaQueryWrapper<>();
         wrapper.eq(ReportDocument::getReportId,reportDocument.getReportId());
        IPage<ReportDocument> pages =this.page(new Page<>(reportDocument.getCurrent(),reportDocument.getSize()),wrapper);
         return  Response.success(pages);
    }

    public String deleteExport(Integer id) {
         this.removeById(id);
         return Response.success();
    }
    //导出报告
    public String exportReport(Integer reportId,Integer templeId) throws IOException {
          //根据模板ID获得模板
        Template reportTemplate=  templateService.getById(templeId);
        //获得模板路径
        String filePath =fileUtils.getPath(reportTemplate.getTemplatePath());
        // 读取模板后保存生成word的地址
        String fileName = IdUtil.simpleUUID() + ".docx";
        String directoryName = fileUtils.createDirectory();
        String outPath = fileUtils.getSavePath(directoryName)+fileName;
        //根据报告Id获得报告信息
        Report report = reportService.getById(reportId);
        // 根据拆分人（报告的创建人）Id和报告ID获得所有特征
        LambdaQueryWrapper<Features> allFeaturesWrapper = new LambdaQueryWrapper<>();
        allFeaturesWrapper.eq(Features::getPartnerId, report.getPersonId())
                .eq(Features::getReportId, report.getId());
        List<Features> allFeatures = featureService.list(allFeaturesWrapper);
        //查询所有的对比方案并获得Id
        LambdaQueryWrapper<CompareScenarios> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompareScenarios::getReportId, reportId);
        List<CompareScenarios> compareScenarios = compareScenariosService.list(queryWrapper);
        List<Integer> scenarioIds = compareScenarios.stream().map(CompareScenarios::getId).collect(Collectors.toList());
        //根据对比方案Id 从关联表里获得对比记录特征关联ID
        LambdaQueryWrapper<AssoScenarIOS> queryRecordsByIDs = new LambdaQueryWrapper<>();
        queryRecordsByIDs.in(AssoScenarIOS::getScenariosID, scenarioIds);
        List<AssoScenarIOS> scenariosRecords = scenariosRecordsService.list(queryRecordsByIDs);
        List<Integer> recordfeatureRecordIds = scenariosRecords.stream().map(AssoScenarIOS::getFeatureRecordID).collect(Collectors.toList());
        //根据关联ID查出报告Id和特征Id
        LambdaQueryWrapper<AssoRecordsFeature> wrapper =new LambdaQueryWrapper<>();
        wrapper.in(AssoRecordsFeature::getId,recordfeatureRecordIds);
        List<AssoRecordsFeature> assoRecordsFeatures =assoRecordsFeatureService.list(wrapper);
        List<Integer> recordIds =assoRecordsFeatures.stream().map(AssoRecordsFeature::getRecordsId).collect(Collectors.toList());
        //根据对比记录ID查询对比记录
        LambdaQueryWrapper<CompareRecords> queryPatentByIDs = new LambdaQueryWrapper<>();
        queryPatentByIDs.in(CompareRecords::getId, recordIds);
        List<CompareRecords> compareRecords = compareRecordsService.list(queryPatentByIDs);
        //根据对比记录ID获得专利号
        List<String> PatentNos = compareRecords.stream().map(CompareRecords::getPatentNo).collect(Collectors.toList());
        PatentVO patentVO = new PatentVO();
        patentVO.setPatentNos(PatentNos);
        //根据专利号查询专利详细信息
        String resBody = outInterfaceService.getPatentDTOListForRMS(patentVO);
        JSONObject jsonObject = JSONObject.parseObject(resBody);
        List<JSONObject> patentDTOS = JSON.parseArray(jsonObject.get("data").toString(), JSONObject.class);
        //存放专利信息的map集合
        List<Map<String, Object>> patentListMaps = new ArrayList<>();
        //专利号别名的map
        Map<String, Object> OtherName = new HashMap<>();
        //填充专利数据到patentListMap
        for (int i = 0; i < patentDTOS.size(); i++) {
            JSONObject item = patentDTOS.get(i);
            Map<String, Object> patentListMap = new HashMap<>();
            List<JSONObject> applicantJSONs = JSON.parseArray(item.get("applicant").toString(), JSONObject.class);
            ;
            StringBuilder applicants = new StringBuilder();
            applicantJSONs.forEach(tem -> {
                applicants.append(tem.get("name") + "\r");
            });
            patentListMap.put("name", item.get("name"));
            patentListMap.put("fileName", "D" + (i + 1));
            patentListMap.put("publicDate", item.get("publicDate"));
            patentListMap.put("publicNo", item.get("publicNo"));
            patentListMap.put("SSIM", "");
            patentListMap.put("applicant", applicants);
            patentListMap.put("patentNo", item.get("publicNo"));
            patentListMap.put("abstractStr", item.get("abstractStr"));
            patentListMap.put("compareFileName", "对比文件" + (i + 1));
            patentListMap.put("applicationDate", item.get("applicationDate"));
            patentListMap.put("abstractPath", item.get("abstractPath"));
            patentListMaps.add(patentListMap);
            OtherName.put(item.get("publicNo").toString(), ("D" + (i + 1)));
        }

        //存放对比方案信息的map集合
        List<Map<String, Object>> scenariosMaps = new ArrayList<>();
        //存放所有对比方案所有不重复的rightId
        List<Integer> rightIds = new ArrayList<>();
        for (int i = 0; i < compareScenarios.size(); i++) {
            CompareScenarios item1 = compareScenarios.get(i);
            //获得单个对比方案的
            List<AssoScenarIOS> partScenariosRecords = scenariosRecords.stream().filter(item -> item.getScenariosID().equals(item1.getId())).collect(Collectors.toList());
            List<Integer> featureRecordsIds = partScenariosRecords.stream().map(AssoScenarIOS::getFeatureRecordID).collect(Collectors.toList());
            List<AssoRecordsFeature> assoRecordsFeatures1 =   assoRecordsFeatures.stream().filter(item->featureRecordsIds.contains(item.getId())).collect(Collectors.toList());
            List<Integer> partRecordIds=assoRecordsFeatures1.stream().map(AssoRecordsFeature::getRecordsId).collect(Collectors.toList());
            List<Integer> partFetIds =assoRecordsFeatures1.stream().map(AssoRecordsFeature::getFeatureId).collect(Collectors.toList());
            //获得单个对比方案的权要的所有特征
            List<Features> partFeatures = allFeatures.stream().filter(item -> partFetIds.contains(item.getId())).collect(Collectors.toList());
            List<CompareRecords> records = compareRecords.stream().filter(item -> partRecordIds.contains(item.getId())).collect(Collectors.toList());
            //存放单条对比结果的map
            Map<String, Object> temMap = new HashMap<>();
            if (partFeatures.get(0).getRightType().equals(1)) {
                temMap.put("rightName", "独立" + partFeatures.get(0).getRightName());
            } else {
                temMap.put("rightName", "附属" + partFeatures.get(0).getRightName());
            }
            temMap.put("rightId", item1.getRightId());
            temMap.put("remark",item1.getContrastResult());
            // 从关联数据里获得特征id
            if (!rightIds.contains(item1.getRightId())) {
                rightIds.add(item1.getRightId());
            }
            //存放对比方案每一个特征记录
            List<Map<String, Object>> maps = new ArrayList<>();
            partFeatures.forEach(tem -> {
                Map<String, Object> map = new HashMap<>();
                map.put("featureContent", tem.getContent());
                AssoRecordsFeature assoRecordsFeature = assoRecordsFeatures.stream().filter(item -> item.getFeatureId().equals(tem.getId())).findFirst().orElse(new AssoRecordsFeature());
                map.put("compareResult", assoRecordsFeature.getComResult()!=null?assoRecordsFeature.getComResult():"");
                CompareRecords record = records.stream().filter(item -> item.getId().equals(assoRecordsFeature.getRecordsId())).findFirst().orElse(new CompareRecords());
                map.put("compareContent", record.getContent()!=null?record.getContent():"");
                maps.add(map);
            });
            //方案内容
            temMap.put("fileDetails", maps);
            //新颖性模块
            //获得本方案所有的专利号
            List<String> patentNOs = new ArrayList<>();
            records.forEach(item -> {
                if (!patentNOs.contains(item.getPatentNo())) {
                    patentNOs.add(item.getPatentNo());
                }
            });
            //比较所有专利号和权要所有权要的大小，如果相等则将该专利加入到新颖性列表中

            List<String> noveltyFiles = new ArrayList<>();
            patentNOs.forEach(
                    item -> {
                        List<Integer> temRecordIds = records.stream().filter(tm -> tm.getPatentNo().equals(item)).map(CompareRecords::getId).collect(Collectors.toList());
                        List<Integer> temFIds = assoRecordsFeatures.stream().filter(tm -> temRecordIds.contains(tm.getRecordsId())).map(AssoRecordsFeature::getFeatureId).collect(Collectors.toList());
                        String tmName = item;
                        if (OtherName.containsKey(item)) {
                            tmName = OtherName.get(item).toString();
                        }
                        if (temFIds.size() == partFeatures.size()) {
                            noveltyFiles.add(tmName);
                        }
                    }
            );

            //创造性列表
            List<String> creativeFiles = new ArrayList<>();
            //当前方案所有的特征Id
            partFeatures.forEach(
                    item -> {
                        String tmName = item.getSignPatentNo();
                        if (OtherName.containsKey(tmName)) {
                            tmName = OtherName.get(tmName).toString();
                        }
                        if(!creativeFiles.contains(tmName)){
                            creativeFiles.add(tmName);}
                    }
            );
            List<AssoScenarIOS> andRecords = partScenariosRecords.stream().filter(tm -> tm.getScenariosID().equals(item1.getId())).collect(Collectors.toList());
            if (andRecords.size() != 0) {
                creativeFiles.add("C");
            }
            String creative =creativeFiles.size()==0?"": StringUtils.join(creativeFiles, "+");
            String novelty =noveltyFiles.size()==0?"": StringUtils.join(noveltyFiles, "-");
            //新颖性
            temMap.put("novelty", novelty);
            //创造性
            temMap.put("creative", creative);
            scenariosMaps.add(temMap);

        }
        List<Map<String,Object>> allRightScenarios=new ArrayList<>();
        List<Map<String,Object>> resultMaps =new ArrayList<>();
        rightIds.forEach(tem -> {
            Map<String,Object> map =new HashMap<>();
            Map<String,Object> resultMap =new HashMap<>();
            List<Map<String, Object>> rightScenarios = new ArrayList<>();
            //存放新颖性信息
            List<String> noveList=new ArrayList<>();
            List<String> creaList=new ArrayList<>();
            //存放创造性信息
            for (int t=0;t<scenariosMaps.size();t++){
                Map<String,Object> item =scenariosMaps.get(t);
                if (item.get("rightId").equals(tem)) {
                    item.put("scenariosName","对比组合"+(t+1));
                    rightScenarios.add(item);
                    if(item.get("novelty").toString()!="") {
                        if(!noveList.contains(item.get("novelty").toString())){
                            noveList.add(item.get("novelty").toString());}
                    }
                    if(item.get("creative").toString()!=""){
                        if(!creaList.contains(item.get("creative").toString())){
                            creaList.add(item.get("creative").toString());}
                    }
                }

            }
            map.put("rightScenrios",rightScenarios);
            map.put("rightName",rightScenarios.get(0).get("rightName"));
            String creative =creaList.size()==0?"": StringUtils.join(creaList, "、");
            String novelty =noveList.size()==0?"": StringUtils.join(noveList, "-");
            resultMap.put("rightName",rightScenarios.get(0).get("rightName"));
            resultMap.put("rightNovelty",novelty);
            resultMap.put("rightCreative",creative);
            allRightScenarios.add(map);
            resultMaps.add(resultMap);
        });


        // 为表格的显示绑定行循环
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        // 将bz设置为行循环绑定的数据源的key,即key是bz的value会在模板中的{{bz}}处进行解析
        Configure configure = Configure.builder().bind("patentList", policy).bind("fileDetails", policy).bind("allResults", policy).build();
        Map<String, Object> map = new HashMap<>();

        //1.系统数据
        String date = DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD);
        String[] ds = date.split("-");
        map.put("sys", new SystemMO(ds[0], ds[1], ds[2], "", "reportName"));
        map.put("sss", "saeqeq");
        map.put("patentList", patentListMaps);
        map.put("combinations", allRightScenarios);
        map.put("allResults",resultMaps);
        // 读取模板、数据并渲染
        XWPFTemplate template = XWPFTemplate.compile(filePath, configure).render(map);
//         文件是否已存在，则删除
        File file = new File(outPath);
        if (file.exists()) {
            file.delete();
        }
//         生成word保存在指定目录
        template.writeToFile(outPath);
        template.close();
        //导出成功后，导出报告记录入库
        String url = fileUtils.getDirectory2(directoryName) + fileName;
        PersonnelVO personnelVO =cacheUtils.getLoginUser(loginUtils.getId());
        ReportDocument reportDocument =new ReportDocument();
        reportDocument.setReportId(reportId);
        reportDocument.setFileName(fileName);
        reportDocument.setFilePath(url);
        reportDocument.setPersonId(personnelVO.getId());
        reportDocument.setTemplateId(reportTemplate.getId());
        reportDocument.setTemplateName(reportTemplate.getTemplateName());
        reportDocument.setPersonName(personnelVO.getName());
        reportDocument.insert();
        return Response.success();
    }

    }


