package com.chinaweal.aiccs.aiccs.abnormal.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
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.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.claim.service.TSEntBaseService;
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.*;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.solr.entity.EBaseInfoSolrBean;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 异常企业异议处理业务接口
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/26 10:18
 **/
@Slf4j
@RestController
@RequestMapping("/bizDissent")
public class BizDissentController extends BaseController {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSBizDissentService tsBizDissentService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;

    /**
     * 异常名录异议 启动待办
     * @param request
     * @param abnlistid
     * @param entertype
     * @param isOnlyRem 是否只是移除异常名录异议
     * @return
     */
    @Transactional
    @PostMapping("/startbizDissent.do")
    public RestResult<?> startbizDissent(HttpServletRequest request, String abnlistid, String entertype, String isOnlyRem) {
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        Map<String, Object> resultMap = new HashMap<>();

        String bizseq = UUID.randomUUID().toString();
        TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
        //获取主体信息
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, tsAbnListModel.getPripid()));

        //添加待办启动流程
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizseq);

        if ("1".equals(isOnlyRem)) {
            taskListModel.setBustype(BaseDataConstant.BUSTNESS_TYPE_REM_ABN_OBJECTION);
        } else {
            if ("individual".equals(entertype)) {//个体户异常名录异议
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_OBJECTION);//个体户异常名录异议
            } else if ("farmer".equals(entertype)) {//农合异常名录异议
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_OBJECTION);//农合异常名录异议
            } else {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_OBJECTION);//企业异常名录异议
            }
        }
        taskListModel.setBusname(tsAbnListModel.getEntname());

        //添加异议表数据
        TSBizDissent tsBizDissentModel = new TSBizDissent();
        tsBizDissentModel.setBizseq(bizseq);
        tsBizDissentModel.setAbnlistid(tsAbnListModel.getAbnlistid());
        tsBizDissentModel.setPripid(tsAbnListModel.getPripid());
        tsBizDissentModel.setRegno(tsAbnListModel.getRegno());
        tsBizDissentModel.setUniscid(tsAbnListModel.getUniscid());
        tsBizDissentModel.setEntname(tsAbnListModel.getEntname());
        tsBizDissentModel.setLerepname(eBaseinfo.getName());
        tsBizDissentModel.setAbnTime(tsAbnListModel.getAbntime());
        tsBizDissentModel.setAbnRea(tsAbnListModel.getSpecause());
        tsBizDissentModel.setAbnReaCn(tsAbnListModel.getSpereasons());
        tsBizDissentModel.setStatus("9");
        tsBizDissentModel.setAppOrPc("1");

        // 获取列入文书号
        TSWrit writQueryModel = new TSWrit();
        writQueryModel.setPripid(tsBizDissentModel.getPripid());
        writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_11);
        List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
        if (tsWritQueryModels.size() > 0) {
            resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
        }

        taskListModel = tsBizDissentService.startBizDissentAccept(user, null, taskListModel, tsBizDissentModel);
        resultMap.put("tsBizDissentModel", tsBizDissentModel);
        resultMap.put("tasklistid", taskListModel.getTasklistid());
        resultMap.put("bizseq", bizseq);
        resultMap.put("currentNode", FlowUtil.DISSENTWORKFLOW_ACCEPTDISSENTENTER);
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(FlowUtil.DISSENTWORKFLOW_ACCEPTDISSENTENTER));
        return RestResult.ok(resultMap);
    }


    /**
     * 判断是否经过异议申请审核环节
     *
     * @param bustype 异议类型才判断
     * @param bizseq  业务号，查询是否生成通知书文书号
     * @return
     */
    @GetMapping("/isPassDissentApply")
    public RestResult<?> isPassDissentApply(String bustype, String bizseq) {
        AssertUtils.isNotBlank(bizseq);
        //是否通过申请审核环节
        boolean isPass = false;
        if (BaseDataConstant.EXPTLIST_TYPE_OBJECTION.equals(bustype)) {
            List<TSWrit> list = tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, bizseq));
            if (list.size() > 0) {
                isPass = true;
            }
        }
        //审核结果
        TSBizDissent tsBizDissent = tsBizDissentService.getOne(new LambdaQueryWrapper<TSBizDissent>().eq(TSBizDissent::getBizseq, bizseq));
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("isPass", isPass);
        resultMap.put("acceptstat", tsBizDissent.getAcceptstat());
        return RestResult.ok(resultMap);
    }

    /**
     * 受理更新
     */
    @Transactional
    @PostMapping("/updatebizDissent.do")
    public RestResult<?> updatebizDissent(HttpServletRequest request, String nextNodeID, TSOpinion opinionModel,
                                          String tasklistid, String nextPerformerids, String nextPerformerNames, TSBizDissent tsBizDissentModel) {
        AICUser user = getLoginUser(request);
        Map<String, Object> resultMap = new HashMap<>();

        if (tsBizDissentModel != null && StringUtils.isNotBlank(tsBizDissentModel.getBizseq())) {
            QueryWrapper<TSBizDissent> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TSBizDissent::getBizseq, tsBizDissentModel.getBizseq());
            //数据库异议表
            TSBizDissent tsBizDissentModel1 = tsBizDissentService.getOne(wrapper);
            //下一步为受理审批，保存录入信息
            if (FlowUtil.DISSENTWORKFLOW_HANDLEDISSENTACCEPT.equals(nextNodeID)) {
                tsBizDissentModel1.setContacts(tsBizDissentModel.getContacts());
                tsBizDissentModel1.setTelephone(tsBizDissentModel.getTelephone());
                tsBizDissentModel1.setApplyRemark(tsBizDissentModel.getApplyRemark());
                tsBizDissentModel1.setStatus("1");
            }
            if(StringUtils.isNotEmpty(tsBizDissentModel.getAcceptstat())) {
                tsBizDissentModel1.setAcceptstat(tsBizDissentModel.getAcceptstat());
            }
            //下一步为核准经办，保存录入信息
            if (FlowUtil.DISSENTWORKFLOW_APPROVEDISSENTACCEPT.equals(nextNodeID)
                || FlowUtil.DISSENTWORKFLOW_OVERFINISH.equals(nextNodeID)) {
                tsBizDissentModel1.setContacts(tsBizDissentModel.getContacts());
                tsBizDissentModel1.setTelephone(tsBizDissentModel.getTelephone());
                tsBizDissentModel1.setApplyRemark(tsBizDissentModel.getApplyRemark());
                tsBizDissentModel1.setSituation(tsBizDissentModel.getSituation());
                if (FlowUtil.DISSENTWORKFLOW_OVERFINISH.equals(nextNodeID)) tsBizDissentModel1.setStatus("3");
            }
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            if(StringUtils.isBlank(nextPerformerids)) {
                TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeID);
                // 通过order判断为回退还是前进 >0前进
                if(order >0){
                    LambdaQueryWrapper<TSOpinion> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, "0")// 经办为0
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(queryWrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
                // 回退时 获取上一个处理人
                if (order < 0){
                    if (taskListModel == null) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(taskListModel.getWorkflowid(),nextNodeID);
                    nextPerformerids = tsTwfProcessNodes.get(0).getCurruserid();
                    nextPerformerNames = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
                }
            }
            //发送
            String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
            String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);


            tsBizDissentService.saveBizDissentAuditProcess(user, taskListModel, tsBizDissentModel1, opinionModel, nextNodeID, ids, names);
            if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                resultMap.put("bizseq", tsBizDissentModel.getBizseq());
                resultMap.put("nextNodeId", nextNodeID);
                resultMap.put("taskListId", tasklistid);
                resultMap.put("workFlowId", taskListModel.getWorkflowid());
            }
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 获取异议业务表及其文书号
     *
     * @param request
     * @param bizseq
     * @return
     */
    @PostMapping(value = "/getBizDissentAndWrirsno")
    public RestResult<?> getBizDissentAndWrirsno(HttpServletRequest request, String bizseq) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNotBlank(bizseq)) {
            QueryWrapper<TSBizDissent> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TSBizDissent::getBizseq, bizseq);
            //数据库异议表
            TSBizDissent tsBizDissentModel1 = tsBizDissentService.getOne(wrapper);
            if (tsBizDissentModel1 != null) {
                resultMap.put("tsBizDissentModel", tsBizDissentModel1);
            }
            TSAbnList tsAbnList = tsAbnListService.getById(tsBizDissentModel1.getAbnlistid());
            resultMap.put("tsAbnList", tsAbnList);
            TSBizSpeList tsBizSpeList = tsBizSpeListService.getById(tsAbnList.getAbnlistid());
            if (tsBizSpeList != null) {
                TSWrit tsWrit = tsWritService.getOne(new LambdaQueryWrapper<TSWrit>()
                        .eq(TSWrit::getBizseq, tsBizSpeList.getBizseq()).eq(TSWrit::getPripid, tsBizSpeList.getPripid()));
                if (tsWrit != null) tsAbnList.setWritsno(tsWrit.getWritsno());
                resultMap.put("wrirsno", tsWrit);
            }
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 异常名录异议 审核意见页面
     */
    @RequestMapping(value = "/next.do")
    public RestResult<?> next(HttpServletRequest request, String tasklistid, String approve) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");

        TSTaskList taskListModel1 = taskListService.selectByTasklistID(tasklistid);
        if (taskListModel1 == null) {
            return RestResult.error(ResultCode.DATA_NONE);
        }
        Map<String, Object> resultMap = new HashMap<>();
        String currentNode = taskListModel1.getCurrentNode();
        // 获得审批意见类型
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode);

        TSBizDissent tsBizDissentModel = tsBizDissentService.selectbizDissentone(taskListModel1.getBizseqid());
        if (tsBizDissentModel == null) {
            throw new BusinessException("TSBizDissentModel is null");
        }

        TSWrit writQueryModel = new TSWrit();
        writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_11);
        writQueryModel.setPripid(tsBizDissentModel.getPripid());
        List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
        if (tsWritQueryModels.size() > 0) {
            resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
        }
        resultMap.put("acceptstat", tsBizDissentModel.getAcceptstat());
        resultMap.put("regno", tsBizDissentModel.getRegno());
        resultMap.put("entname", tsBizDissentModel.getEntname());
        resultMap.put("situation", tsBizDissentModel.getSituation());
        resultMap.put("opinionList", opinionService.selectByAuditingID(taskListModel1.getWorkflowid()));
        resultMap.put("nextSequenceFlowList", workFlowService.findNextSequenceFlowList(taskListModel1.getWorkflowid()));
        resultMap.put("tasklistid", taskListModel1.getTasklistid());
        resultMap.put("pripid", tsBizDissentModel.getPripid());
        resultMap.put("bizSeq", taskListModel1.getBizseqid());
        resultMap.put("dissentid", tsBizDissentModel.getDissentid());
        resultMap.put("currentNode", currentNode);
        resultMap.put("currentLinkTypeID", opinionType); //用于意见管理
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode));
        resultMap.put("approve", approve);
        return RestResult.ok(resultMap);
    }


    /**
     * 发送审批流程
     */
    @PostMapping(value = "/exptnext.do")
    public RestResult<?> opentexptlist(HttpServletRequest request, TSBizDissent tsBizDissentModel, TSOpinion opinionModell, String pripid,
                                       String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID) {
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        //发送
        String[] ids = StringUtils.split(nextPerformerids, ",");
        String[] names = StringUtils.split(nextPerformerNames, ",");
        TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
        Map<String, Object> resultMap = new HashMap<>();
        taskListModel = tsBizDissentService.saveBizDissentAuditProcess(user, taskListModel, tsBizDissentModel, opinionModell, nextNodeID, ids, names);
        resultMap.put("nextNodeID", nextNodeID);
        resultMap.put("currentNode", taskListModel.getCurrentNode());
        resultMap.put("bizSeq", taskListModel.getBizseqid());
        resultMap.put("tasklistid", tasklistid);
        resultMap.put("workflowid", taskListModel.getWorkflowid());
        return RestResult.ok(resultMap);
    }

    /**
     * 进入异常名录异议核准经办流程
     */
    @PostMapping(value = "/nextapprove.do")
    public RestResult<?> nextapprove(HttpServletRequest request, String bizSeq, String tasklistid, String flag) {
        Map<String, Object> resultMap = new HashMap<>();
        TSBizDissent tsBizDissentModel = null;
        if (StringUtils.isNotBlank(bizSeq)) {
            tsBizDissentModel = tsBizDissentService.selectbizDissentone(bizSeq);
            resultMap.put("acceptstat", tsBizDissentModel.getAcceptstat());
            resultMap.put("dissentid", tsBizDissentModel.getDissentid());
            resultMap.put("pripid", tsBizDissentModel.getPripid());
        }
        resultMap.put("tasklistid", tasklistid);
        resultMap.put("bizSeq", bizSeq);
        resultMap.put("flag", StringUtils.isBlank(flag) ? "0" : flag);
        return RestResult.ok(resultMap);
    }

    /**
     * 进入文书打印环节
     */
    @PostMapping(value = "/printNotice.do")
    public RestResult<?> printNotice(HttpServletRequest request, String acceptstat, String bizSeq, String workflowid) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        TSWrit writQueryModel = new TSWrit();//文书号
        //获取当前时间
        Calendar ca = Calendar.getInstance();
        Map<String, Object> resultMap = new HashMap<>();

        TSBizDissent tsBizDissentModel = tsBizDissentService.selectbizDissentone(bizSeq);
        resultMap.put("entname", tsBizDissentModel.getEntname());
        resultMap.put("tsBizDissentModel", tsBizDissentModel);
        //获取机构
        TSAbnList tsAbnListModel = tsAbnListService.getById(tsBizDissentModel.getAbnlistid());
        resultMap.put("tsAbnListModel", tsAbnListModel);
        if (acceptstat.equals("0")) {//列入经营异常名录异议不予受理通知书页面
            writQueryModel.setPripid(tsBizDissentModel.getPripid());
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_13);
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            resultMap.put("nowTime", ca.getTime());
            return RestResult.ok(resultMap);

        } else if (acceptstat.equals("2")) {//列入经营异常名录异议核实结果告知书
            writQueryModel.setPripid(tsBizDissentModel.getPripid());
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_14);
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            resultMap.put("nowTime", ca.getTime());
            return RestResult.ok(resultMap);

        } else if (acceptstat.equals("3")) {//打印异议审批表
            List<TSOpinion> opinionList = opinionService.selectByAuditingID(workflowid);
            resultMap.put("opinionList", opinionList);

            writQueryModel.setPripid(tsBizDissentModel.getPripid());
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_11);
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            return RestResult.ok(resultMap);

        } else { //列入经营异常名录异议受理通知书
            writQueryModel.setPripid(tsBizDissentModel.getPripid());
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_12);
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            resultMap.put("nowTime", ca.getTime());
            return RestResult.ok(resultMap);

        }
    }

    /**
     * 异常名录异议 启动待办前校验
     */
    @PostMapping("/validateBizDissent")
    public RestResult<?> validateBiz(HttpServletRequest request, String abnlistid) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时,请重新登录");

        TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);

        if (!aicUser.getRegionID().equals(tsAbnListModel.getDecorg())) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "不是主体所在的行政区，不允许发起异议");
        }

        // 判断是否有在办移出业务
        int remBusCount = tsBizRemListService.lambdaQuery().eq(TSBizRemList::getAbnlistid, abnlistid).in(TSBizRemList::getStatus, "9", "1").last("AND bizseq is not null").count();
        if (remBusCount > 0) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "存在在办移出业务，不允许发起异议");
        }

        TSBizDissent paramModel = new TSBizDissent();
        paramModel.setAbnlistid(abnlistid);
        List<TSBizDissent> tsBizDissentList = tsBizDissentService.selectbizDissentList(paramModel);
        //发起过异议
        if (CollectionUtils.isNotEmpty(tsBizDissentList)) {
            for (TSBizDissent tsBizDissentModel : tsBizDissentList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(tsBizDissentModel.getBizseq());
                if (CollectionUtils.isNotEmpty(tsTaskListModels)) {
                    for (TSTaskList tsTaskListModel : tsTaskListModels) {
                        if (BaseDataConstant.BUSINESS_STATUS_TRANSACT.equals(tsTaskListModel.getBusstatus())) { //存在待办未办结
                            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"此记录正在申请异议,请先完成");
                        }
                    }
                }
            }
        }

        return OK;
    }

    /**
     * 文书打印查询--文书列表校验（不予受理的异议，无对应文书列表）
     */
    @PostMapping("/validateAccept.do")
    public RestResult<?> validateAccept(HttpServletRequest request, String bizSeq) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");

        if (StringUtils.isNotBlank(bizSeq)) {
            TSBizDissent tsBizDissentModel = tsBizDissentService.selectbizDissentone(bizSeq);
            if (tsBizDissentModel != null) {
                if ("1".equals(tsBizDissentModel.getAcceptstat())) {
                    return OK;
                } else {
                    throw new BusinessException("该异议申请未予受理，无对应文书列表");
                }
            }
        }
        throw new BusinessException("无法找到记录，请联系管理员");
    }

    /**
     * 获取异常主体列表分页
     *
     * @return
     */
    @PostMapping(value = "common_page")
    public RestResult<?> getDissentListPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时,请重新登录");
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        // 搜索统一码和注册号
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        String searchName = StringUtils.tranObject(customParamMap.get("searchName"));
        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(searchUscc)) {
            if(StringUtils.isUscc(searchUscc)){
                customParamMap.put("uniscid",searchUscc);
            }else {
                customParamMap.put("regno",searchUscc);
            }
        }
        if(StringUtils.isNotBlank(searchName)){
            HashMap<String, Object> params = new HashMap<>();
            params.put("entName",searchName);
            params.put("enttype","company");
            EBaseinfo baseinfoParams = new EBaseinfo().setEntname(searchName);
            Page page1 = eBaseinfoService.solrQueryPripidByEntName(new Page<>(1, -1, false), baseinfoParams);
            Page page = eBaseinfoService.solrQueryPripidByEntName(new Page<>(1, page1.getTotal(), false), baseinfoParams);
            List records = page.getRecords();
            if(CollectionUtils.isNotEmpty(records)){
                String[] pripidArray = new String[records.size()];
                EBaseInfoSolrBean eBaseinfo;
                for (int i = 0; i < records.size(); i++) {
                    eBaseinfo = (EBaseInfoSolrBean) records.get(i);
                    pripidArray[i] = eBaseinfo.getPripid();
                }
                customParamMap.put("pripids",pripidArray);
            }else {
                return RestResult.ok(new Page<EBaseinfo>());
            }

        }
        return RestResult.ok(tsAbnListService.getDissentListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap));
    }

    /**
     * 获取移出异议主体列表分页
     *
     * @return
     */
    @PostMapping(value = "dissentList")
    public RestResult<?> dissentList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时,请重新登录");
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        // 搜索统一码和注册号
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        String searchName = StringUtils.tranObject(customParamMap.get("searchName"));
        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(searchUscc)) {
            if(StringUtils.isUscc(searchUscc)){
                customParamMap.put("uniscid",searchUscc);
            }else {
                customParamMap.put("regno",searchUscc);
            }
        }
        if(StringUtils.isNotBlank(searchName)){
            HashMap<String, Object> params = new HashMap<>();
            params.put("entName",searchName);
            params.put("enttype","company");
            EBaseinfo baseinfoParams = new EBaseinfo().setEntname(searchName);
            Page page1 = eBaseinfoService.solrQueryPripidByEntName(new Page<>(1, -1, false), baseinfoParams);
            Page page = eBaseinfoService.solrQueryPripidByEntName(new Page<>(1, page1.getTotal(), false), baseinfoParams);
            List records = page.getRecords();
            if(CollectionUtils.isNotEmpty(records)){
                String[] pripidArray = new String[records.size()];
                EBaseInfoSolrBean eBaseinfo;
                for (int i = 0; i < records.size(); i++) {
                    eBaseinfo = (EBaseInfoSolrBean) records.get(i);
                    pripidArray[i] = eBaseinfo.getPripid();
                }
                customParamMap.put("pripids",pripidArray);
            }else {
                return RestResult.ok(new Page<EBaseinfo>());
            }

        }
        return RestResult.ok(tsAbnListService.getRemDissentListPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap));
    }

    /**
     * 异议核实结果告知书，内容保存
     * @param writsid     文书主键
     * @param writstype    文书类型
     * @param content       文书内容
     * @param request
     * @return
     */
    @PostMapping("updateResultNotice")
    public RestResult<?> updateResultNotice(String writsid,String writstype, String content,HttpServletRequest request){
        AssertUtils.isNotEmpty(writsid,content,writstype);
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");
        TSWrit tsWrit = new TSWrit();
        tsWrit.setWritsid(writsid);
        if(WorkNoUtil.WORKNOTYPE_14.equals(writstype)){
            content = BaseDataConstant.ABN_DISSENT_RESULT_NOTICE_CONTENT + content;
        }
        tsWrit.setContent(content);
        tsWrit.setLauptime(LocalDateTime.now());
        boolean update = tsWritService.updateById(tsWrit);
        if(update) {
            log.info("经营异常名录异议相关文书更新操作用户名：{}，用户id：{}，文书id：{}，文书内容：{}",
                    aicUser.getName(),aicUser.getPrimaryKey(),writsid,content);
        }
        return  RestResult.ok(update);
    }
}
