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.core.toolkit.Wrappers;
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.ExpelledApplyInfo;
import com.chinaweal.aiccs.aiccs.expelled.entity.ExpelledAuditInfo;
import com.chinaweal.aiccs.aiccs.expelled.entity.ExpelledResultInfo;
import com.chinaweal.aiccs.aiccs.expelled.mapper.ExpelledApplyInfoMapper;
import com.chinaweal.aiccs.aiccs.expelled.service.IEntBaseExpelledInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledApplyInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledAuditInfoService;
import com.chinaweal.aiccs.aiccs.expelled.service.IExpelledResultInfoService;
import com.chinaweal.aiccs.aiccs.expelled.vo.AuditInfoVo;
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.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.collections.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/8 10:24
 */
@Service
public class ExpelledApplyInfoServiceImpl extends ServiceImpl<ExpelledApplyInfoMapper, ExpelledApplyInfo> implements IExpelledApplyInfoService {

    @Resource
    private TSTaskListService tsTaskListService;
    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private TSOpinionService opinionService;
    @Resource
    private IExpelledResultInfoService expelledResultInfoService;
    @Resource
    private IExpelledAuditInfoService expelledAuditInfoService;
    @Resource
    private TSAttachmentService attachmentService;
    @Resource
    private IEntBaseExpelledInfoService entBaseExpelledInfoService;

    @Override
    public RestResult<?> startRepairBiz(AuditInfoVo query, HttpServletRequest request) {
        AICUser user = BaseController.getLoginUser(request);
        if (user == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        ExpelledResultInfo resultInfo = expelledResultInfoService.getById(query.getResultId());
        if (resultInfo == null) {
            throw new BusinessException("市场主体拟除名结果信息不存在，请联系管理员");
        }
        Map<String, Object> resultMap = new HashMap<>();
        String bizId = UUID.randomUUID().toString();
        // 添加待办启动流程
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizId);
        tsTaskList.setBustype(BaseDataConstant.BUSINESS_TYPE_REMOVE_REPAIR); // 除名修复
        tsTaskList.setBusname(query.getEntName());
        // 保存除名修复数据
        ExpelledApplyInfo applyInfo = new ExpelledApplyInfo();
        applyInfo.setAuditId(query.getAuditId());
        applyInfo.setResultId(query.getResultId());
        applyInfo.setBizId(bizId);
        applyInfo.setApplyDate(LocalDate.now());
        applyInfo.setRemoveReason(query.getAuditOpinion());
        applyInfo.setRemoveDate(query.getRemoveDate());
        applyInfo.setRemoveOrgNo(query.getRemoveOrgNo());
        applyInfo.setRemoveOrgName(query.getRemoveOrgName());
        applyInfo.setEntName(query.getEntName());
        applyInfo.setUscc(query.getUscc());
        applyInfo.setLerepName(query.getLerepName());
        applyInfo.setAddress(query.getAddress());
        applyInfo.setState("11"); // 修复中
        // 保存业务待办信息
        tsTaskList = startApplyBizAccept(user, tsTaskList, applyInfo);
        List<SequenceFlowModel> nextSequenceFlows = workFlowService.findNextSequenceFlowList(tsTaskList.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(tsTaskList.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) {
            opinionType = "1";
        }
        // 更新除名结果表信息
        resultInfo.setState("11"); // 修复中
        expelledResultInfoService.saveOrUpdate(resultInfo);
        resultMap.put("repairInfo", applyInfo);
        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<?> getRepairBiz(String bizId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 除名修复业务表
        ExpelledApplyInfo applyInfo = getExpelledApplyInfoByBizId(bizId);
        if (applyInfo == null) {
            throw new BusinessException("除名修复业务信息不存在，请联系管理员");
        }
        resultMap.put("repairInfo", applyInfo);
        // 除名业务待办
        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<?> nextRepairBiz(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();
        ExpelledApplyInfo applyInfoQuery = removeApproveInfo.getApplyInfoQuery();
        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 (!FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeId)) {
//            if (StringUtils.isBlank(nextPerformerIds)) {
//                throw new BusinessException("nextPerformerIds参数缺失");
//            }
//            if (StringUtils.isBlank(nextPerformerNames)) {
//                throw new BusinessException("nextPerformerNames参数缺失");
//            }
//        }
        if (applyInfoQuery == null) {
            throw new BusinessException("applyInfoQuery参数缺失");
        }
//        if (StringUtils.equals("handleExptlist", nextNodeId)
//                || StringUtils.equals("overFinish", nextNodeId)) {
//            if (removeApproveInfo != null
//                    && StringUtils.isNotBlank(removeApproveInfo.getBizId())) {
//                // TODO
//            }
//        }
        Map<String, Object> resultMap = new HashMap<>();
        ExpelledApplyInfo applyInfo = getExpelledApplyInfoByBizId(bizId);
        if (applyInfo == null) {
            throw new BusinessException("除名修复业务信息不存在，请联系管理员");
        }
        // 更新除名修复业务表
        if (applyInfoQuery != null && StringUtils.isNotBlank(applyInfoQuery.getBizId())) {
            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(applyInfoQuery, applyInfo);
                }
            }

            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 (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 = saveApplyAuditProcess(user, tsTaskList, applyInfo, 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 RestResult<?> startReviewBiz(AuditInfoVo query, HttpServletRequest request) {
        AICUser user = BaseController.getLoginUser(request);
        if (user == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        ExpelledResultInfo resultInfo = expelledResultInfoService.getById(query.getResultId());
        if (resultInfo == null) {
            throw new BusinessException("市场主体拟除名结果信息不存在，请联系管理员");
        }
        Map<String, Object> resultMap = new HashMap<>();
        String bizId = UUID.randomUUID().toString();
        // 添加待办启动流程
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizId);
        tsTaskList.setBustype(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVIEW); // 除名复议
        tsTaskList.setBusname(query.getEntName());
        // 保存除名复议数据
        ExpelledApplyInfo applyInfo = new ExpelledApplyInfo();
        applyInfo.setAuditId(query.getAuditId());
        applyInfo.setResultId(query.getResultId());
        applyInfo.setBizId(bizId);
        applyInfo.setApplyDate(LocalDate.now());
        applyInfo.setRemoveReason(query.getAuditOpinion());
        applyInfo.setRemoveDate(query.getRemoveDate());
        applyInfo.setRemoveOrgNo(query.getRemoveOrgNo());
        applyInfo.setRemoveOrgName(query.getRemoveOrgName());
        applyInfo.setEntName(query.getEntName());
        applyInfo.setUscc(query.getUscc());
        applyInfo.setLerepName(query.getLerepName());
        applyInfo.setAddress(query.getAddress());
        applyInfo.setState("12"); // 复议中
        // 保存业务待办信息
        tsTaskList = startApplyBizAccept(user, tsTaskList, applyInfo);
        List<SequenceFlowModel> nextSequenceFlows = workFlowService.findNextSequenceFlowList(tsTaskList.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(tsTaskList.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) {
            opinionType = "1";
        }
        // 更新除名结果表信息
        resultInfo.setState("12"); // 复议中
        expelledResultInfoService.saveOrUpdate(resultInfo);
        resultMap.put("reviewInfo", applyInfo);
        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<?> getReviewBiz(String bizId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 除名复议业务表
        ExpelledApplyInfo applyInfo = getExpelledApplyInfoByBizId(bizId);
        if (applyInfo == null) {
            throw new BusinessException("除名复议业务信息不存在，请联系管理员");
        }
        resultMap.put("reviewInfo", applyInfo);
        // 除名业务待办
        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<?> nextReviewBiz(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();
        ExpelledApplyInfo applyInfoQuery = removeApproveInfo.getApplyInfoQuery();
        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 (!FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeId)) {
//            if (StringUtils.isBlank(nextPerformerIds)) {
//                throw new BusinessException("nextPerformerIds参数缺失");
//            }
//            if (StringUtils.isBlank(nextPerformerNames)) {
//                throw new BusinessException("nextPerformerNames参数缺失");
//            }
//        }
        if (applyInfoQuery == null) {
            throw new BusinessException("applyInfoQuery参数缺失");
        }
//        if (StringUtils.equals("handleExptlist", nextNodeId)
//                || StringUtils.equals("overFinish", nextNodeId)) {
//            if (removeApproveInfo != null
//                    && StringUtils.isNotBlank(removeApproveInfo.getBizId())) {
//                // TODO
//            }
//        }
        Map<String, Object> resultMap = new HashMap<>();
        ExpelledApplyInfo applyInfo = getExpelledApplyInfoByBizId(bizId);
        if (applyInfo == null) {
            throw new BusinessException("除名复议业务信息不存在，请联系管理员");
        }
        // 更新除名复议业务表
        if (applyInfoQuery != null && StringUtils.isNotBlank(applyInfoQuery.getBizId())) {
            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(applyInfoQuery, applyInfo);
                }
            }

            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 (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 = saveApplyAuditProcess(user, tsTaskList, applyInfo, 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 RestResult<?> startRevokeBiz(AuditInfoVo query, HttpServletRequest request) {
        AICUser user = BaseController.getLoginUser(request);
        if (user == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        ExpelledResultInfo resultInfo = expelledResultInfoService.getById(query.getResultId());
        if (resultInfo == null) {
            throw new BusinessException("市场主体拟除名结果信息不存在，请联系管理员");
        }
        Map<String, Object> resultMap = new HashMap<>();
        String bizId = UUID.randomUUID().toString();
        // 添加待办启动流程
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizId);
        tsTaskList.setBustype(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVOKE); // 除名撤销
        tsTaskList.setBusname(query.getEntName());
        // 保存除名撤销数据
        ExpelledApplyInfo applyInfo = new ExpelledApplyInfo();
        applyInfo.setAuditId(query.getAuditId());
        applyInfo.setResultId(query.getResultId());
        applyInfo.setBizId(bizId);
        applyInfo.setApplyDate(LocalDate.now());
        applyInfo.setRemoveReason(query.getAuditOpinion());
        applyInfo.setRemoveDate(query.getRemoveDate());
        applyInfo.setRemoveOrgNo(query.getRemoveOrgNo());
        applyInfo.setRemoveOrgName(query.getRemoveOrgName());
        applyInfo.setEntName(query.getEntName());
        applyInfo.setUscc(query.getUscc());
        applyInfo.setLerepName(query.getLerepName());
        applyInfo.setAddress(query.getAddress());
        applyInfo.setState("13"); // 撤销中
        // 保存业务待办信息
        tsTaskList = startApplyBizAccept(user, tsTaskList, applyInfo);
        List<SequenceFlowModel> nextSequenceFlows = workFlowService.findNextSequenceFlowList(tsTaskList.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(tsTaskList.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) {
            opinionType = "1";
        }
        // 更新除名结果表信息
        resultInfo.setState("13"); // 撤销中
        expelledResultInfoService.saveOrUpdate(resultInfo);
        resultMap.put("revokeInfo", applyInfo);
        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<?> getRevokeBiz(String bizId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 除名撤销业务表
        ExpelledApplyInfo applyInfo = getExpelledApplyInfoByBizId(bizId);
        if (applyInfo == null) {
            throw new BusinessException("除名撤销业务信息不存在，请联系管理员");
        }
        resultMap.put("revokeInfo", applyInfo);
        // 除名业务待办
        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<?> nextRevokeBiz(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();
        ExpelledApplyInfo applyInfoQuery = removeApproveInfo.getApplyInfoQuery();
        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 (!FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeId)) {
//            if (StringUtils.isBlank(nextPerformerIds)) {
//                throw new BusinessException("nextPerformerIds参数缺失");
//            }
//            if (StringUtils.isBlank(nextPerformerNames)) {
//                throw new BusinessException("nextPerformerNames参数缺失");
//            }
//        }
        if (applyInfoQuery == null) {
            throw new BusinessException("applyInfoQuery参数缺失");
        }
//        if (StringUtils.equals("handleExptlist", nextNodeId)
//                || StringUtils.equals("overFinish", nextNodeId)) {
//            if (removeApproveInfo != null
//                    && StringUtils.isNotBlank(removeApproveInfo.getBizId())) {
//                // TODO
//            }
//        }
        Map<String, Object> resultMap = new HashMap<>();
        ExpelledApplyInfo applyInfo = getExpelledApplyInfoByBizId(bizId);
        if (applyInfo == null) {
            throw new BusinessException("除名撤销业务信息不存在，请联系管理员");
        }
        // 更新除名撤销业务表
        if (applyInfoQuery != null && StringUtils.isNotBlank(applyInfoQuery.getBizId())) {
            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(applyInfoQuery, applyInfo);
                }
            }

            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 (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 = saveApplyAuditProcess(user, tsTaskList, applyInfo, 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 ExpelledApplyInfo getExpelledApplyInfoByBizId(String bizId) {
        return getOne(new LambdaQueryWrapper<ExpelledApplyInfo>().eq(ExpelledApplyInfo::getBizId, bizId));
    }

    @Override
    public TSTaskList startApplyBizAccept(AICUser user, TSTaskList tsTaskList, ExpelledApplyInfo applyInfo) {
        if (StringUtils.isBlank(tsTaskList.getTasklistid())) {
            applyInfo.setId(UUID.randomUUID().toString());
            applyInfo.setLinkType("1");
            saveOrUpdate(applyInfo);
            String definedname = FlowUtil.EXPTLISTWORKFLOW; // 除名申请（修复、复议、撤销），这类参考使用企业经营异常名录流程模板，应该是可以的吧
            // 新待办
            tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, user);
            // 开始工作流
            tsTaskListService.startWorkFlow(tsTaskList, user, definedname);
        }
        return tsTaskList;
    }

    @Override
    public TSTaskList saveApplyAuditProcess(AICUser user, TSTaskList tsTaskList, ExpelledApplyInfo applyInfo, 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);
            if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeId)) { // 审批
                applyInfo.setLinkType("3"); // 审批流程中把状态设置成"审批中"
            }
            LocalDate now = LocalDate.now();
            ExpelledResultInfo resultInfo = expelledResultInfoService.getById(applyInfo.getResultId());
            if (FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeId)) { // 完结时
                // 同步更新拟除名名单库状态
                entBaseExpelledInfoService.syncEntBaseExpelledInfo(resultInfo.getId(), "2");
                applyInfo.setApproveDate(now); // 核准时间
                applyInfo.setLinkType("4"); // 1-受理中，2-审核中，3-审批中，4-通过，5-不通过
                if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REPAIR, tsTaskList.getBustype())) {
                    applyInfo.setState("91"); // 修复完成
                    resultInfo.setState("91"); // 修复完成
                } else if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVIEW, tsTaskList.getBustype())) {
                    applyInfo.setState("92"); // 复议通过被动撤销完成
                    resultInfo.setState("92"); // 复议通过被动撤销完成
                } else if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVOKE, tsTaskList.getBustype())) {
                    applyInfo.setState("93"); // 主动撤销完成
                    resultInfo.setState("93"); // 主动撤销完成
                }
            }
            if (FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST.equals(nextNodeId)) {
                applyInfo.setApproveDate(now); // 核准时间
                applyInfo.setLinkType("5"); // 1-受理中，2-审核中，3-审批中，4-通过，5-不通过
                resultInfo.setState("10"); // 恢复有效
                if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REPAIR, tsTaskList.getBustype())) {
                    applyInfo.setState("61"); // 修复不通过
                } else if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVIEW, tsTaskList.getBustype())) {
                    applyInfo.setState("62"); // 复议不通过
                } else if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVOKE, tsTaskList.getBustype())) {
                    applyInfo.setState("63"); // 撤销不通过
                }
            }
            if (FlowUtil.EXPTLISTWORKFLOW_OVERFINISH.equals(nextNodeId)) {
                applyInfo.setApproveDate(now); // 核准时间
                applyInfo.setLinkType("5"); // 1-受理中，2-审核中，3-审批中，4-通过，5-不通过
                resultInfo.setState("10"); // 恢复有效
                if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REPAIR, tsTaskList.getBustype())) {
                    applyInfo.setState("61"); // 修复不通过
                } else if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVIEW, tsTaskList.getBustype())) {
                    applyInfo.setState("62"); // 复议不通过
                } else if (StringUtils.equals(BaseDataConstant.BUSINESS_TYPE_REMOVE_REVOKE, tsTaskList.getBustype())) {
                    applyInfo.setState("63"); // 撤销不通过
                }
            }
            expelledResultInfoService.saveOrUpdate(resultInfo);
            saveOrUpdate(applyInfo);
            // 生成文书
            createApproveDoc(applyInfo, tsTaskList);
        } catch (Exception e) {
            log.error("除名申请（修复、复议、撤销）流程审核出错", e);
            throw new BusinessException("除名申请（修复、复议、撤销）流程审核出错");
        }
        return tsTaskList;
    }

    @Override
    public IPage<ExpelledApplyInfo> listRevokeAnnouncement(BaseQuery<ExpelledApplyInfo> query) {
        ExpelledApplyInfo entity = query.getEntity(ExpelledApplyInfo.class);
        Page<ExpelledApplyInfo> page = query.getPage();
        LambdaQueryWrapper<ExpelledApplyInfo> wrapper = Wrappers.<ExpelledApplyInfo>lambdaQuery()
                .like(StringUtils.isNotBlank(entity.getEntName()), ExpelledApplyInfo::getEntName, entity.getEntName())
                .eq(StringUtils.isNotBlank(entity.getUscc()), ExpelledApplyInfo::getUscc, entity.getUscc())
                .in(ExpelledApplyInfo::getState, "92", "93");
        return page(page, wrapper);
    }

    @Override
    public void createApproveDoc(ExpelledApplyInfo applyInfo, TSTaskList tsTaskList) {
        Map<String, Object> map = new HashMap<>();
        map.put("orgName", applyInfo.getRemoveOrgName());
        map.put("entName", applyInfo.getEntName());
        map.put("uscc", applyInfo.getUscc());
        map.put("lerepName", applyInfo.getLerepName());
        map.put("address",  applyInfo.getAddress());
        ExpelledAuditInfo auditInfo = expelledAuditInfoService.getById(applyInfo.getAuditId());
        if (auditInfo != null) {
            map.put("docNo", auditInfo.getAuditNo());
        }
        map.put("approveDate", applyInfo.getApproveDate());
        map.put("applyReason", applyInfo.getApplyReason());
        // 获取历史审批意见
        LambdaQueryWrapper<TSOpinion> opinionWrapper = new LambdaQueryWrapper<>();
        opinionWrapper.eq(TSOpinion::getBizseq, applyInfo.getBizId())
                .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 + "repairDoc.docx";
            if (StringUtils.equals("92", applyInfo.getState()) || StringUtils.equals("93", applyInfo.getState())) {
                wordTemplatePath = "static" + File.separator + "template" + File.separator + "expelled" + File.separator + "revokeDoc.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(applyInfo.getBizId(), "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 + applyInfo.getBizId();
            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 = applyInfo.getBizId() + File.separator + fileName;
            tsAttachment.setCreatetype("1"); // 文件为系统生成
            tsAttachment.setBizseq(applyInfo.getBizId());
            tsAttachment.setFileext(ext);
            tsAttachment.setFilename(fileName);
            tsAttachment.setTemppath(tempPath);
            tsAttachment.setAttachtype("1"); // 审批表
            attachmentService.saveOrUpdate(tsAttachment);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadApproveDoc(HttpServletResponse response, String bizId, String attachType) {
        TSAttachment tsAttachment = attachmentService.getByBizseqAndType(bizId, attachType);
        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();
            }
        }
    }
}
