package com.chinaweal.aiccs.aiccs.revoke.service.impl;

import cn.hutool.core.util.ReUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.revoke.Vo.TsbizrevlistExcelVo;
import com.chinaweal.aiccs.aiccs.revoke.entity.BizRevEnt;
import com.chinaweal.aiccs.aiccs.revoke.entity.TsCase;
import com.chinaweal.aiccs.aiccs.revoke.service.CaseService;
import com.chinaweal.aiccs.aiccs.revoke.service.CreateFileService;
import com.chinaweal.aiccs.aiccs.revoke.service.IllegalactService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.PdfUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.util.SpringUtil;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.deepoove.poi.policy.TextRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 批吊审批流程生成文件创建
 *
 * @Author Lee
 * @Since 2021/5/17 18:02
 */
@Service
@Slf4j
public class CreateFileServiceImpl implements CreateFileService {

    @Autowired
    private IllegalactService illegalactService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Resource
    private FileStorageService fileStorageService;

    @Override
    public void createCaseApprovalDocx(String bizseq, String areaName, String userOrgCode, String workflowId) throws Exception {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();
                // 主体信息
//                EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, pripid));
                map.put("entname", tsCase.getCaseName().replace("关于", StringUtils.EMPTY).replace("的批量吊销", StringUtils.EMPTY));
//                map.put("uniscid",eBaseinfo.getUniscid());
//                map.put("name",eBaseinfo.getName());
//                map.put("dom",eBaseinfo.getDom());
                map.put("areaName", areaName);
//                String entname = eBaseinfo.getEntname();

                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");

//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
                map.put("situation", tsCase.getSituation());
                map.put("registTime", DateUtils.localDateFormat(tsCase.getRegistTime().toLocalDate(), "yyyy年MM月dd日"));
                map.put("caseName", tsCase.getCaseName());
                map.put("remarks", tsCase.getRemarks());
                // 立案或不予立案 标题
                String type = tsCase.getIsRegister().equals("1") ? "立案" : "不予立案";
                map.put("type", type);
                String title = tsCase.getIsRegister().equals("1") ? "立案审批表" : "不予立案审批表";
                map.put("title", title);
                //获取按时间降序，立案意见标识1 2 3排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "1", "2", "3")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("1".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("handler1", item.getHandler());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("2".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("handler2", item.getHandler());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("3".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("handler3", item.getHandler());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }
                }
                String ext = ".docx";
                String fileName = tsCase.getCaseName() + "-" + title + ext;
                String urlFileName = UUID.randomUUID().toString() + "caseApproval" + ext;
                try {
                    ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                    String wordPath = "static" + File.separator + "template" + File.separator + "caseApproval.docx";
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();

//                    String realPath = CommonConfig.getUploadPath();
//                    realPath += File.separator + bizseq + File.separator + "caseApproval";
//                    File dir = new File(realPath);
//                    dir.mkdirs();
                    String wordpath = "BatchRevocation" + File.separator + bizseq + File.separator + "caseApproval" + File.separator + urlFileName;
                    XWPFTemplate.compile(resource).render(map).write(wordOs);
//                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator+ urlFileName);
                    FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                    fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + wordpath, new ByteArrayInputStream(wordOs.toByteArray()));
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException("立案审批表附件生成出错");
                }
                String tempPath = "BatchRevocation" + File.separator + bizseq + File.separator + "caseApproval" + File.separator + urlFileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
//                tsAttachmentModel.setPripid(pripid);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(CommonConfig.getUploadPath() + File.separator + tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("11");// 立案/不予立案审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createPunishAdviceApprDocx(String bizseq, String areaName, String workflowId) throws Exception {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            AICUser user = SSOUtil.getUser();
            String userOrg = StringUtils.substring(user.getRegionID(), 0, 6);
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();

                map.put("caseName", tsCase.getCaseName());
                map.put("hearingToApprRea", tsCase.getHearingToApprRea());
//                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");
//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
//                map.put("registTime",tsCase.getRegistTime());

                // 标题
                String title = "行政处罚建议审批表";
                map.put("title", title);
                map.put("areaName", areaName);

                //获取按时间降序，调查意见标识4 8 9排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "4", "8", "9")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("4".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("handler1", item.getHandler());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("8".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("handler2", item.getHandler());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("9".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("handler3", item.getHandler());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }
                }

                String ext = ".docx";
                String fileName = title + ext;
                String urlFileName = UUID.randomUUID().toString() + "punishAdviceAppr" + ext;
                try {
                    ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                    String wordPath = "static" + File.separator + "template" + File.separator + "punishAdviceAppr.docx";
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();

//                    String realPath = CommonConfig.getUploadPath();
//                    realPath += File.separator + bizseq + File.separator + "punishAdviceAppr";
//                    File dir = new File(realPath);
//                    dir.mkdirs();
//                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + urlFileName);
                    String wordpath = "BatchRevocation" + File.separator + bizseq + File.separator + "punishAdviceAppr" + File.separator + urlFileName;
                    XWPFTemplate.compile(resource).render(map).write(wordOs);
                    FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                    fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + wordpath, new ByteArrayInputStream(wordOs.toByteArray()));
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException("立案审批表附件生成出错");
                }
                String tempPath = "BatchRevocation" + File.separator + bizseq + File.separator + "punishAdviceAppr" + File.separator + urlFileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(CommonConfig.getUploadPath() + File.separator + tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("19");// 行政处罚建议审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createPunishDecisionApprDocx(String bizseq, String areaName, String workflowId) throws Exception {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            AICUser user = SSOUtil.getUser();
            String userOrg = StringUtils.substring(user.getRegionID(), 0, 6);
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();

                map.put("caseName", tsCase.getCaseName());
                map.put("registTime", DateUtils.localDateFormat(tsCase.getRegistTime().toLocalDate(), "yyyy年MM月dd日"));
                if (StringUtils.isNotBlank(tsCase.getIsReviewHearing())) {
                    if (tsCase.getIsReviewHearing().equals("1")) {
                        map.put("isReviewHearing", "当事人未提出陈述、申辩意见或者未申请听证");
                    } else if (tsCase.getIsReviewHearing().equals("2")) {
                        map.put("isReviewHearing", "案件经复核或者听证");
                    } else {
                        map.put("isReviewHearing", StringUtils.EMPTY);
                    }
                } else {
                    map.put("isReviewHearing", StringUtils.EMPTY);
                }
                map.put("advicePunishContent", tsCase.getAdvicePunishContent());
                map.put("pleadOpinion", tsCase.getPleadOpinion());
                map.put("reviewHearingOpinion", tsCase.getReviewHearingOpinion());

                // 标题
                String title = "行政处理决定审批表";
                map.put("title", title);
                map.put("areaName", areaName);

                //获取按时间降序，决定意见标识10 11 13排序好的意见列表    29为法规负责人，11为办案负责人
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "10", "11", "13")//29为法规负责人，11为办案负责人
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("10".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("handler1", item.getHandler());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("11".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("handler2", item.getHandler());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("13".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("handler3", item.getHandler());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }

                }
                String ext = ".docx";
                String fileName = title + ext;
                String urlFileName = UUID.randomUUID().toString() + "punishDecisionAppr" + ext;
                try {
                    ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                    String wordPath = "static" + File.separator + "template" + File.separator + "punishDecisionAppr.docx";
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();
//                    String realPath = CommonConfig.getUploadPath();
//                    realPath += File.separator + bizseq+ File.separator + "punishDecisionAppr";
//                    File dir = new File(realPath);
//                    dir.mkdirs();
//                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + urlFileName);
                    String wordpath = "BatchRevocation" + File.separator + bizseq + File.separator + "punishDecisionAppr" + File.separator + urlFileName;
                    XWPFTemplate.compile(resource).render(map).write(wordOs);
                    FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                    fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + wordpath, new ByteArrayInputStream(wordOs.toByteArray()));

                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException("行政处理决定审批表附件生成出错");
                }
                String tempPath = "BatchRevocation" + File.separator + bizseq + File.separator + "punishDecisionAppr" + File.separator + urlFileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(CommonConfig.getUploadPath() + File.separator + tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("17");// 处罚决定审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createHearingApprovalDocx(String bizseq, String entname, String workflowId) {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();

                map.put("caseName", tsCase.getCaseName());
                map.put("caseNo", tsCase.getCaseNo());
//                map.put("place",tsCase.getPlace());
                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");
//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
                map.put("registTime", DateUtils.localDateFormat(tsCase.getRegistTime().toLocalDate(), "yyyy年MM月dd日"));

                // 标题
                String title = "听证告知审批表";
                map.put("title", title);

                //获取按时间降序，调查意见标识7 8 9排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "7", "8", "9")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("7".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("handler1", item.getHandler());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("8".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("handler2", item.getHandler());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("9".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("handler3", item.getHandler());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }
                }

                String ext = ".docx";
                String fileName = entname + "-" + title + ext;
                String urlFileName = UUID.randomUUID().toString() + "hearingAppr" + ext;
                try {
                    String wordPath = "static" + File.separator + "template" + File.separator + "hearingAppr.docx";
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();

                    String realPath = CommonConfig.getUploadPath();
                    realPath += File.separator + bizseq + File.separator + "hearingAppr";
                    File dir = new File(realPath);
                    dir.mkdirs();
                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + urlFileName);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                String tempPath = bizseq + File.separator + "hearingAppr" + File.separator + urlFileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("16");// 听证告知审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createDecisionApprovalDocx(String bizseq, String entname, String workflowId) {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();

                map.put("caseName", tsCase.getCaseName());
                map.put("caseNo", tsCase.getCaseNo());
//                map.put("place",tsCase.getPlace());
                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");
//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
                map.put("registTime", DateUtils.localDateFormat(tsCase.getRegistTime().toLocalDate(), "yyyy年MM月dd日"));

                // 标题
                String title = "行政处理决定审批表";
                map.put("title", title);

                //获取按时间降序，决定意见标识10 11 12 13排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "10", "11", "12", "13")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("10".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("handler1", item.getHandler());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("11".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("handler2", item.getHandler());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("12".equals(item.getOpiniontype()) && !flag1) {
                        map.put("departOpinion", item.getOpinioncontent());
                        map.put("handler3", item.getHandler());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("13".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("handler4", item.getHandler());
                        map.put("year4", item.getHandledate().getYear());
                        map.put("month4", item.getHandledate().getMonthValue());
                        map.put("day4", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }
                }
                String ext = ".docx";
                String fileName = entname + "-" + title + ext;
                String urlFileName = UUID.randomUUID().toString() + "decisionAppr" + ext;
                try {
                    String wordPath = "static" + File.separator + "template" + File.separator + "decisionAppr.docx";
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();
                    String realPath = CommonConfig.getUploadPath();
                    realPath += File.separator + bizseq + File.separator + "decisionAppr";
                    File dir = new File(realPath);
                    dir.mkdirs();
                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + urlFileName);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                String tempPath = bizseq + File.separator + "hearingAppr" + File.separator + fileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("17");// 审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createSendApprovalDocx(String bizseq, String workflowId) {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();

                map.put("caseName", tsCase.getCaseName());
                map.put("caseNo", tsCase.getCaseNo());
//                map.put("place",tsCase.getPlace());
                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");
//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
                map.put("registTime", tsCase.getRegistTime());

                // 标题
                String title = "送达审批表";
                map.put("title", title);

                //获取按时间降序，调查意见标识14 15 16排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "14", "15", "16")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("14".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("15".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("16".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }
                }

                try {
                    ClassPathResource classPathResource = new ClassPathResource("static/template/hearingAppr.docx");
                    String resource = classPathResource.getURL().getPath();

                    String realPath = CommonConfig.getUploadPath();
                    realPath += File.separator + bizseq;
                    File dir = new File(realPath);
                    dir.mkdirs();
                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + title + ".docx");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                String ext = ".docx";
                String fileName = title + ext;
                String tempPath = bizseq + File.separator + fileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("11");// 审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public void createInvestigateApprovalDocx(String bizseq, String areaName, String entname, String workflowId) {
        if (StringUtils.isNotBlank(bizseq) && StringUtils.isNotBlank(workflowId)) {
            LambdaQueryWrapper<TsCase> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TsCase::getBizseq, bizseq);
            TsCase tsCase = caseService.getOne(wrapper);
            // 案件信息
            if (tsCase != null) {
                Map<String, Object> map = new HashMap<>();

                map.put("caseName", tsCase.getCaseName());
                map.put("areaName", areaName);
//                map.put("caseNo",tsCase.getCaseNo());
//                Map<String, TRBaseCode> caseFromMap = baseCodeService.getBaseCodeMapFormCache("CE03");
//                map.put("caseFrom", caseFromMap.get(tsCase.getCaseFrom()).getName());
//                map.put("registTime",tsCase.getRegistTime());

                // 标题
                String title = "调查审批表";
                map.put("title", title);
                String ext = ".docx";
//                String fileName = entname + "-" + title + ext;
                String fileName = title + ext;
                String urlFileName = UUID.randomUUID().toString() + "investigateAppr" + ext;

                //获取按时间降序，调查意见标识4 5 6排序好的意见列表
                List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                        .eq(TSOpinion::getWorkflowid, workflowId)
                        .eq(TSOpinion::getIsagree, "1")
                        .in(TSOpinion::getOpiniontype, "4", "8", "9")
                        .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
                boolean flag0 = false;
                boolean flag1 = false;
                boolean flag2 = false;
                for (TSOpinion item : list) {
                    if ("4".equals(item.getOpiniontype()) && !flag0) {
                        map.put("enterOpinion", item.getOpinioncontent());
                        map.put("handler1", item.getHandler());
                        map.put("year1", item.getHandledate().getYear());
                        map.put("month1", item.getHandledate().getMonthValue());
                        map.put("day1", item.getHandledate().getDayOfMonth());
                        flag0 = true;
                    }
                    if ("8".equals(item.getOpiniontype()) && !flag1) {
                        map.put("handleOpinion", item.getOpinioncontent());
                        map.put("handler2", item.getHandler());
                        map.put("year2", item.getHandledate().getYear());
                        map.put("month2", item.getHandledate().getMonthValue());
                        map.put("day2", item.getHandledate().getDayOfMonth());
                        flag1 = true;
                    }
                    if ("9".equals(item.getOpiniontype()) && !flag2) {
                        map.put("approvalOpinion", item.getOpinioncontent());
                        map.put("handler3", item.getHandler());
                        map.put("year3", item.getHandledate().getYear());
                        map.put("month3", item.getHandledate().getMonthValue());
                        map.put("day3", item.getHandledate().getDayOfMonth());
                        flag2 = true;
                    }
                }

                try {
                    ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                    String wordPath = "static" + File.separator + "template" + File.separator + "investigateAppr.docx";
                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();

//                    String realPath = CommonConfig.getUploadPath();
//                    realPath += File.separator + bizseq + File.separator + "investigateAppr";
//                    File dir = new File(realPath);
//                    dir.mkdirs();
//                    XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + urlFileName);
                    String wordpath = bizseq + File.separator + "investigateAppr" + File.separator + urlFileName;
                    XWPFTemplate.compile(resource).render(map).write(wordOs);
                    FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                    fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + wordpath, new ByteArrayInputStream(wordOs.toByteArray()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String tempPath = bizseq + File.separator + "investigateAppr" + File.separator + urlFileName;
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(StringUtils.EMPTY);
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setAttachtype("15");// 调查审批表
                // 没有加上传者及id 要改
                attachmentService.save(tsAttachmentModel);
            }
        }
    }

    @Override
    public String createDocx(String bizseq, String fileName, String attachtype, String path, Map<String, Object> map) {
        if (StringUtils.isNotBlank(bizseq)) {
            // 标题
            String title = path.substring(path.lastIndexOf(File.separator) + 1, path.lastIndexOf(Constant.DOT));
            String ext = ".docx";
            String urlFileName = UUID.randomUUID().toString() + ext;
            try {
                ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

//                String realPath = CommonConfig.getUploadPath();
//                realPath += File.separator + bizseq;
//                File dir = new File(realPath + File.separator + title);
//                dir.mkdirs();

                //配置
                // html内容处理
                String htmlContent = map.get("htmlContent").toString();
                Document htmldoc = Jsoup.parse(htmlContent);
                Elements links = htmldoc.getElementsByTag("p");
                ArrayList<Object> list = new ArrayList<>();
                for (Element link : links) {
                    if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                        HashMap<String, Object> map2 = new HashMap<>();
                        map2.put("rightContent", value.text().trim());
                        list.add(map2);
                    } else if (link.getElementsByAttributeValue("style", "text-align:left;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
                        HashMap<String, Object> map3 = new HashMap<>();
                        map3.put("leftContent", value.text().trim());
                        list.add(map3);
                    } else {
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("pragraph", link.text().trim());
                        list.add(map1);
                    }
                }
                map.put("htmlContent", list);
                String wordpath = bizseq + File.separator + title + File.separator + urlFileName;
                XWPFTemplate.compile(resource).render(map).write(wordOs);
                FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + wordpath, new ByteArrayInputStream(wordOs.toByteArray()));
//                XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + title + File.separator + urlFileName);

            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("附件生成出错");
            }
            if (StringUtils.isBlank(fileName)) {
                fileName = title + ext;
            } else if (fileName.lastIndexOf(Constant.DOT) > -1) {
                fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
            } else {
                fileName = fileName + ext;
            }
            String tempPath = bizseq + File.separator + title + File.separator + urlFileName;

            if (map.get("noAttach") != null && map.get("noAttach").toString().equals("noAttach")) {
                return tempPath;
            }
            boolean save = false;
            if ("20".equals(attachtype)) {// 针对批吊业务的处罚决定书预览附件
                TSAttachment tsAttachment = new TSAttachment();
                tsAttachment.setBizseq(bizseq).setAttachtype("20");
                List<TSAttachment> tsAttachments = attachmentService.selectwritByPage(tsAttachment);
                if (CollectionUtils.isNotEmpty(tsAttachments)) {
                    TSAttachment attachment = tsAttachments.get(0);
                    attachment.setTemppath(tempPath);
                    attachment.setUploaddate(LocalDate.now());
                    attachment.setLauptime(LocalDateTime.now());
                    save = attachmentService.updateById(attachment);
                } else {
                    TSAttachment tsAttachmentModel = new TSAttachment();
                    tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                    tsAttachmentModel.setBizseq(bizseq);
                    tsAttachmentModel.setPripid(map.get("pripid").toString());
                    tsAttachmentModel.setFileext(ext);
                    tsAttachmentModel.setFilename(fileName);
                    tsAttachmentModel.setTemppath(tempPath);
                    tsAttachmentModel.setUploaddate(LocalDate.now());
                    tsAttachmentModel.setLauptime(LocalDateTime.now());
                    tsAttachmentModel.setAttachtype(attachtype);// 审批表
                    // 没有加上传者及id 要改
                    save = attachmentService.save(tsAttachmentModel);
                }
            } else {
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(map.get("pripid").toString());
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setLauptime(LocalDateTime.now());
                tsAttachmentModel.setAttachtype(attachtype);// 审批表
                // 没有加上传者及id 要改
                save = attachmentService.save(tsAttachmentModel);
            }
            if (save) {
                return tempPath;
            }
        }
        return null;
    }

    @Override
    public String createPdf(String bizseq, String fileName, String attachtype, String path, Map<String, Object> map) {
        if (StringUtils.isNotBlank(bizseq)) {
            // 标题
            String title = path.substring(path.lastIndexOf(File.separator) + 1, path.lastIndexOf(Constant.DOT));
            String ext = ".pdf";
            String urlFileName = UUID.randomUUID().toString() + ext;
            try {
                ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                //配置
                // html内容处理
                String htmlContent = map.get("htmlContent").toString();
                Document htmldoc = Jsoup.parse(htmlContent);
                Elements links = htmldoc.getElementsByTag("p");
                ArrayList<Object> list = new ArrayList<>();
                for (Element link : links) {
                    if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                        HashMap<String, Object> map2 = new HashMap<>();
                        map2.put("rightContent", value.text().trim());
                        list.add(map2);
                    } else if (link.getElementsByAttributeValue("style", "text-align:left;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
                        HashMap<String, Object> map3 = new HashMap<>();
                        map3.put("leftContent", value.text().trim());
                        list.add(map3);
                    } else {
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("pragraph", link.text().trim());
                        list.add(map1);
                    }
                }
                map.put("htmlContent", list);
                String pdfPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizseq + File.separator + title + File.separator + urlFileName;
                XWPFTemplate.compile(resource).render(map).write(wordOs);
                PdfUtil.convertDocx2Pdf(wordOs, pdfPath);

            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("批吊附件文书pdf上传失败");
            }
            if (StringUtils.isBlank(fileName)) {
                fileName = urlFileName;
            } else if (fileName.lastIndexOf(Constant.DOT) > -1) {
                fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
            } else {
                fileName = fileName + ext;
            }
            String tempPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizseq + File.separator + title + File.separator + urlFileName;

            if (map.get("noAttach") != null && map.get("noAttach").toString().equals("noAttach")) {
                return tempPath;
            }
            boolean save = false;
            if ("20".equals(attachtype)) {// 针对批吊业务的处罚决定书预览附件
                TSAttachment tsAttachment = new TSAttachment();
                tsAttachment.setBizseq(bizseq).setAttachtype("20");
                List<TSAttachment> tsAttachments = attachmentService.selectwritByPage(tsAttachment);
                if (CollectionUtils.isNotEmpty(tsAttachments)) {
                    TSAttachment attachment = tsAttachments.get(0);
                    attachment.setTemppath(tempPath);
                    attachment.setUploaddate(LocalDate.now());
                    attachment.setLauptime(LocalDateTime.now());
                    save = attachmentService.updateById(attachment);
                } else {
                    TSAttachment tsAttachmentModel = new TSAttachment();
                    tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                    tsAttachmentModel.setBizseq(bizseq);
                    tsAttachmentModel.setPripid(map.get("pripid").toString());
                    tsAttachmentModel.setFileext(ext);
                    tsAttachmentModel.setFilename(fileName);
                    tsAttachmentModel.setTemppath(tempPath);
                    tsAttachmentModel.setUploaddate(LocalDate.now());
                    tsAttachmentModel.setLauptime(LocalDateTime.now());
                    tsAttachmentModel.setAttachtype(attachtype);// 审批表
                    // 没有加上传者及id 要改
                    save = attachmentService.save(tsAttachmentModel);
                }
            } else {
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setCreatetype("1");// 文件为系统生成
                tsAttachmentModel.setBizseq(bizseq);
                tsAttachmentModel.setPripid(map.get("pripid").toString());
                tsAttachmentModel.setFileext(ext);
                tsAttachmentModel.setFilename(fileName);
                tsAttachmentModel.setTemppath(tempPath);
                tsAttachmentModel.setUploaddate(LocalDate.now());
                tsAttachmentModel.setLauptime(LocalDateTime.now());
                tsAttachmentModel.setAttachtype(attachtype);// 审批表
                // 没有加上传者及id 要改
                save = attachmentService.save(tsAttachmentModel);
            }
            if (save) {
                return tempPath;
            }
        }
        return null;
    }

    @Override
    public String createPdfCommon(String bizseq, String title, String fileName, String moduleType, String attachtype, String templatePath, Map<String, Object> data) {
        if (StringUtils.isNotBlank(bizseq)) {
            // 标题
            String ext = ".pdf";
            String urlFileName = UUID.randomUUID().toString() + ext;
            if (StringUtils.isBlank(moduleType)) {
                moduleType = "common";
            }
            try {
                ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                String resource = CreateFileServiceImpl.class.getClassLoader().getResource(templatePath).getPath();

                //配置
                // html内容处理
                String htmlContent = data.get("htmlContent").toString();
                Document htmldoc = Jsoup.parse(htmlContent);
                Elements links = htmldoc.getElementsByTag("p");
                ArrayList<Object> list = new ArrayList<>();
                for (Element link : links) {
                    if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                        HashMap<String, Object> map2 = new HashMap<>();
                        map2.put("rightContent", value.text().trim());
                        list.add(map2);
                    } else if (link.getElementsByAttributeValue("style", "text-align:left;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
                        HashMap<String, Object> map3 = new HashMap<>();
                        map3.put("leftContent", value.text().trim());
                        list.add(map3);
                    } else {
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("pragraph", link.text().trim());
                        list.add(map1);
                    }
                }
                data.put("htmlContent", list);
                String pdfPath = CommonConfig.getUploadPath() + File.separator + moduleType + File.separator + bizseq + File.separator + title + File.separator + urlFileName;
                XWPFTemplate.compile(resource).render(data).write(wordOs);
                PdfUtil.convertDocx2Pdf(wordOs, pdfPath);

            } catch (Exception e) {
                log.error("附件文书pdf生成失败", e);
                throw new BusinessException("附件文书pdf生成失败");
            }
            if (StringUtils.isBlank(fileName)) {
                fileName = urlFileName;
            } else if (fileName.lastIndexOf(Constant.DOT) > -1) {
                fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
            } else {
                fileName = fileName + ext;
            }
            String tempPath = CommonConfig.getUploadPath() + File.separator + moduleType + File.separator + bizseq + File.separator + title + File.separator + urlFileName;
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setCreatetype("1");// 文件为系统生成
            tsAttachmentModel.setBizseq(bizseq);
            tsAttachmentModel.setAttachtype(attachtype);
            tsAttachmentModel.setPripid(StringUtils.tranObject(data.get("pripid")));
            tsAttachmentModel.setFileext(ext);
            tsAttachmentModel.setFilename(fileName);
            tsAttachmentModel.setTemppath(tempPath);
            tsAttachmentModel.setUploaddate(LocalDate.now());
            tsAttachmentModel.setLauptime(LocalDateTime.now());
            tsAttachmentModel.setAttachtype(attachtype);// 审批表
            // 没有加上传者及id 要改
            boolean save = attachmentService.save(tsAttachmentModel);
            if (save) {
                return tempPath;
            }
        }
        return null;
    }

    @Override
    public ServletOutputStream createPdfStream(String bizseq, String fileName, String attachtype, String path, Map<String, Object> map, ServletOutputStream os) {
        if (StringUtils.isNotBlank(bizseq)) {
            try {
                ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                //配置
                // html内容处理
                String htmlContent = map.get("htmlContent").toString();
                Document htmldoc = Jsoup.parse(htmlContent);
                Elements links = htmldoc.getElementsByTag("p");
                ArrayList<Object> list = new ArrayList<>();
                for (Element link : links) {
                    if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                        HashMap<String, Object> map2 = new HashMap<>();
                        map2.put("rightContent", value.text().trim());
                        list.add(map2);
                    } else if (link.getElementsByAttributeValue("style", "text-align:left;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:left;");
                        HashMap<String, Object> map3 = new HashMap<>();
                        map3.put("leftContent", value.text().trim());
                        list.add(map3);
                    } else {
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("pragraph", link.text().trim());
                        list.add(map1);
                    }
                }
                map.put("htmlContent", list);
                XWPFTemplate.compile(resource).render(map).write(wordOs);
                ServletOutputStream pdfOs = PdfUtil.convertDocx2PdfStream(wordOs, os);
                return pdfOs;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void createDocxWithModel(String bizseq, String fileName, String attachtype, String path, Map<String, Object> map) {
        if (StringUtils.isNotBlank(bizseq)) {
            // 标题
            String title = path.substring(path.lastIndexOf(File.separator) + 1, path.lastIndexOf(Constant.DOT));
            String ext = ".docx";
            String urlFileName = UUID.randomUUID().toString() + ext;
            try {
                ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                //配置
                // html内容处理
                String htmlContent = map.get("htmlContent").toString();
                Document htmldoc = Jsoup.parse(htmlContent);
                Elements links = htmldoc.getElementsByTag("p");
                ArrayList<Object> list = new ArrayList<>();
                for (Element link : links) {
                    if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                        HashMap<String, Object> map2 = new HashMap<>();
                        map2.put("rightContent", value.text().trim());
                        list.add(map2);
                    } else {
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("pragraph", link.text().trim());
                        list.add(map1);
                    }
                }
                map.put("htmlContent", list);

                HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
                Configure config = Configure.newBuilder()
                        .bind("nameList", policy).build();

//                XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + title + File.separator + urlFileName);

                String wordpath = bizseq + File.separator + title + File.separator + urlFileName;
                XWPFTemplate.compile(resource, config).render(map).write(wordOs);
                String filePath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + wordpath;
                // 案件终结报告可能存在多次修改更新，更新时覆盖原来的文件，使用map的oldPath
                if (map.get("oldPath") != null && StringUtils.isNotEmpty(map.get("oldPath").toString())) {
                    filePath = map.get("oldPath").toString();
                }
                fileStorageService.writeFromStream(filePath, new ByteArrayInputStream(wordOs.toByteArray()));
                if (map.get("noAttach") != null && map.get("noAttach").toString().equals("noAttach")) {
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isBlank(fileName)) {
                fileName = title + ext;
            } else if (fileName.lastIndexOf(Constant.DOT) > -1) {
                fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
            } else {
                fileName = fileName + ext;
            }
            String tempPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizseq + File.separator + title + File.separator + urlFileName;
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setCreatetype("1");// 文件为系统生成
            tsAttachmentModel.setBizseq(bizseq);
            tsAttachmentModel.setPripid(StringUtils.EMPTY);
            tsAttachmentModel.setFileext(ext);
            tsAttachmentModel.setFilename(fileName);
            tsAttachmentModel.setTemppath(tempPath);
            tsAttachmentModel.setUploaddate(LocalDate.now());
            tsAttachmentModel.setAttachtype(attachtype);// 审批表
            // 没有加上传者及id 要改
            attachmentService.save(tsAttachmentModel);

        }
    }

    @Override
    public void createCasePdfWithModel(String bizseq, String fileName, String attachtype, String path, Map<String, Object> map) {
        if (StringUtils.isNotBlank(bizseq)) {
            // 标题
            String title = path.substring(path.lastIndexOf(File.separator) + 1, path.lastIndexOf(Constant.DOT));
            String ext = ".pdf";
            String urlFileName = UUID.randomUUID().toString() + ext;
            try {
                ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流
                String resource = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();

                //配置
                // html内容处理
                String htmlContent = map.get("htmlContent").toString();
                Document htmldoc = Jsoup.parse(htmlContent);
                Elements links = htmldoc.getElementsByTag("p");
                ArrayList<Object> list = new ArrayList<>();
                for (Element link : links) {
                    if (link.getElementsByAttributeValue("style", "text-align:right;").size() > 0) {
                        Elements value = link.getElementsByAttributeValue("style", "text-align:right;");
                        HashMap<String, Object> map2 = new HashMap<>();
                        map2.put("rightContent", value.text().trim());
                        list.add(map2);
                    } else {
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("pragraph", link.text().trim());
                        list.add(map1);
                    }
                }
                map.put("htmlContent", list);

//                HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy();

                HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
                Configure config = Configure.newBuilder()
//                        .bind("htmlContent",htmlRenderPolicy)
                        .bind("nameList", policy).build();

//                XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + title + File.separator + urlFileName);

                String pdfPath = bizseq + File.separator + title + File.separator + urlFileName;
                XWPFTemplate.compile(resource, config).render(map).write(wordOs);

                String filePath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + pdfPath;
                // 案件终结报告可能存在多次修改更新，更新时覆盖原来的文件，使用map的oldPath
                if (map.get("oldPath") != null && StringUtils.isNotEmpty(map.get("oldPath").toString())) {
                    filePath = map.get("oldPath").toString();
                }
                PdfUtil.convertDocx2Pdf(wordOs, filePath);
                if (map.get("noAttach") != null && map.get("noAttach").toString().equals("noAttach")) {
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException(e.getMessage());
            }
            if (StringUtils.isBlank(fileName)) {
                fileName = title + ext;
            } else if (fileName.lastIndexOf(Constant.DOT) > -1) {
                fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
            } else {
                fileName = fileName + ext;
            }
            String tempPath = CommonConfig.getUploadPath() + File.separator + "BatchRevocation" + File.separator + bizseq + File.separator + title + File.separator + urlFileName;
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setCreatetype("1");// 文件为系统生成
            tsAttachmentModel.setBizseq(bizseq);
            tsAttachmentModel.setPripid(StringUtils.EMPTY);
            tsAttachmentModel.setFileext(ext);
            tsAttachmentModel.setFilename(fileName);
            tsAttachmentModel.setTemppath(tempPath);
            tsAttachmentModel.setUploaddate(LocalDate.now());
            tsAttachmentModel.setAttachtype(attachtype);// 审批表
            // 没有加上传者及id 要改
            attachmentService.save(tsAttachmentModel);

        }
    }

    /**
     * 创建测试用例过程记录的渲染策略：解析对应的html并输出到word
     *
     * @param
     * @return {@link AbstractRenderPolicy}
     * @author xuwangcheng
     * @date 2019/7/26 10:10
     */
    private static AbstractRenderPolicy createHtmlRenderPolicy() {
        return new AbstractRenderPolicy() {
            @Override
            public void doRender(RenderContext renderContext) throws Exception {
                Object data = renderContext.getData();
                XWPFTemplate template = renderContext.getTemplate();
                if (data == null || StringUtils.isBlank(data.toString())) {
                    return;
                }
                //获得Apache POI增强类NiceXWPFDocument
                NiceXWPFDocument doc = template.getXWPFDocument();
                String html = data.toString();
                html = html.replaceAll("&gt;", ">")
                        .replaceAll("&lt;", "<")
                        .replaceAll("&nbsp;", " ")
                        .replaceAll("\\n", "")
                        .replaceAll("<br>", "\n");
                org.jsoup.nodes.Document htmlDoc = Jsoup.parse(html);
                Elements nodes = htmlDoc.body().children();
                XWPFParagraph xwpfParagraph = doc.createParagraph();

                ListIterator<Element> itr = nodes.listIterator();
                while (itr.hasNext()) {
                    Element e = itr.next();
                    xwpfParagraph = parseHtmlToWord(e, doc, xwpfParagraph, true);
                }
            }

            @Override
            protected void afterRender(RenderContext context) {
                // 清空模板标签所在段落
                clearPlaceholder(context, true);
            }

        };
    }

    /**
     * 转换整个html内容为word内容
     *
     * @param ele           ele
     * @param doc           doc
     * @param xwpfParagraph xwpfParagraph
     * @return {@link XWPFParagraph}
     * @author xuwangcheng
     * @date 2019/7/29 18:46
     */
    private static XWPFParagraph parseHtmlToWord(Element ele, NiceXWPFDocument doc, XWPFParagraph xwpfParagraph
            , boolean isParent) throws Exception {

        //处理img图片
//        if ("img".equals(ele.tagName())) {
//            parseImgToWord(ele.attr("src"), xwpfParagraph);
//            return xwpfParagraph;
//        }

        //处理table标签
//        if ("table".equals(ele.tagName())) {
//            parseTableToWord(doc, ele);
//            //有表格的话新建段落
//            xwpfParagraph = doc.createParagraph();
//            return xwpfParagraph;
//        }


        //处理<sup>标签 上标
        if ("sup".equalsIgnoreCase(ele.tagName())) {
            XWPFRun run = xwpfParagraph.createRun();
            run.setText(ele.text());
            // 设置字体加粗;
            run.setBold(true);
            // 设置字体大小;
            run.setFontSize(12);
            run.setFontFamily("Times New Roman", XWPFRun.FontCharRange.ascii);
            run.setFontFamily("宋体", XWPFRun.FontCharRange.eastAsia);
            run.setSubscript(VerticalAlign.SUPERSCRIPT);

            TextRenderPolicy.Helper.renderTextRun(run, new TextRenderData(ele.text()));
            return xwpfParagraph;
        }

        //处理其他文本标签
        String text = ele.ownText();
        boolean continueItr = true;
        //span标签默认全部为文字，不再继续迭代
        if ("span".equalsIgnoreCase(ele.tagName())) {
            text = ele.wholeText();
            continueItr = false;
        }

        boolean enabledBreak = (isParent || StringUtils.isNotBlank(ele.text()))
                && ReUtil.isMatch("(p|h[12345]|li|img)", ele.tagName());
        if (enabledBreak) {
            XWPFRun run = xwpfParagraph.createRun();
            run.addBreak();
        }

        if (StringUtils.isNotBlank(text)) {
            XWPFRun run = xwpfParagraph.createRun();
            TextRenderPolicy.Helper.renderTextRun(run, new TextRenderData(text));
        }


        if (continueItr && ele.children().size() > 0) {
            ListIterator<Element> itr = ele.children().listIterator();
            while (itr.hasNext()) {
                Element me = itr.next();
                xwpfParagraph = parseHtmlToWord(me, doc, xwpfParagraph, false);
            }
        }

        return xwpfParagraph;
    }

    @Override
    public String createEntExcel(String bizseq, String attachtype, List<BizRevEnt> bizRevEnts) {
        if (CollectionUtils.isNotEmpty(bizRevEnts)) {
            String ext = ".xlsx";
            String urlFileName = UUID.randomUUID().toString() + ext;

            String tempPath = "BatchRevocation" + File.separator + bizseq + File.separator + urlFileName;
            ArrayList<TsbizrevlistExcelVo> list = new ArrayList<>();
            for (BizRevEnt bizRevEnt : bizRevEnts) {
                TsbizrevlistExcelVo excelVo = new TsbizrevlistExcelVo();
                excelVo.setUniscid(bizRevEnt.getUniscid());
                excelVo.setRegno(bizRevEnt.getRegno());
                excelVo.setEntname(bizRevEnt.getEntname());
                excelVo.setName(bizRevEnt.getName());
                list.add(excelVo);
            }
            TsCase aCase = caseService.getByBizseq(bizseq);
            String caseName = null;
            if (aCase != null) {
                caseName = aCase.getCaseName();
            }

            String fileName = null;
            String sheetname = "名单清单";
            switch (attachtype) {
                case "21":
                    sheetname = "立案名单";
                    fileName = caseName + "-" + sheetname + ext;
                    break;
                case "22":
                    sheetname = "听证告知名单";
                    fileName = caseName + "-" + sheetname + ext;
                    break;
                case "23":
                    sheetname = "行政处罚决定名单";
                    fileName = caseName + "-" + sheetname + ext;
                    break;
            }
            List<String> includeColumnFiledNames = new ArrayList<>();
            includeColumnFiledNames.add("uniscid");
            includeColumnFiledNames.add("regno");
            includeColumnFiledNames.add("entname");
            includeColumnFiledNames.add("name");
            try {
                ByteArrayOutputStream excelOs = new ByteArrayOutputStream(); // word输出流
                EasyExcel.write(excelOs, TsbizrevlistExcelVo.class).includeColumnFiledNames(includeColumnFiledNames)
                        .sheet(sheetname).doWrite(list);
                FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + tempPath, new ByteArrayInputStream(excelOs.toByteArray()));
            } catch (Exception e) {
                e.printStackTrace();
            }


            // 保存文件信息至数据库
            TSAttachment tsAttachmentModel = new TSAttachment();
            tsAttachmentModel.setCreatetype("1");// 文件为系统生成
            tsAttachmentModel.setBizseq(bizseq);
//            tsAttachmentModel.setPripid(StringUtils.EMPTY);
            tsAttachmentModel.setFileext(ext);
            tsAttachmentModel.setFilename(fileName);
            tsAttachmentModel.setTemppath(CommonConfig.getUploadPath() + File.separator + tempPath);
            tsAttachmentModel.setUploaddate(LocalDate.now());
            tsAttachmentModel.setAttachtype(attachtype);//
            // 没有加上传者及id 要改
            boolean save = attachmentService.save(tsAttachmentModel);
            if (save) {
                return tempPath;
            }
        }
        return null;
    }

    @Override
    public String createPdfZx(String bizseq, String fileName, String attachtype, String path, Map<String, Object> map) {
        // 校验必要参数
        if (StringUtils.isBlank(bizseq) || map == null) {
            throw new BusinessException("必要参数不能为空");
        }

        try {
            // 处理文件名和路径
            String title = path.substring(path.lastIndexOf(File.separator) + 1, path.lastIndexOf(Constant.DOT));
            String ext = ".pdf";
            String urlFileName = UUID.randomUUID().toString() + ext;

            // 构建PDF保存路径
            String baseDir = CommonConfig.getUploadPath() + File.separator + "BatchRevocationZx" +
                    File.separator + bizseq + File.separator + title;
            File dir = new File(baseDir);
            if (!dir.exists() && !dir.mkdirs()) {
                throw new BusinessException("无法创建文件目录: " + baseDir);
            }
            String pdfPath = baseDir + File.separator + urlFileName;

            // 处理模板渲染
            try (ByteArrayOutputStream wordOs = new ByteArrayOutputStream()) {
                // 获取模板资源
                String resourcePath = CreateFileServiceImpl.class.getClassLoader().getResource(path).getPath();
                if (resourcePath == null) {
                    throw new BusinessException("未找到模板文件: " + path);
                }

                // 渲染Word模板
                XWPFTemplate.compile(resourcePath).render(map).write(wordOs);
                wordOs.flush();

                // 转换为PDF
                PdfUtil.convertDocx2Pdf(wordOs, pdfPath);
            }

            // 处理返回文件名
            if (StringUtils.isBlank(fileName)) {
                fileName = urlFileName;
            } else if (fileName.lastIndexOf(Constant.DOT) > -1) {
                fileName = fileName.substring(0, fileName.lastIndexOf(Constant.DOT)) + ext;
            } else {
                fileName = fileName + ext;
            }

            // 不需要保存附件的情况
            if (map.get("noAttach") != null && "noAttach".equals(map.get("noAttach").toString())) {
                return pdfPath;
            }

            // 保存附件信息
            TSAttachment attachment = buildAttachment(bizseq, map, fileName, pdfPath, attachtype);
            boolean saveSuccess = saveOrUpdateAttachment(attachment, attachtype);

            return saveSuccess ? pdfPath : null;

        } catch (Exception e) {
            log.error("生成批吊附件文书PDF失败", e);
            throw new BusinessException("批吊附件文书pdf上传失败: " + e.getMessage());
        }
    }

    /**
     * 构建附件对象
     */
    private TSAttachment buildAttachment(String bizseq, Map<String, Object> map, String fileName,
                                         String tempPath, String attachtype) {
        TSAttachment attachment = new TSAttachment();
        attachment.setAttachmentid(bizseq);
        attachment.setCreatetype("1"); // 系统生成文件
        attachment.setBizseq(bizseq);
        attachment.setPripid(map.get("pripid") != null ? map.get("pripid").toString() : "");
        attachment.setFileext(".pdf");
        attachment.setFilename(fileName);
        attachment.setTemppath(tempPath);
        attachment.setUploaddate(LocalDate.now());
        attachment.setLauptime(LocalDateTime.now());
        attachment.setAttachtype(attachtype);

        // 补充上传者信息（根据实际情况从session或上下文获取）
        // attachment.setUploaderId(...);
        // attachment.setUploaderName(...);

        return attachment;
    }

    /**
     * 保存或更新附件
     */
    private boolean saveOrUpdateAttachment(TSAttachment attachment, String attachtype) {
        return attachmentService.save(attachment);
    }
}
