package com.rongwei.bscommon.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import com.aspose.cells.WorkbookDesigner;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.MailMergeCleanupOptions;
import com.aspose.words.net.System.Data.DataRelation;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataSet;
import com.aspose.words.net.System.Data.DataTable;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rongwei.bscommon.sys.dao.*;
import com.rongwei.bscommon.sys.service.ExportService;
import com.rongwei.bscommon.sys.utils.AsposeWordsUtils;
import com.rongwei.bscommon.sys.utils.QuestionConstants;
import com.rongwei.bscommon.sys.utils.QuestionUtils;
import com.rongwei.bsentity.domin.*;
import com.rongwei.bsentity.vo.Export8DRelevantDataVo;
import com.rongwei.bsentity.vo.HashMapDataTableVo;
import com.rongwei.bsentity.vo.ProblemTrackingAndResolutionWordDataVo;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.service.SysOrganizationService;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.exception.CustomException;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.wfentity.sys.RunTaskDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.rongwei.bscommon.sys.utils.QuestionConstants.StandardizedContent.SUFFIX;
import static com.rongwei.bscommon.sys.utils.QuestionConstants.SysDictType.*;
import static com.rongwei.bscommon.sys.utils.QuestionConstants.YesOrNo.YES;

/**
 * ExportServiceImpl class
 *
 * @author XH
 * @date 2023/03/16
 */
@Service
public class ExportServiceImpl implements ExportService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private ExportSqlDao exportSqlDao;
    @Autowired
    private SrmIssuesListDao srmIssuesListDao;
    @Autowired
    private QuestionCommonSqlDao questionCommonSqlDao;
    @Autowired
    private SrmActionPlanDao srmActionPlanDao;
    @Autowired
    private QQuestionFiveWhyDao qQuestionFiveWhyDao;
    @Autowired
    private SrmFiveWhyDao srmFiveWhyDao;
    @Autowired
    private SysOrganizationService sysOrganizationService;

    private static final Map<String, Function<SrmIssuesListDo, Object>> PROBLEM_TRACKING_AND_RESOLUTION_WORD_MAP = new HashMap<String, Function<SrmIssuesListDo, Object>>() {{
        put("QUESTIONNO", SrmIssuesListDo::getQuestionno);
        put("ISSUESTATUS", SrmIssuesListDo::getIssuestatus);
        put("TRIGGERLEVEL", SrmIssuesListDo::getTriggerlevel);
        put("CREATEUSERNAME", SrmIssuesListDo::getCreateusername);
        put("CREATEDATE", SrmIssuesListDo::getCreatedate);
        put("FAILUREDATE", SrmIssuesListDo::getFailuredate);
        put("FACTORY", SrmIssuesListDo::getFactory);
        put("WORKSHOPORDEPARTMENT", SrmIssuesListDo::getWorkshopordepartment);
        put("WORKSHOPSECTION", SrmIssuesListDo::getWorkshopsection);
        put("FAILUREFREQUENCY", SrmIssuesListDo::getFailurefrequency);
        put("FAULTTYPE", SrmIssuesListDo::getFaulttype);
        put("IMPACTCATEGORY", SrmIssuesListDo::getImpactcategory);
        put("QUESTIONTITLE", SrmIssuesListDo::getQuestiontitle);
        put("INTERIMMEASURES", SrmIssuesListDo::getInterimmeasures);
        put("STANDARDORTARGETCONDITIONORLIFEEXPECTANCY", SrmIssuesListDo::getStandardortargetconditionorlifeexpectancy);
        put("STOPMINUTES", SrmIssuesListDo::getStopminutes);
        put("DISQUALIFICATION", SrmIssuesListDo::getDisqualification);
        put("AMOUNTOFDAMAGES", SrmIssuesListDo::getAmountofdamages);
        put("DEPPSRESPERSON", SrmIssuesListDo::getDeppsresperson);
        put("LEADER", SrmIssuesListDo::getLeader);
        put("spa", SrmIssuesListDo::getSpa);
        put("TEAMMEMBERS", SrmIssuesListDo::getTeammembers);
        put("FOLLOWUPDAYS", SrmIssuesListDo::getFollowupdays);
    }};
    // 日期
    public static final List<String> DATE_KEY = new ArrayList<String>() {{
        add("CREATEDATE");
        add("FAILUREDATE");
    }};
    // 组织机构
    public static final List<String> ORG_KEY = new ArrayList<String>() {{
        add("WORKSHOPORDEPARTMENT");
        add("WORKSHOPSECTION");
    }};
    // 数据字典
    public static final Map<String, String> DICT_KEY = new HashMap<String, String>() {{
        put("STANDARDORTARGETCONDITIONORLIFEEXPECTANCY", YES_OR_NO);
        put("ISSUESTATUS", PROBLEM_STATUS);
        put("TRIGGERLEVEL", ISSUE_TYPE);
        put("FAILUREFREQUENCY", FERQUENCY);
        put("FAULTTYPE", FAULT_TYPE);
        put("IMPACTCATEGORY", IMPACTCATEGORY);
        put("FOLLOWUPDAYS", TRACKDAY);
    }};

    /**
     * 导出8D问题EXCEL
     *
     * @param id
     */
    @Override
    public void export8dExcel(String id, HttpServletResponse response) {
        log.info("开始根据：{}导出8D问题解决", id);
        if (StringUtils.isBlank(id)) {
            log.error("参数异常,ID为空");
            throw new CustomException("参数异常");
        }
        List<Export8DRelevantDataVo> export8dRelevantData = exportSqlDao.getExport8dRelevantData(new ArrayList<String>() {{
            add(id);
        }});
        if (export8dRelevantData.isEmpty()) {
            log.error("无法通过ID：{},获取到数据", id);
            throw new CustomException("无法获取到对应的8D问题");
        }
        AsposeWordsUtils.getExcelLicense();
        // 待导入的数据
        try {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode("供应商考核记录.xls", "UTF-8"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            ClassPathResource classPathResource = new ClassPathResource("template/8Dtemplate.xlsx");
            Workbook wb = new Workbook(classPathResource.getInputStream());
            WorkbookDesigner designer = orgExport8DExcelData(export8dRelevantData.get(0), wb);
            designer.process();
            wb.save(response.getOutputStream(), SaveFormat.XLSX);
            wb.dispose();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("8D问题导出异常");
        }
    }

    /**
     * 导出问题跟踪解决
     *
     * @param id
     * @param response
     */
    @Override
    public void exportProblemTrackingAndResolutionWord(String id, HttpServletResponse response) {
        boolean wordLicense = AsposeWordsUtils.getWordLicense();
        ClassPathResource classPathResource = new ClassPathResource("template/ProblemTrackingAndResolution.docx");
        try {
            ProblemTrackingAndResolutionWordDataVo problemTrackingAndResolutionWordDataVo = orgProblemTrackingAndResolutionWordData(id);
            Document doc = new Document(classPathResource.getInputStream());
            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);
            // 循环处理
            problemTrackingAndResolutionWordDataVo.getListData().forEach(info -> {
                try {
                    doc.getMailMerge().executeWithRegions(info);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new CustomException("PSL问题导出异常");
                }
            });
            // 单独数据合并
            doc.getMailMerge().execute(problemTrackingAndResolutionWordDataVo.getSingleDataMap().keySet().stream().toArray(String[]::new),
                    problemTrackingAndResolutionWordDataVo.getSingleDataMap().values()
                            .stream().map((Function<Object, String>) Object::toString).toArray(String[]::new));
            // 图片插入
            addPicture(problemTrackingAndResolutionWordDataVo.getPictures(), doc);
            if (problemTrackingAndResolutionWordDataVo.getWhyInfo() != null && problemTrackingAndResolutionWordDataVo.getWhyDesc() != null) {
                // 嵌套循环处理
                DataSet whySet = new DataSet();
                whySet.getTables().add(problemTrackingAndResolutionWordDataVo.getWhyInfo());
                whySet.getTables().add(problemTrackingAndResolutionWordDataVo.getWhyDesc());
                String[] contCols = {"whyName"};
                String[] lstCols = {"whyName"};
                whySet.getRelations().add(new DataRelation("UserInfo", problemTrackingAndResolutionWordDataVo.getWhyInfo(),
                        problemTrackingAndResolutionWordDataVo.getWhyDesc(), contCols, lstCols));
                doc.getMailMerge().executeWithRegions(whySet);
            }
            doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS);
            doc.getMailMerge().deleteFields();
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=ProblemTrackingAndResolution.docx");
            doc.save(response.getOutputStream(), com.aspose.words.SaveFormat.DOCX);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("PSL问题导出异常");
        }
    }

    /**
     * 像word模板中插入数据
     *
     * @param pictures
     * @param doc
     * @return
     */
    private void addPicture(List<String> pictures, Document doc) throws Exception {
        DocumentBuilder builder = new DocumentBuilder(doc);
        //定位到指定位置
        builder.moveToBookmark("pictures");
        pictures.forEach(url -> {
            try {
                builder.insertImage(url);
            } catch (Exception e) {
                log.error("图片url:{}不存在", url);
            }
            try {
                builder.writeln();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 组织word导出需要的数据
     *
     * @param id
     * @return
     */
    private ProblemTrackingAndResolutionWordDataVo orgProblemTrackingAndResolutionWordData(String id) {
        Map<String, String> wordMap = new HashMap<>();

        ProblemTrackingAndResolutionWordDataVo vo = new ProblemTrackingAndResolutionWordDataVo();
        List<DataTable> listData = new ArrayList<>();
        if (StringUtils.isBlank(id)) {
            return vo;
        }
        List<SysDictDo> sysDictDoList = questionCommonSqlDao.getDictValueByDictType(DICT_KEY.values().stream().collect(Collectors.toList()));
        // 主表信息
        SrmIssuesListDo srmIssuesListDo = srmIssuesListDao.selectById(id);
        //根据主表的工厂ID重新赋值工厂名称
        if(ObjectUtil.isNotEmpty(srmIssuesListDo.getFactory())){
            //查询工厂ID对应的中文名称
            SysOrganizationDo organizationDo = sysOrganizationService.getById(srmIssuesListDo.getFactory());
            srmIssuesListDo.setFactory(organizationDo.getFullname());
        }
        List<SysOrganizationDo> allOrg = questionCommonSqlDao.getAllOrg();
        PROBLEM_TRACKING_AND_RESOLUTION_WORD_MAP.forEach((k, v) -> {
            Object apply = v.apply(srmIssuesListDo);
            if (apply == null) {
                wordMap.put(k, "");
            } else if (DATE_KEY.contains(k)) {
                wordMap.put(k, QuestionUtils.dateConvertStr((Date) apply));
            } else if (DICT_KEY.containsKey(k)) {
                wordMap.put(k, QuestionUtils.getDictValueByDictName(apply.toString(), DICT_KEY.get(k), sysDictDoList));
            } else if (ORG_KEY.contains(k)) {
                wordMap.put(k, orgIdConvertToOrgName(apply.toString(),allOrg));
            } else {
                wordMap.put(k, apply.toString());
            }
        });
        vo.setSingleDataMap(wordMap);
        // 获取费用列表
        DataTable dataTable;
        Map<String, Object> mapData;

        /*****************************处理行动计划*************************************/
        List<SrmActionPlanDo> planDoList = srmActionPlanDao.selectByMap(new HashMap<String, Object>() {{
            put("MAINID", id);
        }});
        // 获取费用列表
        DataTable planDataTable = new DataTable("plan");
        planDataTable.getColumns().add("serialnumber");
        planDataTable.getColumns().add("TASKTITLE");
        planDataTable.getColumns().add("CREATETASKSPA");
        planDataTable.getColumns().add("TARGETCOMPLETIONDATE");
        planDataTable.getColumns().add("COMDATE");
        for (int i = 0; i < planDoList.size(); i++) {
            DataRow dataRow = planDataTable.newRow();
            dataRow.set("serialnumber", i + 1);
            dataRow.set("TASKTITLE", planDoList.get(i).getTasktitle());
            dataRow.set("CREATETASKSPA", planDoList.get(i).getCreatetaskspa());
            dataRow.set("TARGETCOMPLETIONDATE", QuestionUtils.dateConvertStr(planDoList.get(i).getTargetcompletiondate()));
            dataRow.set("COMDATE", QuestionUtils.dateConvertStr(planDoList.get(i).getComdate()));
            planDataTable.getRows().add(dataRow);
        }
        listData.add(planDataTable);
        /*****************************处理5WHY原因分析*************************************/
        List<QQuestionFiveWhyDo> fiveWhyDoList = qQuestionFiveWhyDao.selectByMap(new HashMap<String, Object>() {{
            put("QID", id);
        }});
        if (!fiveWhyDoList.isEmpty()) {
            List<QQuestionFiveWhyDo> sortFiveWhyDoList = fiveWhyDoList.stream().sorted(Comparator.comparing(QQuestionFiveWhyDo::getCode, Comparator.nullsFirst(Comparator.naturalOrder())))
                    .collect(Collectors.toList());
            List<SrmFiveWhyDo> srmFiveWhyDos = srmFiveWhyDao.selectList(new LambdaQueryWrapper<SrmFiveWhyDo>()
                    .in(SrmFiveWhyDo::getMainid, fiveWhyDoList.stream().map(QQuestionFiveWhyDo::getId).collect(Collectors.toList()))
                    .orderByAsc(BaseDo::getModifydate));
            DataTable userTb = new DataTable("whyList"); //用户
            userTb.getColumns().add("whyName"); //节点名称
            DataTable infoTb = new DataTable("whyDesc"); //用户信息
            infoTb.getColumns().add("whyName"); //名称
            infoTb.getColumns().add("whyDesc"); // 描述
            for (int i = 0; i < sortFiveWhyDoList.size(); i++) {
                DataRow dataRow = userTb.newRow();
                dataRow.set("whyName", sortFiveWhyDoList.get(i).getName());
                userTb.getRows().add(dataRow);
                int finalI = i;
                List<SrmFiveWhyDo> whyList = srmFiveWhyDos.stream().filter(info -> sortFiveWhyDoList.get(finalI).getId().equals(info.getMainid())).collect(Collectors.toList());
                for (int j = 0; j < whyList.size(); j++) {
                    DataRow dataRow1 = infoTb.newRow();
                    dataRow1.set("whyName", sortFiveWhyDoList.get(i).getName());
                    dataRow1.set("whyDesc", whyList.get(j).getDescription());
                    infoTb.getRows().add(dataRow1);
                }
            }
            vo.setWhyInfo(userTb);
            vo.setWhyDesc(infoTb);
        }
        /*****************************问题描述*************************************/
        List<SrmIssuesFiveWhyDo> issuesFiveWhyDos = questionCommonSqlDao.getListByMainId(id)
                .stream()
                .sorted(Comparator.comparing(info->StringUtils.isBlank(info.getWhnumber())?0:Integer.parseInt(info.getWhnumber())))
                .collect(Collectors.toList());
        DataTable pdDataTable = new DataTable("pd");
        pdDataTable.getColumns().add("TITLE");
        pdDataTable.getColumns().add("DESCRIPTION");
        issuesFiveWhyDos.forEach(info -> {
            DataRow dataRow = pdDataTable.newRow();
            dataRow.set("TITLE", info.getWhy());
            dataRow.set("DESCRIPTION", info.getDescription());
            pdDataTable.getRows().add(dataRow);
        });
        listData.add(pdDataTable);
        vo.setListData(listData);
        /*****************************图片处理*************************************/
        List<String> pictures = new ArrayList<>();
        // 原因分析鱼骨图
        pictures.add(srmIssuesListDo.getCauseanalysisimg());
        // 未检测分析鱼骨图
        pictures.add(srmIssuesListDo.getUndetectedanalysisimg());
        // 获取树状图ID
        List<String> mindMappingUrl = exportSqlDao.getMindMappingUrl(id);
        pictures.addAll(mindMappingUrl);
        pictures = pictures.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        vo.setPictures(pictures);
        return vo;
    }

    /**
     * 组织导出excel说需要的数据
     *
     * @param export8DRelevantDataVo
     * @return
     */
    private WorkbookDesigner orgExport8DExcelData(Export8DRelevantDataVo export8DRelevantDataVo, Workbook wb) {
        WorkbookDesigner designer = new WorkbookDesigner();
        designer.setWorkbook(wb);
        designer.setDataSource("edproblemno", "编号Number：" + export8DRelevantDataVo.getEdproblemno());
        designer.setDataSource("edproblemname", export8DRelevantDataVo.getEdproblemname());
        designer.setDataSource("edstartdate", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getEdstartdate()));
        // 组织机构替换
        List<SysOrganizationDo> orgInfo = questionCommonSqlDao.getOrgInfo(new ArrayList<String>() {{
            add(export8DRelevantDataVo.getEdprodepartment());
        }});
        String orgName = orgInfo.isEmpty()?"":orgInfo.get(0).getFullname();
        designer.setDataSource("edprodepartment", orgName);
        designer.setDataSource("edproblemdescription", export8DRelevantDataVo.getEdproblemdescription());
        designer.setDataSource("groupmrmbrr", export8DRelevantDataVo.getGroupmrmbrr());
        designer.setDataSource("edfeverification", export8DRelevantDataVo.getEdfeverification());
        designer.setDataSource("edfvverifier", export8DRelevantDataVo.getEdfvverifier());
        designer.setDataSource("edfvverifiertime", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getEdfvverifiertime()));
        designer.setDataSource("syspreventivemeasure", export8DRelevantDataVo.getSyspreventivemeasure());
        designer.setDataSource("syspreventivetime", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getSyspreventivetime()));
        designer.setDataSource("remake", export8DRelevantDataVo.getRemake());
        designer.setDataSource("tcqaqc", export8DRelevantDataVo.getTcqaqc());
        designer.setDataSource("productionmgr", export8DRelevantDataVo.getProductionmgr());
        /******************************处理系统预防措施*******************************/
        designer.setDataSource("updatepfmea", orgStandardizedContent(export8DRelevantDataVo.getUpdatepfmea(), QuestionConstants.StandardizedContent.PFMEA));
        designer.setDataSource("upfatecontrolplan", orgStandardizedContent(export8DRelevantDataVo.getUpfatecontrolplan(), QuestionConstants.StandardizedContent.CONTROL_PLAN));
        designer.setDataSource("updatesop", orgStandardizedContent(export8DRelevantDataVo.getUpdatesop(), QuestionConstants.StandardizedContent.SOP));
        designer.setDataSource("updatesysfile", orgStandardizedContent(export8DRelevantDataVo.getUpdatesysfile(), QuestionConstants.StandardizedContent.SYSTEM_DOCUMENT));
        designer.setDataSource("ishorizontalexpansion", orgStandardizedContent(export8DRelevantDataVo.getIshorizontalexpansion(), QuestionConstants.StandardizedContent.HORIZONTAL_EXPANSION));
        designer.setDataSource("respomsiblepersonpfmea", export8DRelevantDataVo.getRespomsiblepersonpfmea());
        designer.setDataSource("respomsiblepersonplan", export8DRelevantDataVo.getRespomsiblepersonplan());
        designer.setDataSource("respomsiblepersonsop", export8DRelevantDataVo.getRespomsiblepersonsop());
        designer.setDataSource("respomsiblepersonfile", export8DRelevantDataVo.getRespomsiblepersonfile());
        designer.setDataSource("respomsiblepersonh", export8DRelevantDataVo.getRespomsiblepersonh());
        designer.setDataSource("planedtimepfme", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getPlanedtimepfme()));
        designer.setDataSource("controplanedtime", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getControplanedtime()));
        designer.setDataSource("planedtimesop", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getPlanedtimesop()));
        designer.setDataSource("planedtimesopfile", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getPlanedtimesopfile()));
        designer.setDataSource("planedtimesoph", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getPlanedtimesoph()));
        designer.setDataSource("realplanedtimepfme", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getRealedtimepfme()));
        designer.setDataSource("realcontroplanedtime", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getRealedtimecontro()));
        designer.setDataSource("realplanedtimesop", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getRealedtimesop()));
        designer.setDataSource("realplanedtimesopfile", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getRealedtimesopfile()));
        designer.setDataSource("realplanedtimesoph", QuestionUtils.dateConvertStr(export8DRelevantDataVo.getRealedtimesoph()));
        RunTaskDo runTaskDo = getIVIAInfo(export8DRelevantDataVo.getProcessinstid());
        designer.setDataSource("IVIAedfvverifier",runTaskDo== null?"": runTaskDo.getModifyusername());
        designer.setDataSource("IVIAedfvverifiertime",runTaskDo== null?"":QuestionUtils.dateConvertStr(runTaskDo.getModifydate()));

        /******************************处理实施及验证临时措施*******************************/
        List<Map<String, Object>> listMap;
        Map<String, Object> dataMap;
        listMap = new ArrayList<>();
        List<SrmEightDPlanlistDo> srmEightDPlanlistDos = export8DRelevantDataVo.getSrmEightDPlanlistDos();
        // 按照修改日期逆序
        List<SrmEightDPlanlistDo> planList = srmEightDPlanlistDos.stream()
                .sorted(Comparator.comparing(SrmEightDPlanlistDo::getPlannumber, Comparator.nullsFirst(Comparator.naturalOrder())))
                .collect(Collectors.toList());
        for (int i = 0; i < planList.size(); i++) {
            dataMap = new HashMap<>();
            dataMap.put("serialnumber", i + 1);
            dataMap.put("correctiveaction", planList.get(i).getCorrectiveaction());
            dataMap.put("responsibleperson", planList.get(i).getResponsibleperson());
            dataMap.put("planneddate", QuestionUtils.dateConvertStr(planList.get(i).getPlanendtime()));
            dataMap.put("realplanendDate", QuestionUtils.dateConvertStr(planList.get(i).getRealplanendtime()));
            listMap.add(dataMap);
        }
        designer.setDataSource("list1", new HashMapDataTableVo(listMap));
        /******************************处理寻找和确认根本原因*******************************/
        listMap = new ArrayList<>();
        List<SrmEightDCauselistDo> srmEightDCauselistDos = export8DRelevantDataVo.getSrmEightDCauselistDos();
        // 按照修改日期逆序
        List<SrmEightDCauselistDo> caseList = srmEightDCauselistDos.stream()
                .sorted(Comparator.comparing(SrmEightDCauselistDo::getPlannumber, Comparator.nullsFirst(Comparator.naturalOrder())))
                .collect(Collectors.toList());
        for (int i = 0; i < caseList.size(); i++) {
            dataMap = new HashMap<>();
            dataMap.put("serialnumber", i + 1);
            dataMap.put("outflowcause", caseList.get(i).getOutflowcause());
            dataMap.put("inflowcause", caseList.get(i).getInflowcause());
            listMap.add(dataMap);
        }
        designer.setDataSource("list2", new HashMapDataTableVo(listMap));
        /******************************处理永久性措施*******************************/
        listMap = new ArrayList<>();
        List<SrmEightDAnalysislistDo> srmEightDAnalysislistDoList = export8DRelevantDataVo.getSrmEightDAnalysislistDoList();
        // 按照修改日期逆序
        List<SrmEightDAnalysislistDo> analysislist = srmEightDAnalysislistDoList.stream()
                .sorted(Comparator.comparing(SrmEightDAnalysislistDo::getPlannumber, Comparator.nullsFirst(Comparator.naturalOrder())))
                .collect(Collectors.toList());
        for (int i = 0; i < analysislist.size(); i++) {
            dataMap = new HashMap<>();
            dataMap.put("serialnumber", i + 1);
            dataMap.put("permanentmeasure", analysislist.get(i).getPermanentmeasure());
            dataMap.put("responsibleperson", analysislist.get(i).getResponsibleperson());
            dataMap.put("planneddate", QuestionUtils.dateConvertStr(analysislist.get(i).getPlanendtime()));
            dataMap.put("realplanendDate", QuestionUtils.dateConvertStr(analysislist.get(i).getRealplanendtime()));
            listMap.add(dataMap);
        }
        designer.setDataSource("List3", new HashMapDataTableVo(listMap));
        return designer;
    }

    /**
     * 获取零食验证措施
     */
    private RunTaskDo getIVIAInfo(String processintId){
        if(StringUtils.isBlank(processintId)){
            return  null;
        }
        List<RunTaskDo> runTaskDoList = questionCommonSqlDao.getRunTaskByProcessinsIdAndTaskCode(processintId, "userTask___1678775789101");
        if(runTaskDoList.isEmpty()){
            return null;
        }
        // 获取创建时间最近的一条数据
        RunTaskDo runTaskDo = runTaskDoList.stream()
                .sorted(Comparator.comparing(BaseDo::getCreatedate).reversed()).collect(Collectors.toList()).get(0);
        // 如果最近的一条记录状态不为30 代表退回后待处理
        if(!"30".equals(runTaskDo.getTaskstatus())){
            return null;
        }
        return runTaskDo;
    }
    /**
     * 㢟标准化内容
     *
     * @return
     */
    private String orgStandardizedContent(String value, String prefix) {
        return prefix + String.format(SUFFIX, YES.equals(value) ? "√" : "口", YES.equals(value) ? "口" : "√");
    }

    /**
     * 㢟标准化内容
     *
     * @return
     */
    private String orgIdConvertToOrgName(String orgId, List<SysOrganizationDo> sysOrganizationDos) {
        if (StringUtils.isBlank(orgId)) {
            return "";
        }
        SysOrganizationDo sysOrganizationDo = sysOrganizationDos.stream().filter(info -> info.getId().equals(orgId)).findFirst().orElse(null);
        return sysOrganizationDo == null ? "" : sysOrganizationDo.getFullname();
    }
}
