package com.chinaweal.aiccs.aiccs.seriousillegal.controller;

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.chinaweal.aiccs.aiccs.abnormal.entity.EPriPerson;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.EPriPersonService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
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.claim.entity.TSEntBase;
import com.chinaweal.aiccs.aiccs.claim.service.TSEntBaseService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.EOtIlldisdetail;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.EOtIlldisdetailTemp;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.*;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.vo.ApprovalPageVo;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.vo.PrintTSWritVo;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.vo.TaskDetailVo;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.vo.TaskSubmitResultVo;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IEOtIlldisdetailService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.IEOtIlldisdetailTempService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.CommonConstants;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 其他部门列入严重违法失信企业名单（黑名单）详细信息表
 *
 * @author lroyia
 * @since 2026/3/9 9:53
 **/
@Slf4j
@Api(tags = "其他部门列入严重违法失信企业名单（黑名单）")
@RestController
@RequestMapping("/eOtIlldisdetail")
public class EOtIlldisdetailController extends BaseController {

    @Autowired
    private IEOtIlldisdetailService eOtIlldisdetailService;

    @Autowired
    private IEOtIlldisdetailTempService eOtIlldisdetailTempService;

    @Autowired
    private TSTaskListService taskListService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private TSOpinionService opinionService;

    @Autowired
    private TSEntBaseService tsEntBaseService;

    @Autowired
    private TRBaseCodeService baseCodeService;

    @Autowired
    private EPriPersonService priPersonService;

    @Autowired
    private TSWritService tsWritService;

    /**
     * 列入严重违法失信企业名单（黑名单）-受理
     */
    @Transactional
    @ApiOperation("其他部门列入严重违法失信企业名单（黑名单）-受理")
    @PostMapping("/enterAccept")
    public RestResult<TaskSubmitResultVo> enterAccept(HttpServletRequest request,
                                                      @RequestBody EnterAcceptDto dto) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 验证必填项
        if (StringUtils.isBlank(dto.getInfotype())) {
            throw new BusinessException("业务类别不能为空");
        }
        if (StringUtils.isBlank(dto.getSerillrea())) {
            throw new BusinessException("列入事由不能为空");
        }
        if (dto.getAbntime() == null) {
            throw new BusinessException("列入时间不能为空");
        }
        if (dto.getPripidList() == null || dto.getPripidList().isEmpty()) {
            throw new BusinessException("列入市场主体主键名单不能为空");
        }

        // 查询列入事由对应的中文名称
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        TRBaseCode serillreaCode = codeMap.get(dto.getSerillrea());
        if (serillreaCode == null) {
            throw new BusinessException("未找到列入事由代码为 " + dto.getSerillrea() + " 的代码表记录");
        }
        String serillreaCn = serillreaCode.getName();

        // 根据pripidList查询企业基础信息，生成EOtIlldisdetailTemp列表
        List<EOtIlldisdetailTemp> bizList = new ArrayList<>();
        for (String pripid : dto.getPripidList()) {
            // 查询企业基础信息
            TSEntBase entBase = tsEntBaseService.findTsentbaseByID(pripid);
            if (entBase == null) {
                throw new BusinessException("未找到主体身份代码为 " + pripid + " 的企业信息");
            }

            // 查询法人信息（lerepsign=1）
            EPriPerson legalPerson = priPersonService.lambdaQuery()
                    .eq(EPriPerson::getPripid, pripid)
                    .eq(EPriPerson::getLerepsign, "1")
                    .one();

            // 创建业务记录
            EOtIlldisdetailTemp tempRecord = new EOtIlldisdetailTemp();
            tempRecord.setPripid(entBase.getPripid());
            tempRecord.setUniscid(entBase.getUscc());
            tempRecord.setRegno(entBase.getRegno());
            tempRecord.setEntname(entBase.getEntname());
            tempRecord.setName(legalPerson != null ? legalPerson.getName() : null);
            tempRecord.setCerno(legalPerson != null ? legalPerson.getCerno() : null);
            tempRecord.setCertype(legalPerson != null ? legalPerson.getCertype() : null);
            tempRecord.setInfotype(dto.getInfotype());
            tempRecord.setSerillrea(dto.getSerillrea());
            tempRecord.setSerillreaCn(serillreaCn);
            tempRecord.setAbntime(dto.getAbntime());

            bizList.add(tempRecord);
        }

        // 生成业务号
        String bizSeq = UUID.randomUUID().toString();

        // 创建待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_ENTER);

        // 保存业务并启动工作流
        taskListModel = eOtIlldisdetailService.saveEnterAccept(user, taskListModel, bizList);

        TaskSubmitResultVo result = new TaskSubmitResultVo();
        result.setTasklistid(taskListModel.getTasklistid());
        result.setBizseq(bizSeq);
        result.setWorkflowId(taskListModel.getWorkflowid());

        return RestResult.ok(result);
    }

    /**
     * 移出严重违法失信企业名单（黑名单）-受理
     */
    @Transactional
    @ApiOperation("其他部门移出严重违法失信企业名单（黑名单）-受理")
    @PostMapping("/removeAccept")
    public RestResult<TaskSubmitResultVo> removeAccept(HttpServletRequest request,
                                                       @RequestBody RemoveAcceptDto dto) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 验证必填项
        if (dto.getIllidList() == null || dto.getIllidList().isEmpty()) {
            throw new BusinessException("移出记录清单不能为空");
        }
        if (StringUtils.isBlank(dto.getRemexcpres())) {
            throw new BusinessException("移出事由不能为空");
        }
        if (dto.getRemdate() == null) {
            throw new BusinessException("移出日期不能为空");
        }

        // 查询移出事由对应的中文名称
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD74");
        TRBaseCode remexcpresCode = codeMap.get(dto.getRemexcpres());
        if (remexcpresCode == null) {
            throw new BusinessException("未找到移出事由代码为 " + dto.getRemexcpres() + " 的代码表记录");
        }
        String remexcpresCn = remexcpresCode.getName();

        // 生成业务号
        String bizSeq = UUID.randomUUID().toString();

        // 创建待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_REMOVE);

        // 保存业务并启动工作流
        taskListModel = eOtIlldisdetailService.saveRemoveAccept(user, taskListModel, dto, remexcpresCn);

        TaskSubmitResultVo result = new TaskSubmitResultVo();
        result.setTasklistid(taskListModel.getTasklistid());
        result.setBizseq(bizSeq);
        result.setWorkflowId(taskListModel.getWorkflowid());

        return RestResult.ok(result);
    }

    /**
     * 获取审批页面信息
     */
    @ApiOperation("获取审批页面信息")
    @GetMapping("/approvalPage")
    public RestResult<ApprovalPageVo> approvalPage(@ApiParam("待办ID") @RequestParam String tasklistid) {
        TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
        if (taskListModel == null) {
            throw new BusinessException("待办记录不存在");
        }

        // 查询业务记录
        List<EOtIlldisdetailTemp> bizList = eOtIlldisdetailTempService.listByBizSeq(taskListModel.getBizseqid());

        // 查询下一节点
        List<SequenceFlowModel> nextSequenceFlowList = workFlowService.findNextSequenceFlowList(taskListModel.getWorkflowid());

        // 查询当前节点
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());

        // 获取意见类型
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) {
            opinionType = "1";
        }

        // 查询审批意见
        List<TSOpinion> opinionList = null;
        if (taskListModel.getWorkflowid() != null) {
            opinionList = opinionService.selectByAuditingID(taskListModel.getWorkflowid());
        }

        ApprovalPageVo result = new ApprovalPageVo();
        result.setTasklistid(tasklistid);
        result.setBizSeq(taskListModel.getBizseqid());
        result.setWorkflowId(taskListModel.getWorkflowid());
        result.setBizList(bizList);
        result.setNextSequenceFlowList(nextSequenceFlowList);
        result.setCurrentNode(currentNode.getCurrentnode());
        result.setCurrentNodeName(WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        result.setCurrentLinkTypeID(opinionType);
        result.setOpinionList(opinionList);
        result.setBustype(taskListModel.getBustype());

        return RestResult.ok(result);
    }

    /**
     * 提交审批
     */
    @Transactional
    @ApiOperation("提交审批")
    @PostMapping("/approval")
    public RestResult<TSTaskList> approval(HttpServletRequest request,
                                           @RequestBody ApprovalDto dto) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 查询待办
        TSTaskList taskListModel = taskListService.selectByTasklistID(dto.getTasklistid());
        if (taskListModel == null) {
            throw new BusinessException("待办记录不存在");
        }

        // 查询业务记录
        List<EOtIlldisdetailTemp> bizList = eOtIlldisdetailTempService.listByBizSeq(taskListModel.getBizseqid());
        if (bizList == null || bizList.isEmpty()) {
            throw new BusinessException("业务记录不存在");
        }

        // 处理人ID和姓名数组
        String[] nextPerformeridArray = dto.getNextPerformerids().split(",");
        String[] nextPerformerNameArray = dto.getNextPerformerNames().split(",");

        // 根据业务类型处理审批流程
        TSTaskList result;
        if (BaseDataConstant.SERILLEGAL_TYPE_OT_ENTER.equals(taskListModel.getBustype())) {
            // 列入业务审批
            result = eOtIlldisdetailTempService.handleEnterApprovalProcess(
                    user, taskListModel, bizList, dto.getOpinionModel(), dto.getNextNodeID(), nextPerformeridArray, nextPerformerNameArray);
        } else if (BaseDataConstant.SERILLEGAL_TYPE_OT_REMOVE.equals(taskListModel.getBustype())) {
            // 移出业务审批
            result = eOtIlldisdetailTempService.handleRemoveApprovalProcess(
                    user, taskListModel, bizList, dto.getOpinionModel(), dto.getNextNodeID(), nextPerformeridArray, nextPerformerNameArray);
        } else {
            throw new BusinessException("未知的业务类型");
        }

        return RestResult.ok(result);
    }

    /**
     * 根据业务号查询Temp表记录
     */
    @ApiOperation("根据业务号查询Temp表记录")
    @GetMapping("/listByBizSeq")
    public RestResult<List<EOtIlldisdetailTemp>> listByBizSeq(@ApiParam("业务号") @RequestParam String bizSeq) {
        List<EOtIlldisdetailTemp> list = eOtIlldisdetailTempService.listByBizSeq(bizSeq);
        return RestResult.ok(list);
    }

    /**
     * 根据ID查询正式表记录
     */
    @ApiOperation("根据ID查询正式表记录")
    @GetMapping("/getById")
    public RestResult<EOtIlldisdetail> getById(@ApiParam("主键ID") @RequestParam String illid) {
        EOtIlldisdetail detail = eOtIlldisdetailService.getById(illid);
        return RestResult.ok(detail);
    }

    /**
     * 根据ID查询Temp表记录
     */
    @ApiOperation("根据ID查询Temp表记录")
    @GetMapping("/getTempById")
    public RestResult<EOtIlldisdetailTemp> getTempById(@ApiParam("主键ID") @RequestParam String illid) {
        EOtIlldisdetailTemp temp = eOtIlldisdetailService.getTempById(illid);
        return RestResult.ok(temp);
    }

    /**
     * 根据主体信息查询正式表记录
     */
    @ApiOperation("根据主体信息查询正式表记录")
    @GetMapping("/getByPripid")
    public RestResult<List<EOtIlldisdetail>> getByPripid(@ApiParam("主体身份代码") @RequestParam String pripid) {
        List<EOtIlldisdetail> list = eOtIlldisdetailService.lambdaQuery()
                .eq(EOtIlldisdetail::getPripid, pripid)
                .list();
        return RestResult.ok(list);
    }

    /**
     * 作废待办
     */
    @Transactional
    @ApiOperation("作废待办")
    @PostMapping("/nullify")
    public RestResult<TSTaskList> nullify(HttpServletRequest request,
                                          @ApiParam("待办ID") @RequestParam String tasklistid,
                                          @ApiParam("作废原因") @RequestParam String reason) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 查询待办
        TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
        if (taskListModel == null) {
            throw new BusinessException("待办记录不存在");
        }

        // 校验当前用户是否为待办创建人
        if (StringUtils.notEquals(user.getPrimaryKey(), taskListModel.getCreateUserid())) {
            throw new BusinessException("非待办创建人无权作废待办");
        }

        // 保存作废意见
        TSOpinion opinion = new TSOpinion();
        opinion.setBizseq(taskListModel.getBizseqid());
        opinion.setOpiniontype(BaseDataConstant.OPINION_TYPE_ENTER);
        opinion.setHandler(user.getName());
        opinion.setHandlerid(user.getPrimaryKey());
        opinion.setHandledate(java.time.LocalDateTime.now());
        opinion.setOperOpinion("作废原因：" + reason);
        opinionService.save(opinion);

        // 作废工作流
        taskListService.updateWorkFlow(user, opinion, taskListModel, FlowUtil.SERIOUS_ILLEGAL_NULLIFY,
                new String[]{user.getPrimaryKey()}, new String[]{user.getEname()});

        return RestResult.ok(taskListModel);
    }

    /**
     * 查询外单位严重违法列入待办列表
     */
    @ApiOperation("查询外单位严重违法列入待办列表")
    @PostMapping("/enterTaskList")
    public RestResult<IPage<TSTaskList>> enterTaskList(HttpServletRequest request,
                                                       @RequestBody BaseQuery<TaskListTodoParam> baseQuery) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        TaskListTodoParam param = baseQuery.getEntity(TaskListTodoParam.class);
        param.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_ENTER);
        param.setCurrentUserId(user.getPrimaryKey());

        IPage<TSTaskList> result = eOtIlldisdetailTempService.getTaskListTodoPage(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), param);

        return RestResult.ok(result);
    }

    /**
     * 查询外单位严重违法列入已办记录
     */
    @ApiOperation("查询外单位严重违法列入已办记录")
    @PostMapping("/enterFinishedList")
    public RestResult<IPage<EOtIlldisdetailTemp>> enterFinishedList(HttpServletRequest request,
                                                                    @RequestBody BaseQuery<TaskListTodoParam> baseQuery) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        TaskListTodoParam param = baseQuery.getEntity(TaskListTodoParam.class);
        param.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_ENTER);
        param.setCurrentUserId(user.getPrimaryKey());

        return RestResult.ok(eOtIlldisdetailTempService.getTodoHistoryPage(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), param));
    }

    /**
     * 查询外单位严重违法移出待办列表
     */
    @ApiOperation("查询外单位严重违法移出待办列表")
    @PostMapping("/removeTaskList")
    public RestResult<IPage<TSTaskList>> removeTaskList(HttpServletRequest request,
                                                        @RequestBody BaseQuery<TaskListTodoParam> baseQuery) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        TaskListTodoParam param = baseQuery.getEntity(TaskListTodoParam.class);
        param.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_REMOVE);
        param.setCurrentUserId(user.getPrimaryKey());

        IPage<TSTaskList> result = eOtIlldisdetailTempService.getTaskListTodoPage(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), param);

        return RestResult.ok(result);
    }

    /**
     * 查询外单位严重违法移出已办记录
     */
    @ApiOperation("查询外单位严重违法移出已办记录")
    @PostMapping("/removeFinishedList")
    public RestResult<IPage<EOtIlldisdetailTemp>> removeFinishedList(HttpServletRequest request,
                                                                     @RequestBody BaseQuery<TaskListTodoParam> baseQuery) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        TaskListTodoParam param = baseQuery.getEntity(TaskListTodoParam.class);
        param.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_REMOVE);
        param.setCurrentUserId(user.getPrimaryKey());

        return RestResult.ok(eOtIlldisdetailTempService.getTodoHistoryPage(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), param));
    }

    /**
     * 按主体信息查询外单位严重违法记录
     */
    @ApiOperation("按主体信息查询外单位严重违法记录")
    @PostMapping("/searchByEntInfo")
    public RestResult<IPage<EOtIlldisdetail>> searchByEntInfo(@RequestBody BaseQuery<SearchByEntInfoQueryDto> baseQuery) {
        SearchByEntInfoQueryDto query = baseQuery.getEntity(SearchByEntInfoQueryDto.class);
        if (query == null) {
            query = new SearchByEntInfoQueryDto();
        }

        LambdaQueryWrapper<EOtIlldisdetail> wrapper =
                new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(query.getUniscid())) {
            wrapper.eq(EOtIlldisdetail::getUniscid, query.getUniscid());
        }
        if (StringUtils.isNotBlank(query.getRegno())) {
            wrapper.eq(EOtIlldisdetail::getRegno, query.getRegno());
        }
        if (StringUtils.isNotBlank(query.getEntname())) {
            wrapper.like(EOtIlldisdetail::getEntname, query.getEntname());
        }

        wrapper.orderByDesc(EOtIlldisdetail::getSExtDatetime);

        IPage<EOtIlldisdetail> result = eOtIlldisdetailService.page(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), wrapper);

        return RestResult.ok(result);
    }

    /**
     * 查询处于列入状态的外单位记录（用于移出业务）
     */
    @ApiOperation("查询处于列入状态的外单位记录")
    @PostMapping("/getEnteredRecords")
    public RestResult<IPage<EOtIlldisdetail>> getEnteredRecords(@RequestBody BaseQuery<GetEnteredRecordsQueryDto> baseQuery) {
        GetEnteredRecordsQueryDto query = baseQuery.getEntity(GetEnteredRecordsQueryDto.class);
        if (query == null) {
            query = new GetEnteredRecordsQueryDto();
        }

        LambdaQueryWrapper<EOtIlldisdetail> wrapper = new LambdaQueryWrapper<>();

        // 查询条件：remdate为空表示处于列入状态
        wrapper.isNull(EOtIlldisdetail::getRemdate);

        if (StringUtils.isNotBlank(query.getUniscid())) {
            wrapper.eq(EOtIlldisdetail::getUniscid, query.getUniscid());
        }
        if (StringUtils.isNotBlank(query.getRegno())) {
            wrapper.eq(EOtIlldisdetail::getRegno, query.getRegno());
        }
        if (StringUtils.isNotBlank(query.getEntname())) {
            wrapper.like(EOtIlldisdetail::getEntname, query.getEntname());
        }

        wrapper.orderByDesc(EOtIlldisdetail::getSExtDatetime);

        IPage<EOtIlldisdetail> result = eOtIlldisdetailService.page(new Page<>(baseQuery.getCurrent(), baseQuery.getSize()), wrapper);

        return RestResult.ok(result);
    }

    /**
     * 根据待办ID获取待办详情（包含业务数据）
     */
    @ApiOperation("根据待办ID获取待办详情")
    @GetMapping("/getTaskDetail")
    public RestResult<TaskDetailVo> getTaskDetail(@ApiParam("待办ID") @RequestParam String workflowid) {
        // 查询待办信息
        TSTaskList one = taskListService.lambdaQuery().eq(TSTaskList::getWorkflowid, workflowid).last("limit 1").one();
        if (one == null) {
            throw new BusinessException("待办记录不存在");
        }
        TSTaskList taskListModel = taskListService.selectByTasklistID(one.getTasklistid());
        if (taskListModel == null) {
            throw new BusinessException("待办记录不存在");
        }

        TaskDetailVo result = new TaskDetailVo();
        result.setTaskList(taskListModel);
        result.setBizInfo(eOtIlldisdetailTempService.lambdaQuery()
                .eq(StringUtils.equals(taskListModel.getBustype(), BaseDataConstant.SERILLEGAL_TYPE_OT_ENTER), EOtIlldisdetailTemp::getInBizseq, taskListModel.getBizseqid())
                .eq(StringUtils.equals(taskListModel.getBustype(), BaseDataConstant.SERILLEGAL_TYPE_OT_REMOVE), EOtIlldisdetailTemp::getOutBizseq, taskListModel.getBizseqid())
                .ne(EOtIlldisdetailTemp::getDstate, CommonConstants.DELETED_2).one());

        return RestResult.ok(result);
    }

    /**
     * 个案办理 - 外单位严重违法列入
     */
    @Transactional
    @ApiOperation("个案办理 - 外单位严重违法列入")
    @PostMapping("/enterCaseHandle")
    public RestResult<TaskSubmitResultVo> enterCaseHandle(HttpServletRequest request,
                                                          @RequestBody com.chinaweal.aiccs.aiccs.seriousillegal.entity.dto.EnterCaseHandleDto dto) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 验证必填项
        if (StringUtils.isBlank(dto.getUniscid()) && StringUtils.isBlank(dto.getRegno())) {
            throw new BusinessException("统一社会信用代码和注册号至少填写一个");
        }

        // 创建业务记录
        EOtIlldisdetailTemp tempRecord = new EOtIlldisdetailTemp();
        tempRecord.setUniscid(dto.getUniscid());
        tempRecord.setRegno(dto.getRegno());
        tempRecord.setEntname(dto.getEntname());
        tempRecord.setSerillrea(dto.getSerillrea());
        tempRecord.setSerillreaCn(dto.getSerillreaCn());
        tempRecord.setAbntime(dto.getAbntime());
        tempRecord.setRegorg(dto.getRegorg());
        tempRecord.setDecorg(dto.getDecorg());
        tempRecord.setDecorgCn(dto.getDecorgCn());
        tempRecord.setDedocnum(dto.getDedocnum());
        tempRecord.setInfotype(dto.getInfotype());
        tempRecord.setName(dto.getName());

        List<EOtIlldisdetailTemp> bizList = new ArrayList<>();
        bizList.add(tempRecord);

        // 保存业务并启动工作流
        String bizSeq = UUID.randomUUID().toString();
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_ENTER);
        taskListModel = eOtIlldisdetailService.saveEnterAccept(user, taskListModel, bizList);

        TaskSubmitResultVo result = new TaskSubmitResultVo();
        result.setTasklistid(taskListModel.getTasklistid());
        result.setBizseq(bizSeq);
        result.setWorkflowId(taskListModel.getWorkflowid());

        return RestResult.ok(result);
    }

    /**
     * 个案办理 - 外单位严重违法移出
     */
    @Transactional
    @ApiOperation("个案办理 - 外单位严重违法移出")
    @PostMapping("/removeCaseHandle")
    public RestResult<TaskSubmitResultVo> removeCaseHandle(HttpServletRequest request,
                                                           @RequestBody RemoveCaseHandleDto dto) {
        AICUser user = getLoginUser(request);
        if (user == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 验证必填项
        if (StringUtils.isBlank(dto.getIllid())) {
            throw new BusinessException("记录ID不能为空");
        }

//        // 查询移出事由对应的中文名称
//        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD74");
//        TRBaseCode remexcpresCode = codeMap.get(dto.getRemexcpres());
//        if (remexcpresCode == null) {
//            throw new BusinessException("未找到移出事由代码为 " + dto.getRemexcpres() + " 的代码表记录");
//        }
//        String remexcpresCn = remexcpresCode.getName();

        // 查询原始记录
        EOtIlldisdetail originalRecord = eOtIlldisdetailService.getById(dto.getIllid());
        if (originalRecord == null) {
            throw new BusinessException("原始记录不存在");
        }
        if (originalRecord.getRemdate() != null) {
            throw new BusinessException("该记录已被移出，不能重复移出");
        }

        // 创建移出业务记录
        EOtIlldisdetailTemp tempRecord = new EOtIlldisdetailTemp();
        // 使用原始illid，以便审批后能正确更新正式表中的对应记录
        tempRecord.setIllid(dto.getIllid());
        tempRecord.setPripid(originalRecord.getPripid());
        tempRecord.setUniscid(originalRecord.getUniscid());
        tempRecord.setRegno(originalRecord.getRegno());
        tempRecord.setEntname(originalRecord.getEntname());
//        tempRecord.setRemexcpres(dto.getRemexcpres());
//        tempRecord.setRemexcpresCn(remexcpresCn);
        tempRecord.setRemdate(dto.getRemdate());
        tempRecord.setRecorg(dto.getRecorg());
        tempRecord.setRecorgCn(dto.getRecorgCn());
        tempRecord.setRedocnum(dto.getRedocnum());

        List<EOtIlldisdetailTemp> bizList = new ArrayList<>();
        bizList.add(tempRecord);

        // 保存业务并启动工作流
        String bizSeq = UUID.randomUUID().toString();
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_OT_REMOVE);
        taskListModel = eOtIlldisdetailService.saveRemoveAccept(user, taskListModel, bizList);

        TaskSubmitResultVo result = new TaskSubmitResultVo();
        result.setTasklistid(taskListModel.getTasklistid());
        result.setBizseq(bizSeq);
        result.setWorkflowId(taskListModel.getWorkflowid());

        return RestResult.ok(result);
    }

    /**
     * 打印文书页面
     */
    @ApiOperation("打印文书页面")
    @PostMapping("/printTSWrit")
    public RestResult<PrintTSWritVo> printTSWrit(@RequestBody PrintTSWritDto dto) {
        PrintTSWritVo result = new PrintTSWritVo();

        if ("1".equals(dto.getPrintstatus())) {
            // 打印决定书
            EOtIlldisdetailTemp detail = eOtIlldisdetailTempService.getById(dto.getIllid());
            if (detail == null) {
                throw new BusinessException("记录不存在");
            }

            TSWrit writQueryModel = new TSWrit();
            if ("enter".equals(dto.getType())) {
                // 列入决定书
                writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_21);
                writQueryModel.setPripid(detail.getPripid());
                writQueryModel.setBizseq(detail.getInBizseq());
            } else if ("remove".equals(dto.getType())) {
                // 移出决定书
                writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_25);
                writQueryModel.setPripid(detail.getPripid());
                writQueryModel.setBizseq(detail.getOutBizseq());
            }

            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                result.setWrirsno(tsWritQueryModels.get(0).getWritsno());
            }

            result.setDetail(detail);
            result.setNowTime(LocalDate.now());
            if ("enter".equals(dto.getType())) {
                // 列入决定书需要加上届满日期
                if (detail.getAbntime() != null) {
                    result.setExpirationDate(detail.getAbntime().plusYears(5));
                }
            }

        } else if ("3".equals(dto.getPrintstatus())) {
            // 打印审批表
            TSTaskList taskListModel = taskListService.selectByWorkflowID(dto.getWorkflowid());
            if (taskListModel == null) {
                throw new BusinessException("待办记录不存在");
            }

            StringBuilder regno = new StringBuilder();
            StringBuilder ename = new StringBuilder();
            List<EOtIlldisdetailTemp> list = eOtIlldisdetailTempService.listByBizSeq(taskListModel.getBizseqid());

            if (list != null && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    if (i > 2) {
                        regno.append("等");
                        ename.append("等企业");
                        break;
                    }
                    if (i > 0) {
                        ename.append(", ");
                        regno.append(", ");
                    }
                    ename.append(list.get(i).getEntname());
                    regno.append(list.get(i).getUniscid() != null ? list.get(i).getUniscid() : list.get(i).getRegno());
                }
            }

            List<TSOpinion> opinionList = opinionService.selectByAuditingID(dto.getWorkflowid());
            result.setOpinionList(opinionList);
            result.setRegno(regno.toString());
            result.setEname(ename.toString());
            result.setList(list);
            if (list != null && !list.isEmpty()) {
                result.setDecorgString(list.get(0).getDecorgCn());
                if ("enter".equals(dto.getType())) {
                    result.setLostCreditExplain(list.get(0).getSerillreaCn());
                } else if ("remove".equals(dto.getType())) {
                    result.setLostCreditExplainrem(list.get(0).getRemexcpresCn());
                }
            }
        }

        return RestResult.ok(result);
    }

    /**
     * 查询处理意见记录
     */
    @ApiOperation("查询处理意见记录")
    @GetMapping("/queryOpinionRecords")
    public RestResult<List<TSOpinion>> queryOpinionRecords(@ApiParam("工作流ID") @RequestParam String workflowid) {
        if (StringUtils.isBlank(workflowid)) {
            throw new BusinessException("工作流ID不能为空");
        }

        List<TSOpinion> opinionList = opinionService.selectByAuditingID(workflowid);
        return RestResult.ok(opinionList);
    }

    /**
     * 修改暂存的业务数据
     *
     * @param modifyDto 业务记录
     * @return 修改结果
     */
    @ApiOperation("修改暂存的业务数据")
    @PostMapping("modify/temp")
    public RestResult<?> modifyTemp(@RequestBody @Valid EOtIlldisdetailTempModifyDto modifyDto) {
        String bizseq = modifyDto.getBizseq();
        String bizType = modifyDto.getBizType();
        if (!StringUtils.equalsAny(modifyDto.getBizType(), CommonConstants.FALSE_0, CommonConstants.TRUE_1) || StringUtils.isBlank(bizseq)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }
        EOtIlldisdetailTemp temp = new EOtIlldisdetailTemp();
        BeanUtils.copyProperties(modifyDto, temp);
        if (StringUtils.isNotBlank(temp.getSerillrea())) {
            // CD73
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
            TRBaseCode serillreaCode = codeMap.get(temp.getSerillrea());
            if (serillreaCode != null) {
                temp.setSerillreaCn(serillreaCode.getName());
            }
        }
        if (StringUtils.isNotBlank(temp.getRemexcpres())) {
            // CD74
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD74");
            TRBaseCode remCode = codeMap.get(temp.getRemexcpres());
            if (remCode != null) {
                temp.setRemexcpresCn(remCode.getName());
            }
        }
        eOtIlldisdetailTempService.update(temp, new LambdaQueryWrapper<EOtIlldisdetailTemp>()
                .eq(StringUtils.equals(CommonConstants.FALSE_0, bizType), EOtIlldisdetailTemp::getInBizseq, bizseq)
                .eq(StringUtils.equals(CommonConstants.TRUE_1, bizType), EOtIlldisdetailTemp::getOutBizseq, bizseq));
        return RestResult.ok();
    }
}
