package cn.cslg.pas.service;

import cn.cslg.pas.common.core.base.Constants;
import cn.cslg.pas.common.model.dto.report.*;
import cn.cslg.pas.common.model.vo.ReportVO;
import cn.cslg.pas.common.utils.*;
import cn.cslg.pas.domain.*;
import cn.cslg.pas.mapper.ReportMapper;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 报告表 服务实现类
 * </p>
 *
 * @author 王岩
 * @since 2021-12-27
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ReportService extends ServiceImpl<ReportMapper, Report> {

    private final PatentService patentService;
    private final ReportTemplateService reportTemplateService;
    private final ReportTemplateLabelService reportTemplateLabelService;
    private final ProjectService projectService;
    private final PatentAffairService patentAffairService;
    private final PatentApplicantService patentApplicantService;
    private final PatentApplicantLinkService patentApplicantLinkService;
    private final PatentInventorService patentInventorService;
    private final PatentInventorLinkService patentInventorLinkService;
    private final PatentLicensorService patentLicensorService;
    private final SystemDictService systemDictService;
    private final PatentAgencyService patentAgencyService;
    private final PatentAgentService patentAgentService;
    private final FileUtils fileUtils;
    private final ProjectFolderPatentLinkService projectFolderPatentLinkService;
    private final ProjectFieldPatentLinkService projectFieldPatentLinkService;
    private final PatentLabelService patentLabelService;
    private final PatentClassNumberLinkService patentClassNumberLinkService;
    private final PatentInstructionTextService patentInstructionTextService;
    private final PatentRightService patentRightService;
    private final PatentSimpleFamilyLinkService patentSimpleFamilyLinkService;

    public List<Report> getReportList(ReportVO params) {
        LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(params.getPatentKey())) {
            queryWrapper.eq(Report::getPatentKey, params.getPatentKey());
        }
        queryWrapper.orderByDesc(Report::getCreateTime);
        List<Report> dataList = this.list(queryWrapper);
        dataList.forEach(item -> item.setCfg(null));
        return dataList;
    }

    public Report getReportById(Integer id) {
        Report report = this.getById(id);
        report.setCfg(null);
        return report;
    }

    public List<Report> getReportByIds(List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Report::getId, ids);
        return this.list(queryWrapper);
    }

    public List<Integer> getReportIdsLikeName(String name) {
        LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Report::getName, name);
        List<Integer> ids = this.list(queryWrapper).stream().map(Report::getId).collect(Collectors.toList());
        if (ids.size() == 0) {
            ids.add(0);
        }
        return ids;
    }

    @Async
    public void add(Report report) {
        try {
            LoopRowTableRenderPolicy hackLoopSameLineTableRenderPolicy = new LoopRowTableRenderPolicy(true);
            Configure config = Configure.builder()
                    .bind("content", hackLoopSameLineTableRenderPolicy)//权利要求行循环
                    .bind("selfcontent", hackLoopSameLineTableRenderPolicy)//独权合并行
                    .bind("patents", hackLoopSameLineTableRenderPolicy)
                    .useSpringEL()//使用spring表达式
                    .setValidErrorHandler(new Configure.AbortHandler())
                    .build();
            //获取模板
            ReportTemplate reportTemplate = reportTemplateService.getTemplateById(report.getTemplateId());
            XWPFTemplate template = XWPFTemplate.compile(fileUtils.getPath(reportTemplate.getPath()), config);
            //数据整合
            Map<String, Object> map = this.assemData(report);
            //渲染数据
            template.render(map);
            //导出
            String fileName = IdUtil.simpleUUID() + ".docx";
            String directoryName = fileUtils.createDirectory();
            String savePath = fileUtils.getSavePath(directoryName);
            template.writeAndClose(new FileOutputStream(savePath + fileName));
            String url = fileUtils.getDirectory2(directoryName) + fileName;
            //保存文件地址到报表表
            report.setPath(url);
            report.setStatus(1);
            report.updateById();
            this.getReturnData(String.valueOf(report.getCreateBy()));
        } catch (Exception e) {
            e.printStackTrace();
            report.setStatus(2);
            report.updateById();
            this.getReturnData(String.valueOf(report.getCreateBy()));
        }
    }

    private void getReturnData(String userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        WebSocketServer.sendInfo(Response.success(map), userId);
    }

    //组建数据
    private Map<String, Object> assemData(Report report) {
        //数据整合
        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], "", report.getName()));
        //2专题库信息
        ThematicMO thematicMO = this.formatThematic(report);
        map.put("thematic", thematicMO);
        //3 分类，专利数据
        List<ClassifyMO> classifyMOS = this.formatClassify(report);
        if (classifyMOS.size() > 0) {
            for (ClassifyMO m : classifyMOS) {
                map.put(m.getKey(), m);
            }
        }

        //4.所有专利
        List<PatentMO> patentList = new ArrayList<>();
        List<Patent> patents = patentService.getPatentListByIds(report.getPatentIds());
        ParameModel parameModel = getParame(report.getPatentIds());
        if (patents != null && patents.size() > 0) {
            for (Patent p : patents) {
                patentList.add(this.formatPatentMO(p, parameModel.getAllApplicant(), parameModel.getAllAffair(), parameModel.getAllInventor(), parameModel.getAllInventorRelation(), parameModel.getAllLicensorRelation()));
            }
        }
        map.put("patents", patentList);
        return map;
    }

    private List<ClassifyMO> formatClassify(Report report) {
        List<ClassifyMO> list = new ArrayList<>();
        //获取分类
        List<ReportTemplateLabel> reportTemplateLabelList = reportTemplateLabelService.getTemplateLabelByTemplateIds(Collections.singletonList(report.getTemplateId()));
        List<ReportPatentLabelDTO> reportLabelCfg = JsonUtils.jsonToList(report.getCfg(), ReportPatentLabelDTO.class);
        ClassifyMO classifyMO;
        for (ReportTemplateLabel label : reportTemplateLabelList) {
            classifyMO = new ClassifyMO();
            classifyMO.setKey(label.getLabel().replace("-", ""));
            classifyMO.setClassify_name(label.getName());
            //此分类的配置的专利
            ReportPatentLabelDTO lscfg = null;
            if (reportLabelCfg != null) {
                lscfg = reportLabelCfg.stream().filter(m -> m.getLabel().equals(label.getId())).findFirst().orElse(null);
            }
            if (lscfg == null || lscfg.getId() == null || lscfg.getId().size() == 0) {
                continue;
            }
            List<Integer> patentIDS = lscfg.getId();
            List<Patent> patentList = patentService.getPatentListByIds(patentIDS);
            if (patentList == null || patentList.size() == 0) {
                continue;
            }
            ParameModel parameModel = this.getParame(patentIDS);
            List<PatentMO> arrys = new ArrayList<>();
            for (Patent p : patentList) {
                arrys.add(this.formatPatentMO(p, parameModel.getAllApplicant(), parameModel.getAllAffair(), parameModel.getAllInventor(), parameModel.getAllInventorRelation(), parameModel.getAllLicensorRelation()));
            }
            classifyMO.setArrys(arrys);
            list.add(classifyMO);
        }
        //补齐其他标记
        if (reportTemplateLabelList.size() != list.size()) {
            for (ReportTemplateLabel lb : reportTemplateLabelList) {
                String lkey = lb.getLabel().replace("-", "");
                long count = list.stream().filter(m -> m.getKey().equalsIgnoreCase(lkey)).count();
                if (count == 0) {
                    classifyMO = new ClassifyMO();
                    classifyMO.setKey(lkey);
                    classifyMO.setClassify_name(lb.getName());
                    classifyMO.setArrys(new ArrayList<>());
                    list.add(classifyMO);
                }
            }
        }
        return list;
    }

    private ParameModel getParame(List<Integer> ids) {
        List<PatentApplicantLink> attrList = patentApplicantLinkService.getApplicantAttributesListByPatentIds(ids);
        List<PatentAffair> affList = patentAffairService.getPatentAffairListByPatentIds(ids);
        List<PatentInventor> inventorList = patentInventorService.getPatentInventorByPatentIds(ids);
        List<PatentInventorLink> inventorRelationList = patentInventorLinkService.getPatentInventorLinkByPatentIds(ids);
        List<PatentLicensor> licensorList = patentLicensorService.getPatentLicensorByPatentIds(ids);
        ParameModel m = new ParameModel();
        m.setAllAffair(affList);
        m.setAllApplicant(attrList);
        m.setAllInventor(inventorList);
        m.setAllInventorRelation(inventorRelationList);
        m.setAllLicensorRelation(licensorList);
        return m;
    }

    private ThematicMO formatThematic(Report report) {
        Project project = projectService.getProjectById(report.getProjectId());
        ThematicMO thematicMO = new ThematicMO();
        thematicMO.setTname(FormatUtil.toString(project.getName()));//专题库名称
        thematicMO.setTechnical_theme(FormatUtil.toString(project.getTechnicalTheme()));//技术主题
        thematicMO.setInnerfile(FormatUtil.toString(project.getInnerFile()));//内部案卷
        thematicMO.setUpdate_cycle(project.getUpdate().equals(1) ? "是" : "否");//是否更新
        thematicMO.setTreat_status(FormatUtil.toString(project.getStatus()));//处理状态
        thematicMO.setContract_no(FormatUtil.toString(project.getContractNo()));//合同号
        thematicMO.setCase_data(FormatUtil.toString(project.getCaseDate()));//委案日
        thematicMO.setTupdate_time(FormatUtil.toString(project.getUpdateTime()));//更新周期
        thematicMO.setTremark(FormatUtil.toString(project.getRemark()));//备注
        thematicMO.setTcreate_time(DateUtils.formatDate(project.getCreateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));//TODO:创建时间
        thematicMO.setSurvey_type(FormatUtil.toString(project.getTypeName()));//调查类型
        thematicMO.setScenario(FormatUtil.toString(project.getScenarioName()));//委托场景
        thematicMO.setClient(FormatUtil.toString(project.getClientName()));//委托方
        return thematicMO;
    }

    public PatentMO formatPatentMO(Patent p,
                                   List<PatentApplicantLink> allApplicant,
                                   List<PatentAffair> allAffair,
                                   List<PatentInventor> allInventor,
                                   List<PatentInventorLink> allInventorRelation,
                                   List<PatentLicensor> allLicensorRelation
    ) {
        PatentMO patentMO = new PatentMO();
        patentMO.setPname(FormatUtil.toString(p.getName()));//专利名称(标题)
        patentMO.setTranslate_name(FormatUtil.toString(p.getNameOut()));//专利名称(标题)（译）
        patentMO.setPatentno(FormatUtil.toString(p.getPatentNo()));//专利号
        patentMO.setAbstracts(FormatUtil.toString(p.getAbstractStr()));//摘要
        patentMO.setAbstractout(FormatUtil.toString(p.getAbstractOut()));//摘要（译）
        patentMO.setApplicationno(FormatUtil.toString(p.getApplicationNo()));//申请号
        patentMO.setAppdate(DateUtils.formatDate(p.getApplicationDate(), DateUtils.YYYY_MM_DD));//申请日
        patentMO.setPublicno(FormatUtil.toString(p.getPublicNo()));//公开号
        patentMO.setPublicdate(DateUtils.formatDate(p.getPublicDate(), DateUtils.YYYY_MM_DD));//:公开日
        patentMO.setFpublicdate(DateUtils.formatDate(p.getFirstPublicDate(), DateUtils.YYYY_MM_DD));//:首次公开日
        patentMO.setPublictono(FormatUtil.toString(p.getPublicAccreditNo()));//公开授权号
        patentMO.setPublictodate(DateUtils.formatDate(p.getPublicAccreditDate(), DateUtils.YYYY_MM_DD));//:公开授权日
        patentMO.setBureau(FormatUtil.toString(p.getBureau()));//受理局
        List<PatentClassNumberLink> patentClassNumberLinkList = patentClassNumberLinkService.getPatentClassNumberLinkByPatentIds(Collections.singletonList(p.getId()));
        patentMO.setIntclassno(FormatUtil.toString(StringUtils.join(patentClassNumberLinkList.stream().filter(item -> item.getType().equals(Constants.PATENT_CLASS_NUMBER_IPC)).map(PatentClassNumberLink::getCode).collect(Collectors.toList()), "\n")));//IPC分类号
        patentMO.setIntclasscpcno(FormatUtil.toString(StringUtils.join(patentClassNumberLinkList.stream().filter(item -> item.getType().equals(Constants.PATENT_CLASS_NUMBER_CPC)).map(PatentClassNumberLink::getCode).collect(Collectors.toList()), "\n")));//CPC分类号
        patentMO.setIntclassupcno(FormatUtil.toString(StringUtils.join(patentClassNumberLinkList.stream().filter(item -> item.getType().equals(Constants.PATENT_CLASS_NUMBER_UPC)).map(PatentClassNumberLink::getCode).collect(Collectors.toList()), "\n")));//UPC分类号
        patentMO.setIntclasslocno(FormatUtil.toString(StringUtils.join(patentClassNumberLinkList.stream().filter(item -> item.getType().equals(Constants.PATENT_CLASS_NUMBER_LOC)).map(PatentClassNumberLink::getCode).collect(Collectors.toList()), "\n")));//LOC分类号
        patentMO.setPstatus(systemDictService.getSystemDictLabelByTypeAndValue(Constants.PATENT_SIMPLE_STATUS, p.getSimpleStatus()));//状态
        patentMO.setPtype(systemDictService.getSystemDictLabelByTypeAndValue(Constants.PATENT_TYPE, p.getType()));//类型
        patentMO.setCode(FormatUtil.toString(p.getCode()));//文献代码
        PatentInstructionText patentInstructionText = patentInstructionTextService.getPatentInstructionTextByPatentId(p.getId());
        if (patentInstructionText != null) {
            patentMO.setManual(FormatUtil.toString(patentInstructionText.getManual()));//说明书
            patentMO.setManualout(FormatUtil.toString(patentInstructionText.getManualOut()));//说明书(译)
        }
        patentMO.setPage(FormatUtil.toString(p.getDocPage()));//文献页数
        patentMO.setInventornum(FormatUtil.toString(p.getInventorNum()));//发明人数量
        patentMO.setNum2(FormatUtil.toString(p.getSelfRightContentNum()));//权利要求数量
        patentMO.setNum3(FormatUtil.toString(p.getSelfRightNum()));//独立权利要求数量 这个字段是没有数据的
        List<PatentRight> patentRightList = patentRightService.getPatentRightByPatentId(p.getId());
        List<PatentMO.ContentMO2> cs = formatContent(patentRightList.stream().filter(item -> item.getType().equals(1)).collect(Collectors.toList()));
        patentMO.setSelfcontent(cs);//独立权利要求
        patentMO.setPriorityno(FormatUtil.toString(p.getPriorityNo()));//优先权号
        patentMO.setPrioritycountry(FormatUtil.toString(p.getPriorityCountry()));//优先权国家
        patentMO.setPrioritydate(DateUtils.formatDate(p.getPriorityDate(), DateUtils.YYYY_MM_DD));
        patentMO.setSimplefamilynum(FormatUtil.toString(p.getSimpleFamilyNum()));//：简单同族数量
        patentMO.setInpadocfamilynum(FormatUtil.toString(p.getInpadocFamilyNum()));//：Inpadoc同族数量
        patentMO.setQuoteno(FormatUtil.toString(p.getQuoteNum()));//：引用专利数量
        patentMO.setQuotedno(FormatUtil.toString(p.getQuotedNum()));//：被引用数量
        patentMO.setQuotedno3(FormatUtil.toString(p.getQuotedNum3()));//：三年内被引用数量
        patentMO.setQuotedno5(FormatUtil.toString(p.getQuotedNum5()));//：五年内被引用数量
        List<PatentSimpleFamilyLink> patentSimpleFamilyLinkList = patentSimpleFamilyLinkService.getPatentSimpleFamilyLinkByFamilyIds(Arrays.asList(p.getSimpleFamily(), p.getInpadocFamily()));
        patentMO.setSfamily(FormatUtil.toString(StringUtils.join(patentSimpleFamilyLinkList.stream().filter(item -> item.getFamilyId().equals(p.getSimpleFamily())).map(PatentSimpleFamilyLink::getPatentNo).collect(Collectors.toList()), " | ")));//简单同族
        patentMO.setIfamily(FormatUtil.toString(StringUtils.join(patentSimpleFamilyLinkList.stream().filter(item -> item.getFamilyId().equals(p.getInpadocFamily())).map(PatentSimpleFamilyLink::getPatentNo).collect(Collectors.toList()), " | ")));//i同族
        if (StringUtils.isNotEmpty(p.getAgencyId())) {
            PatentAgency a = patentAgencyService.getById(p.getAgencyId());
            if (a != null) {
                patentMO.setAgency(a.getName());//:代理机构
            }
        }
        List<PatentAgent> b = patentAgentService.getPatentAgentByPatentId(p.getId());
        if (b != null && b.size() != 0) {
            patentMO.setAgent(StringUtils.join(b.stream().map(PatentAgent::getName).collect(Collectors.toList()), ","));
        }
        patentMO.setWonational(FormatUtil.toString(p.getWo()));//WO国家阶段
        patentMO.setExaminer(p.getExaminer());//审查员
        patentMO.setAssexaminer(p.getAidExaminer());//助理审查员
        patentMO.setQuote(FormatUtil.toString(p.getQuote()));//引用专利
        patentMO.setQuoted(FormatUtil.toString(p.getQuoted()));//被引用专利
        patentMO.setNonpatentquote(FormatUtil.toString(p.getNotPatentQuote()));//非专利引用文献
        if (StringUtils.isNotEmpty(p.getAbstractPath())) {
            PictureRenderData pic = new PictureRenderData(100, 100, fileUtils.getPath(p.getAbstractPath()));
            patentMO.setAbstract_path(pic);//摘要附图
        }
        patentMO.setEpcountry(FormatUtil.toString(p.getEpStatus()));//指定国状态
        //1是权利人  2是申请人
        List<PatentApplicantLink> applyList = allApplicant.stream().filter(m -> m.getPatentId().equals(p.getId()) && m.getType().equals(2)).collect(Collectors.toList());
        if (applyList.size() > 0) {
            //申请人 当前
            List<Integer> currAppIDS = applyList.stream().map(PatentApplicantLink::getApplicantId).collect(Collectors.toList());
            List<PatentApplicant> alist = patentApplicantService.getPatentApplicantByIds(currAppIDS);
            List<String> names = alist.stream().map(PatentApplicant::getName).collect(Collectors.toList());
            patentMO.setApplicant_names_current(FormatUtil.toString(StringUtils.join(names, ",")));
            List<PatentApplyMO> aplist = new ArrayList<>();
            PatentApplyMO mo;
            for (PatentApplicant a : alist) {
                mo = new PatentApplyMO();
                mo.setName(a.getName());
                mo.setBname(a.getShortName());
                mo.setRemark(a.getRemark());
                aplist.add(mo);
            }
            PatentApplicantLink firstApplicantLink = applyList.stream().filter(item -> item.getOrder().equals(0)).findFirst().orElse(null);
            if (firstApplicantLink != null) {
                PatentApplicant firstApplicant = alist.stream().filter(item -> item.getId().equals(firstApplicantLink.getApplicantId())).findFirst().orElse(null);
                if (firstApplicant != null) {
                    if (firstApplicant.getName() == null || firstApplicant.getName().equals("")) {
                        patentMO.setFirstapplicant("无");
                    } else {
                        patentMO.setFirstapplicant(FormatUtil.toString(firstApplicant.getName()));
                    }
                }
            }
            patentMO.setApplicant_list_current(aplist);
            //申请人 标准
            List<String> names2 = alist.stream().map(PatentApplicant::getShortName).collect(Collectors.toList());
            patentMO.setApplicant_names_standard(FormatUtil.toString(StringUtils.join(names2, ",")));//赋值
            List<PatentApplyMO> aplist2 = new ArrayList<>();
            PatentApplyMO mo2;
            for (PatentApplicant a : alist) {
                mo2 = new PatentApplyMO();
                mo2.setName(a.getName());
                mo2.setBname(a.getShortName());
                mo2.setRemark(a.getRemark());
                aplist2.add(mo2);
            }
            patentMO.setApplicant_list_standard(aplist2);
        }
        //权利人
        List<PatentApplicantLink> obligeeList = allApplicant.stream().filter(m -> m.getPatentId().equals(p.getId()) && m.getType().equals(1)).collect(Collectors.toList());
        if (obligeeList.size() > 0) {
            //权利人 当前
            List<Integer> currAppIDS = obligeeList.stream().map(PatentApplicantLink::getApplicantId).collect(Collectors.toList());
            List<PatentApplicant> alist = patentApplicantService.getPatentApplicantByIds(currAppIDS);
            List<String> names = alist.stream().map(PatentApplicant::getName).collect(Collectors.toList());
            patentMO.setObligee_names_current(FormatUtil.toString(StringUtils.join(names, ",")));//赋值
            List<PatentApplyMO> aplist = new ArrayList<>();
            PatentApplyMO mo;
            for (PatentApplicant a : alist) {
                mo = new PatentApplyMO();
                mo.setName(a.getName());
                mo.setBname(a.getShortName());
                mo.setRemark(a.getRemark());
                aplist.add(mo);
            }
            patentMO.setObligee_list_current(aplist);
            //权利人 标准
            List<String> names2 = alist.stream().map(PatentApplicant::getName).collect(Collectors.toList());
            patentMO.setObligee_names_standard(FormatUtil.toString(StringUtils.join(names2, ",")));//赋值
            List<PatentApplyMO> aplist2 = new ArrayList<>();
            PatentApplyMO mo2;
            for (PatentApplicant a : alist) {
                mo2 = new PatentApplyMO();
                mo2.setName(a.getName());
                mo2.setBname(a.getShortName());
                mo2.setRemark(a.getRemark());
                aplist2.add(mo2);
            }
            patentMO.setObligee_list_standard(aplist2);
        }

        //法律事务
        List<PatentLawMO> affairMoList = new ArrayList<>();
        List<PatentAffair> affairList = allAffair.stream().filter(m -> m.getPatentId().equals(p.getId())).collect(Collectors.toList());
        if (affairList.size() > 0) {
            PatentLawMO m;
            for (PatentAffair a : affairList) {
                m = new PatentLawMO();
                m.setLaw_content(a.getContent());
                m.setLaw_datetime(DateUtils.formatDate(a.getDateTime(), DateUtils.YYYY_MM_DD));
                m.setLaw_remark(a.getRemark());
                m.setLaw_simplestatus(systemDictService.getSystemDictLabelByTypeAndValue(Constants.PATENT_SIMPLE_STATUS, a.getSimpleStatus()));
                m.setLaw_status(systemDictService.getSystemDictLabelByTypeAndValue(Constants.PATENT_STATUS, a.getStatus()));
                affairMoList.add(m);
            }
        }
        patentMO.setLawArrys(affairMoList);//法律事务

        //发明人
        List<InventorMO> inventorMoList = new ArrayList<>();
        List<PatentInventorLink> inventorReloationList = allInventorRelation.stream().filter(m -> m.getPatentId().equals(p.getId())).collect(Collectors.toList());
        if (inventorReloationList.size() > 0) {
            List<Integer> ids = inventorReloationList.stream().map(PatentInventorLink::getInventorId).collect(Collectors.toList());
            List<PatentInventor> inventorList = allInventor.stream().filter(m -> ids.contains(m.getId())).collect(Collectors.toList());
            List<String> inventorNames = inventorList.stream().map(PatentInventor::getName).collect(Collectors.toList());
            patentMO.setInventor_names(FormatUtil.toString(StringUtils.join(inventorNames, ",")));//赋值
            InventorMO m;
            for (PatentInventor a : inventorList) {
                m = new InventorMO();
                m.setName(a.getName());
                inventorMoList.add(m);
            }
        }
        patentMO.setInventor_list(inventorMoList);//发明人

        List<PermitMO> permitMoList = new ArrayList<>(); //许可人
        List<PermitMO> licentorMoList = new ArrayList<>();//被许可
        List<PatentLicensor> permitRelation = allLicensorRelation.stream().filter(m -> m.getPatentId().equals(p.getId())).collect(Collectors.toList());
        permitRelation.forEach(item -> {
            PermitMO m1 = new PermitMO();
            m1.setName(item.getLicensor());
            PermitMO m2 = new PermitMO();
            m2.setName(item.getLicensee());
            m1.setPermittype(item.getType());
            m2.setPermittype(item.getType());
            permitMoList.add(m1);
            licentorMoList.add(m2);
        });
        patentMO.setPermit_list(permitMoList);//许可
        patentMO.setLicensed_list(licentorMoList);//被许可
        return patentMO;
    }


    //独立权利要求格式化
    private List<PatentMO.ContentMO2> formatContent(List<PatentRight> content) {
        if (content == null || content.size() == 0) {
            return new ArrayList<>();
        }
        List<PatentMO.ContentMO> list = new ArrayList<>();
        for (int i = 0; i < content.size(); i++) {
            PatentMO.ContentMO m = new PatentMO.ContentMO();
            m.setTitle("独权" + (i + 1));
            m.setItem(Collections.singletonList(content.get(i).getContent()));
            m.setOut(Collections.singletonList(content.get(i).getContentOut()));
            list.add(m);
        }
        List<PatentMO.ContentMO2> rlist = new ArrayList<>();
        if (list.size() > 0) {
            for (PatentMO.ContentMO cm : list) {
                StringBuilder sb = new StringBuilder();
                StringBuilder sbb = new StringBuilder();
                for (String s : cm.getItem()) {
                    sb.append(s);
                }
                for (String s : cm.getOut()) {
                    sbb.append(s);
                }
                String dcode = sb.toString().replace("\n", "").replace("；", ";");
                String code;
                if (sbb.toString().contains("。")) {
                    code = sbb.toString().replace("\n", "").replace("。", ";");
                } else {
                    code = sbb.toString().replace("\n", "").replace("；", ";");
                }
                List<String> sarry = Arrays.asList(dcode.split(";"));
                List<String> out = Arrays.asList(code.split(";"));
                for (int i = 0, sarrySize = sarry.size(); i < sarrySize; i++) {
                    String s = sarry.get(i);
                    if (sarrySize - 1 == i) {
                        if (out.size() > i) {
                            rlist.add(new PatentMO.ContentMO2(cm.getTitle(), s + ".", out.get(i)));
                        } else {
                            rlist.add(new PatentMO.ContentMO2(cm.getTitle(), s + ".", ""));
                        }
                    } else {
                        if (out.size() > i) {
                            rlist.add(new PatentMO.ContentMO2(cm.getTitle(), s + ";", out.get(i)));
                        } else {
                            rlist.add(new PatentMO.ContentMO2(cm.getTitle(), s + ";", ""));
                        }
                    }

                }
            }
        }
        return rlist;
    }

    public List<ReportPatentDTO> getPatentList(List<Integer> patentIds, Integer projectId) {
        List<ReportPatentDTO> dataList = new ArrayList<>();
        List<Patent> patentList = patentService.getPatentListByIds(patentIds);
        List<PatentApplicant> patentApplicantList = patentApplicantService.getPatentApplicantByPatentIds(patentIds);
        List<ProjectFolderPatentLink> projectFolderPatentLinkList = projectFolderPatentLinkService.getProjectFolderLinkListByProjectIdAndPatentIds(projectId, patentIds);
        List<ProjectFieldPatentLink> projectFieldPatentLinkList = projectFieldPatentLinkService.getProjectPatentLinkByPatentIdsAndProjectId(patentIds, projectId);
        List<PatentLabel> patentLabelList = patentLabelService.getPatentLabelByPatentIdsAndProjectId(patentIds, projectId);
        patentList.forEach(item -> {
            List<PatentApplicant> patentApplicants = patentApplicantList.stream().filter(patentApplicant -> patentApplicant.getPatentId().equals(item.getId())).collect(Collectors.toList());
            List<ProjectFieldPatentLink> projectFieldPatentLinks = projectFieldPatentLinkList.stream().filter(projectFieldPatentLink -> projectFieldPatentLink.getPatentId().equals(item.getId())).collect(Collectors.toList());
            ReportPatentDTO patentDTO = new ReportPatentDTO();
            List<ReportPatentDTO.Field> fieldList = new ArrayList<>();
            patentDTO.setName(item.getName());
            patentDTO.setPatentno(item.getPatentNo());
            patentDTO.setApplicationno(item.getApplicationNo());
            patentDTO.setPublicno(item.getPublicNo());
            patentDTO.setId(item.getId());
            patentDTO.setType(item.getType());
            patentDTO.setStatus(item.getSimpleStatus());
            patentDTO.setFolder(projectFolderPatentLinkList.stream().filter(projectFolderPatentLink -> projectFolderPatentLink.getPatentId().equals(item.getId())).map(ProjectFolderPatentLink::getFolderId).distinct().collect(Collectors.toList()));
            patentDTO.setApplicant(patentApplicants.stream().filter(patentApplicant -> patentApplicant.getDataType().equals(2)).map(PatentApplicant::getName).collect(Collectors.toList()));
            patentDTO.setObligee(patentApplicants.stream().filter(patentApplicant -> patentApplicant.getDataType().equals(1)).map(PatentApplicant::getName).collect(Collectors.toList()));
            List<Integer> fieldIds = projectFieldPatentLinks.stream().map(ProjectFieldPatentLink::getFieldId).distinct().collect(Collectors.toList());
            fieldIds.forEach(fieldId -> {
                ReportPatentDTO.Field field = new ReportPatentDTO.Field();
                field.setId(fieldId);
                field.setValue(projectFieldPatentLinks.stream().filter(projectFieldPatentLink -> projectFieldPatentLink.getFieldId().equals(fieldId)).map(ProjectFieldPatentLink::getOptionId).distinct().collect(Collectors.toList()));
                fieldList.add(field);
            });
            patentDTO.setLabel(patentLabelList.stream().filter(patentLabel -> patentLabel.getPatentId().equals(item.getId())).map(PatentLabel::getName).collect(Collectors.toList()));
            patentDTO.setField(fieldList);
            dataList.add(patentDTO);
        });
        return dataList;
    }

    //根据Id删除报告
    public String deleteById(List<Integer> ids) {
        this.deleteById(ids);
        return Response.success();

    }
}
