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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
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.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.rules.model.SequenceFlowModel;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.expelled.entity.EntBaseExpelledInfo;
import com.chinaweal.aiccs.aiccs.expelled.entity.ExpelledBizInfo;
import com.chinaweal.aiccs.aiccs.expelled.entity.ExpelledEntInfo;
import com.chinaweal.aiccs.aiccs.expelled.mapper.ExpelledBizInfoMapper;
import com.chinaweal.aiccs.aiccs.expelled.service.IEntBaseExpelledInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledBizInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledEntInfoService;
import com.chinaweal.aiccs.aiccs.expelled.vo.BizInfoVo;
import com.chinaweal.aiccs.aiccs.expelled.vo.RemoveApproveInfo;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.HandleWorkFlowUtil;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.utils.BeanUtil;
import com.chinaweal.aiccs.utils.DocumentNoGenerator;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.deepoove.poi.XWPFTemplate;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: 市场主体拟除名名单业务表实现类
 * @Author: TiAmo-cc
 * @Email: 1049976610@qq.com
 * @Date: 2026/1/5 10:52
 */
@Service
public class ExpelledBizInfoServiceImpl extends ServiceImpl<ExpelledBizInfoMapper, ExpelledBizInfo> implements IExpelledBizInfoService {

    @Resource
    private IEntBaseExpelledInfoService entBaseExpelledInfoService;
    @Resource
    private IExpelledEntInfoService expelledEntInfoService;
    @Resource
    private TSTaskListService tsTaskListService;
    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private TSOpinionService opinionService;
    @Resource
    private TSAttachmentService attachmentService;

    @Override
    public RestResult<?> startNoticeBiz(ExpelledBizInfo query, HttpServletRequest request) {
        AICUser user = BaseController.getLoginUser(request);
        if (user == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        if (CollectionUtils.isEmpty(query.getExpelledIds())) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK, "请至少勾选一个拟除名市场主体");
        }
        Map<String, Object> resultMap = new HashMap<>();
        String bizId = UUID.randomUUID().toString();
        // 添加待办启动流程
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizId);
        tsTaskList.setBustype(BaseDataConstant.BUSINESS_TYPE_REMOVE_NOTICE); // 除名告知
        tsTaskList.setBusname(query.getBusName());
        // 保存除名告知数据
        ExpelledBizInfo noticeInfo = new ExpelledBizInfo();
        noticeInfo.setId(bizId);
        noticeInfo.setBizNo(generateBizNo());
        // 初始化市场主体除名结果信息
        for (String expelledId : query.getExpelledIds()) {
            EntBaseExpelledInfo expelledInfo = entBaseExpelledInfoService.getById(expelledId);
            if (expelledInfo == null) {
                continue;
            }
            ExpelledEntInfo entInfo = new ExpelledEntInfo();
            entInfo.setBizId(noticeInfo.getId());
            entInfo.setExpelledId(expelledId);
            expelledEntInfoService.saveExpelledEntInfo(entInfo);
            // 更新拟除名名单库状态
            expelledInfo.setState("0"); // 拟除名中
            entBaseExpelledInfoService.saveOrUpdate(expelledInfo);
        }
        // 保存业务待办信息
        tsTaskList = startNoticeBizAccept(user, tsTaskList, noticeInfo);
        List<SequenceFlowModel> nextSequenceFlows = workFlowService.findNextSequenceFlowList(tsTaskList.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(tsTaskList.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) {
            opinionType = "1";
        }
        resultMap.put("noticeInfo", noticeInfo);
        resultMap.put("taskId", tsTaskList.getTasklistid());
        resultMap.put("bizId", bizId);
        resultMap.put("nextSequenceFlows", nextSequenceFlows);
        resultMap.put("currentNode", currentNode.getCurrentnode());
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        resultMap.put("currentLinkTypeID", opinionType);
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> getNoticeBiz(String bizId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 除名告知业务表
        ExpelledBizInfo noticeInfo = getById(bizId);
        if (noticeInfo == null) {
            throw new BusinessException("除名告知业务信息不存在，请联系管理员");
        }
        resultMap.put("noticeInfo", noticeInfo);
        // 拟除名企业信息
        BizInfoVo query = new BizInfoVo();
        query.setId(bizId);
        List<BizInfoVo> entInfos = baseMapper.listNoticeEntBaseInfo(query);
        resultMap.put("entInfos", entInfos);
        // 除名业务待办
        TSTaskList tsTaskList = tsTaskListService.searchTaskListByBizId(bizId);
        if (tsTaskList == null) {
            throw new BusinessException("除名告知业务待办信息不存在，请联系管理员");
        }
        resultMap.put("tsTaskList", new TSTaskList().setTasklistid(tsTaskList.getTasklistid()).setWorkflowid(tsTaskList.getWorkflowid()));
        // 获取历史审批意见
        LambdaQueryWrapper<TSOpinion> opinionWrapper = new LambdaQueryWrapper<>();
        opinionWrapper.eq(TSOpinion::getBizseq, bizId)
                .ne(TSOpinion::getOpiniontype, "55")
                .orderByAsc(TSOpinion::getHandledate);
        List<TSOpinion> tsOpinions = opinionService.list(opinionWrapper);
        resultMap.put("historyOpinions", tsOpinions);
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> nextNoticeBiz(RemoveApproveInfo removeApproveInfo, HttpServletRequest request) {
        AICUser user = BaseController.getLoginUser(request);
        if (user == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        String bizId = removeApproveInfo.getBizId();
        String taskId = removeApproveInfo.getTaskId();
        String nextNodeId = removeApproveInfo.getNextNodeId();
        String nextPerformerIds = removeApproveInfo.getNextPerformerIds();
        String nextPerformerNames = removeApproveInfo.getNextPerformerNames();
        ExpelledBizInfo noticeInfoQuery = removeApproveInfo.getNoticeInfo();
        if (StringUtils.isBlank(bizId)) {
            throw new BusinessException("bizId参数缺失");
        }
        if (StringUtils.isBlank(taskId)) {
            throw new BusinessException("taskId参数缺失");
        }
        if (StringUtils.isBlank(nextNodeId)) {
            throw new BusinessException("nextNodeId参数缺失");
        }
        if (noticeInfoQuery == null) {
            throw new BusinessException("noticeInfoQuery参数缺失");
        }
        Map<String, Object> resultMap = new HashMap<>();
        ExpelledBizInfo noticeInfo = getById(bizId);
        if (noticeInfo == null) {
            throw new BusinessException("除名告知业务信息不存在，请联系管理员");
        }
        // 更新除名告知业务表
        if (noticeInfoQuery != null && StringUtils.isNotBlank(noticeInfoQuery.getId())) {
            TSTaskList tsTaskList = tsTaskListService.selectByTasklistID(taskId);
            TSTwfProcessNode processNode = workFlowService.findCurrentNode(tsTaskList.getWorkflowid());

            // 下一步为审核
            if (StringUtils.equals(FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST, nextNodeId)) {
                if (StringUtils.equals(FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER, processNode.getCurrentnode())) {
                    BeanUtil.copyBean(noticeInfoQuery, noticeInfo);
                }
            }

            if (StringUtils.isBlank(nextPerformerIds)) {
                processNode = workFlowService.findCurrentNode(tsTaskList.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeId);
                // 通过order判断为回退还是前进 >0 前进
                if (order > 0) {
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, tsTaskList.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, "0") // 经办为0
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE, "除名告知审批意见不存在，请联系管理员");
                    }
                    nextPerformerIds = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
                // 回退时获取经办人
                if (order < 0) {
                    // 获取经办人
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, tsTaskList.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, '0')
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (org.apache.commons.collections.CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE, "除名告知审批意见不存在，请联系管理员");
                    }
                    nextPerformerIds = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
            }

            // 发送
            String[] ids = StringUtils.split(nextPerformerIds, Constant.COMMA);
            String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
            try {
                tsTaskList = saveNoticeAuditProcess(user, tsTaskList, noticeInfo, removeApproveInfo.getOpinionQuery(), nextNodeId, ids, names);
                if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                    resultMap.put("bizId", bizId);
                    resultMap.put("taskId", taskId);
                    resultMap.put("nextNodeId", nextNodeId);
                    resultMap.put("workFlowId", tsTaskList.getWorkflowid());
                }
            } catch (Exception e) {
                log.error("除名告知业务审批出错：", e);
                throw new BusinessException("除名告知业务审批出错");
            }
        }
        return RestResult.ok(resultMap);
    }

    @Override
    public TSTaskList startNoticeBizAccept(AICUser user, TSTaskList tsTaskList, ExpelledBizInfo noticeInfo) {
        if (StringUtils.isBlank(tsTaskList.getTasklistid())) {
            noticeInfo.setIsDelete("0");
            saveOrUpdate(noticeInfo);
            String definedname = FlowUtil.EXPTLISTWORKFLOW; // 除名告知，这类参考使用企业经营异常名录流程模板，应该是可以的吧
            // 新待办
            tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
            // 开始工作流
            tsTaskListService.startWorkFlow(tsTaskList, user, definedname);
        }
        return tsTaskList;
    }

    @Override
    public TSTaskList saveNoticeAuditProcess(AICUser user, TSTaskList tsTaskList, ExpelledBizInfo noticeInfo, TSOpinion opinion, String nextNodeId, String[] nextPerformerIds, String[] nextPerformerNames) {
        try {
            if (StringUtils.isNotBlank(tsTaskList.getAcceptgroupid())) {
                workFlowService.claimGroup(tsTaskList.getWorkflowid(), user.getPrimaryKey());
            }
            tsTaskListService.updateWorkFlow(user, opinion, tsTaskList, nextNodeId, nextPerformerIds, nextPerformerNames);
            noticeInfo.setRemoveTime(LocalDate.now()); // 核准时间
            noticeInfo.setRemoveOrgNo(user.getRegionID());
            noticeInfo.setRemoveOrgName(user.getOrgName());
            saveOrUpdate(noticeInfo);
            List<ExpelledEntInfo> entInfos = expelledEntInfoService.searchEntInfoByBizId(noticeInfo.getId());
            if (!CollectionUtils.isEmpty(entInfos)) {
                for  (ExpelledEntInfo entInfo : entInfos) {
                    if (FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeId)) { // 完结时
                        entInfo.setStatus("0");
                    }
                    if (FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST.equals(nextNodeId) || FlowUtil.EXPTLISTWORKFLOW_OVERFINISH.equals(nextNodeId)) {
                        entInfo.setStatus("-1"); // 除名告知不通过，即是不建议
                        // 更新拟除名名单库状态为有效
                        EntBaseExpelledInfo expelledInfo = entBaseExpelledInfoService.getById(entInfo.getExpelledId());
                        if (expelledInfo != null) {
                            expelledInfo.setState("2"); // 有效
                            entBaseExpelledInfoService.saveOrUpdate(expelledInfo);
                        }
                    }
                    expelledEntInfoService.saveOrUpdate(entInfo);
                }
            }
            // 生成文书
            createApproveDoc(noticeInfo, tsTaskList);
        } catch (Exception e) {
            log.error("除名告知流程审核出错", e);
            throw new BusinessException("除名告知流程审核出错");
        }
        return tsTaskList;
    }

    @Override
    public ExpelledBizInfo getExpelledBizInfoByBizNo(String bizNo) {
        return getOne(new LambdaQueryWrapper<ExpelledBizInfo>().eq(ExpelledBizInfo::getBizNo, bizNo));
    }

    @Override
    public String generateBizNo() {
        String bizNo = DocumentNoGenerator.generateBizNo();
        ExpelledBizInfo bizInfo = getExpelledBizInfoByBizNo(bizNo);
        if (bizInfo == null) {
            return bizNo;
        }
        return generateBizNo();
    }

    @Override
    public IPage<BizInfoVo> listTodoNoticeInfo(BaseQuery<BizInfoVo> query) {
        BizInfoVo entity = query.getEntity(BizInfoVo.class);
        Page<BizInfoVo> page = query.getPage();
        return baseMapper.listTodoNoticeInfo(page, entity);
    }

    @Override
    public void createApproveDoc(ExpelledBizInfo noticeInfo, TSTaskList tsTaskList) {
        Map<String, Object> map = new HashMap<>();
        map.put("orgName", noticeInfo.getRemoveOrgName());
        // 拟除名企业信息
        BizInfoVo query = new BizInfoVo();
        query.setId(noticeInfo.getId());
        List<BizInfoVo> entInfos = baseMapper.listNoticeEntBaseInfo(query);
        String entNames = "";
        if (!CollectionUtils.isEmpty(entInfos)) {
            for (int i = 0; i < entInfos.size(); i++) {
                if (i >= 3) {
                    continue;
                }
                entNames += entInfos.get(i).getEntName() + '、';
            }
            entNames = entNames.substring(0, entNames.length() - 1) + "等" + entInfos.size() + "户企业/个体户";
        }
        map.put("entNames", entNames);
        map.put("removeReason", new StringBuilder(noticeInfo.getTruth()).append(System.lineSeparator()).append(noticeInfo.getReason()).append(System.lineSeparator()).append(noticeInfo.getLaw()).toString());
        // 获取历史审批意见
        LambdaQueryWrapper<TSOpinion> opinionWrapper = new LambdaQueryWrapper<>();
        opinionWrapper.eq(TSOpinion::getBizseq, noticeInfo.getId())
                .in(TSOpinion::getOpiniontype,"0", "1", "2")
                .orderByAsc(TSOpinion::getHandledate);
        List<TSOpinion> tsOpinions = opinionService.list(opinionWrapper);
        for (TSOpinion item : tsOpinions) {
            int index = Integer.parseInt(item.getOpiniontype()) + 1;
            map.put("opinion" + index, item.getOpinioncontent());
            map.put("handler" + index, item.getHandler());
            map.put("year" + index, item.getHandledate().getYear());
            map.put("month" + index, item.getHandledate().getMonthValue());
            map.put("day" + index, item.getHandledate().getDayOfMonth());
        }
        try {
            // 文书模板路径
            String wordTemplatePath = "static" + File.separator + "template" + File.separator + "expelled" + File.separator + "noticeDoc.docx";
            String resource = this.getClass().getClassLoader().getResource(wordTemplatePath).getPath();
            // URL解码
            resource = URLDecoder.decode(resource, "UTF-8");
            String realPath = CommonConfig.getUploadPath(); // 存储路径
            String docName = UUID.randomUUID().toString(); // 文件名
            TSAttachment tsAttachment = attachmentService.getByBizseqAndType(noticeInfo.getId(), "1");
            if (tsAttachment == null) {
                tsAttachment = new TSAttachment();
                tsAttachment.setAttachmentid(UUID.randomUUID().toString());
                tsAttachment.setUploaddate(LocalDate.now());
            } else {
                realPath = CommonConfig.getUploadPathByDate(tsAttachment.getUploaddate());
                docName = tsAttachment.getFilename().substring(0, tsAttachment.getFilename().lastIndexOf("."));
            }
            realPath += File.separator + noticeInfo.getId();
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 生成
            XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + docName + ".docx");
            // 保存记录
            String ext = ".docx";
            String fileName = docName + ext;
            String tempPath = noticeInfo.getId() + File.separator + fileName;
            tsAttachment.setCreatetype("1"); // 文件为系统生成
            tsAttachment.setBizseq(noticeInfo.getId());
            tsAttachment.setFileext(ext);
            tsAttachment.setFilename(fileName);
            tsAttachment.setTemppath(tempPath);
            tsAttachment.setAttachtype("1"); // 审批表
            attachmentService.saveOrUpdate(tsAttachment);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void createNoticeDoc(ExpelledEntInfo entInfo) {
        Map<String, Object> map = new HashMap<>();
        ExpelledBizInfo noticeInfo = getById(entInfo.getBizId());
        if (noticeInfo == null) {
            throw new BusinessException("除名告知业务信息不存在，请联系管理员");
        }
        map.put("orgName", noticeInfo.getRemoveOrgName());
        map.put("noticeNo", entInfo.getNoticeNo());
        EntBaseExpelledInfo expelledInfo = entBaseExpelledInfoService.getById(entInfo.getExpelledId());
        if (expelledInfo == null) {
            throw new BusinessException("拟除名企业信息不存在，请联系管理员");
        }
        map.put("entName", expelledInfo.getEntName());
        map.put("year", noticeInfo.getRemoveTime().getYear());
        map.put("month", noticeInfo.getRemoveTime().getMonthValue());
        map.put("day", noticeInfo.getRemoveTime().getDayOfMonth());
        try {
            // 文书模板路径
            String wordTemplatePath = "static" + File.separator + "template" + File.separator + "expelled" + File.separator + "noticeEntDoc.docx";
            String resource = this.getClass().getClassLoader().getResource(wordTemplatePath).getPath();
            // URL解码
            resource = URLDecoder.decode(resource, "UTF-8");
            String realPath = CommonConfig.getUploadPath(); // 存储路径
            String docName = UUID.randomUUID().toString(); // 文件名
            TSAttachment tsAttachment = attachmentService.getByBizseqAndType(entInfo.getId(), "1");
            if (tsAttachment == null) {
                tsAttachment = new TSAttachment();
                tsAttachment.setAttachmentid(UUID.randomUUID().toString());
                tsAttachment.setUploaddate(LocalDate.now());
            } else {
                realPath = CommonConfig.getUploadPathByDate(tsAttachment.getUploaddate());
                docName = tsAttachment.getFilename().substring(0, tsAttachment.getFilename().lastIndexOf("."));
            }
            realPath += File.separator + entInfo.getId();
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 生成
            XWPFTemplate.compile(resource).render(map).writeToFile(realPath + File.separator + docName + ".docx");
            // 保存记录
            String ext = ".docx";
            String fileName = docName + ext;
            String tempPath = entInfo.getId() + File.separator + fileName;
            tsAttachment.setCreatetype("1"); // 文件为系统生成
            tsAttachment.setBizseq(entInfo.getId());
            tsAttachment.setFileext(ext);
            tsAttachment.setFilename(fileName);
            tsAttachment.setTemppath(tempPath);
            tsAttachment.setAttachtype("2"); // 除名告知书
            attachmentService.saveOrUpdate(tsAttachment);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadNoticeDoc(HttpServletResponse response, String noticeNo) {
        ExpelledEntInfo entInfo = expelledEntInfoService.getExpelledEntInfo(noticeNo);
        if (entInfo == null) {
            return;
        }
        TSAttachment tsAttachment = attachmentService.getByBizseqAndType(entInfo.getId(), "2");
        if (tsAttachment == null) {
            createNoticeDoc(entInfo);
            tsAttachment = attachmentService.getByBizseqAndType(entInfo.getId(), "2");
            if (tsAttachment == null) {
                return;
            }
        }
        // 获取流
        InputStream is = null;
        OutputStream os = null;
        try {
            // 获取文件
            String realPath = CommonConfig.getUploadPathByDate(tsAttachment.getUploaddate()) + File.separator + tsAttachment.getTemppath();
            is = new FileInputStream(realPath);
            os = response.getOutputStream();
            String fileName = new String(tsAttachment.getFilename().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            // 设置：当浏览器收到这份资源的时候，以下载的方式提醒用户，而不是直接显示
            response.setHeader("Content-Disposition", "attachment;  filename=\"" + fileName + "\"");
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文书时发生异常:{}=", e);
            return;
        } finally {
            try {
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
