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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AbnWsqDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AbnWsqDtoAll;
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.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.market.entity.TSUsualInspect;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.market.service.impl.BizOwnerAssignServiceImpl;
import com.chinaweal.aiccs.aiccs.revoke.service.impl.CreateFileServiceImpl;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiccs.temp.entity.Temprepairinfo;
import com.chinaweal.aiccs.aiccs.temp.service.TemprepairinfoService;
import com.chinaweal.aiccs.aiceps.annual.entity.TREntBaseInfoSplit;
import com.chinaweal.aiccs.aiceps.annual.service.TREntBaseInfoSplitService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.HolidaysUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
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.util.SpringUtil;
import com.deepoove.poi.XWPFTemplate;
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.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 移动端个体户经营异常状态控制层
 *
 * @author lwd
 * @since 2021/09/27 17:58
 **/
@RestController
@RequestMapping("/wx/bizRemListApp")
@Slf4j
public class BizRemListAppController {


    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TUsersService usersService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSWritService tsWritService;
    @Resource
    private TSOpinionService tsOpinionService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private TemprepairinfoService temprepairinfoService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Resource
    private BizOwnerAssignServiceImpl bizOwnerAssignService;
    @Resource
    private ITSUsualInspectService iTSUsualInspectService;

    @Autowired
    private TREntBaseInfoSplitService trEntBaseInfoSplitService;
    /**
     * 根据统一信用代码查询企业的经营异常信用修复列表
     */
    @GetMapping("/listTSAbnList")
    public RestResult<List<TSAbnList>> listTSAbnList(@RequestParam String uscc, String type) {

        Map<String, Object> parm = new HashMap<>();

        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(uscc)) {
            if (StringUtils.isUscc(uscc)) {
                parm.put("uniscid", uscc);
            } else {
                parm.put("regno", uscc);
            }
        }

        if ("individual".equals(type)) {
            parm.put("entType", "individual");
        } else if ("farmer".equals(type)) {
            parm.put("entType", "farmer");
        }
        List<TSAbnList> list = tsAbnListService.getTSAbnListByMap(parm);
        Map<String, TRBaseCode> causeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
        for (TSAbnList tsAbnList : list) {
            TRBaseCode code = causeMap.get(tsAbnList.getSpecause());
            if (code != null) {
                tsAbnList.setSpecauseCn(code.getName());
            }
        }

        return RestResult.ok(list);
    }

    /**
     * 进入个体申请信用修复页面
     *
     * @param _map
     * @author lwd
     * @since 2021年8月30日 15:11:21
     */
    @RequestMapping(value = "/intoGtCreditRepair_ydd", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> intoGtCreditRepair_ydd(@RequestBody Map _map, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String uniscid = (String) _map.get("uniscid");
        String abnlistid = (String) _map.get("abnlistid");
        String pripid = (String) _map.get("pripid");

        // 封装参数
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();


        //判断是社会统一码还是注册号
        if (uniscid.length() == 18 && (uniscid.trim().startsWith("9") || uniscid.trim().startsWith("3"))) {
            wrapper.eq(EBaseinfo::getUniscid, uniscid);
        } else {
            wrapper.eq(EBaseinfo::getRegno, uniscid);
        }
        wrapper.eq(EBaseinfo::getRegstate, "1");
        wrapper.select(EBaseinfo::getPripid, EBaseinfo::getCerno,
                EBaseinfo::getUniscid, EBaseinfo::getRegno,
                EBaseinfo::getEntname, EBaseinfo::getDom,
                EBaseinfo::getName, EBaseinfo::getPhone);
        // 查询基本信息
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
        result.put("eBaseinfo", eBaseinfo);//企业基本信息

        if ("9100".equals(eBaseinfo.getEnttype()) || "9200".equals(eBaseinfo.getEnttype())) {//农合
            result.put("entertype", "farmer");
        } else {
            result.put("entertype", "company");
        }

        //查询个体业务主体信息
        TSBizSpeList tsBizSpeList = tsBizSpeListService.selectBSPexptlistById(abnlistid);
        TSAbnList tsAbnList = tsAbnListService.selectTsAbnById(abnlistid);
        tsAbnList.setCerno(null); // 证件号码不显示 敏感信息
        String intowritid = tsAbnList.getIntowritid();
        TSWrit tsWrit = null;
        if (intowritid != null) {
            tsWrit = tsWritService.getById(intowritid);

        } else {
            if (tsBizSpeList != null) {
                //查询文书信息
                Map<String, Object> paramTwr = new HashMap<>();
                paramTwr.put("bizseq", tsBizSpeList.getBizseq());
                paramTwr.put("pripid", pripid);
                tsWrit = tsWritService.selectTsWritByMap(paramTwr);

            }
        }
        if (tsWrit != null) {
            tsAbnList.setWritsno(tsWrit.getWritsno());
        }

        result.put("bizseq", UUID.randomUUID().toString());

        if (tsWrit != null) {
            tsAbnList.setWritsno(tsWrit.getWritsno());
        }

        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
        TRBaseCode trBaseCode = codeMap.get(tsAbnList.getSpecause());
        if (trBaseCode != null) {
            tsAbnList.setSpecauseCn(trBaseCode.getName());
        }
        result.put("tsAbnList", tsAbnList);//经营异常违法失信企业信息

        return result;
    }

    /**
     * 移动端经营异常启动流程 下一步
     *
     * @param abnlistid   经营异常id
     * @param entertype   类型：'individual'-个体户 'farmer'-农专 'company'-企业
     * @param applicantId 申请人身份证号码
     * @param applicant   申请人姓名
     * @param applicantNo 申请人手机号码
     * @param bizseqUp    业务流水号
     * @return
     * @author lwd
     * @date 2021-10-08
     */
    @Transactional
    @PostMapping(value = "/next_app")
    public RestResult<?> next_app(String abnlistid, String entertype, String applicantId,
                                  String applicant, String applicantNo, String bizseqUp) {

        Map<String, Object> resultMap = new HashMap<>();
        Temprepairinfo temprepairinfo = new Temprepairinfo();
        temprepairinfo.setApplyTime(LocalDateTime.now());
        temprepairinfo.setAbnid(abnlistid);
        temprepairinfo.setApplicant(applicant);
        temprepairinfo.setApplicantNo(applicantNo);
        temprepairinfo.setBizseq(bizseqUp);
        temprepairinfo.setType(entertype);
        temprepairinfoService.saveApplyInfo(temprepairinfo);

        try {
            List<TSBizRemList> bizRemListModelList = new ArrayList<>();
            //添加到 移出异常名录业务表
            TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
            EBaseinfo eBaseInfo = eBaseinfoService.getById(tsAbnListModel.getPripid());
            //查询个体业务主体信息
            TSBizRemList tsBizRemListModel = new TSBizRemList();
            tsBizRemListModel.setBizseq(bizseqUp);
            tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
            tsBizRemListModel.setPripid(tsAbnListModel.getPripid());
            tsBizRemListModel.setRegno(tsAbnListModel.getRegno());
            tsBizRemListModel.setEntname(tsAbnListModel.getEntname());
            tsBizRemListModel.setSpecause(tsAbnListModel.getSpecause());
            tsBizRemListModel.setAbntime(tsAbnListModel.getAbntime());
            tsBizRemListModel.setSpereasons(tsAbnListModel.getSpereasons());
            tsBizRemListModel.setApplicant(applicant);
            tsBizRemListModel.setApplicantNo(applicantNo);
            tsBizRemListModel.setApplicantId(applicantId);
            tsBizRemListModel.setCerno(eBaseInfo.getCerno());
            tsBizRemListModel.setType(entertype);
            tsBizRemListModel.setLauptime(LocalDateTime.now());
            tsBizRemListModel.setAppOrPc("0");//移动端
            tsBizRemListModel.setApplyTime(LocalDateTime.now());
            tsBizRemListModel.setHandleStatus("1");
            bizRemListModelList.add(tsBizRemListModel);

            //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
            String permission = "individual".equals(entertype) ? "individualRecoverAccept" : "exptRemoveEnter";
            List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, tsAbnListModel.getDecorg(), tsAbnListModel.getIntoDecorg())
                    .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
            if (userIdList.isEmpty()) {
                log.error("分派失败，受理人列表为空,tsabnlist为：{},权限为：{}", tsAbnListModel, permission);
                throw new BusinessException("受理人列表为空！");
            } else {
                TSTaskList taskListModel = new TSTaskList();
                //添加待办
                taskListModel.setBizseqid(bizseqUp);
                if ("individual".equals(entertype)) {
                    taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE);
                } else if ("farmer".equals(entertype)) {
                    taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_REMOVE);
                } else {
                    taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_REMOVE);
                }
                taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(tsBizRemListService.getInsertDeadlineDate(tsAbnListModel.getSpecause(), taskListModel.getBustype(), true)));
                taskListModel.setBusname(bizRemListModelList.get(0).getEntname());
                //移动端过来的数据要更新为申请人的信息
                taskListModel.setSenderuserid("");
                taskListModel.setSenderorgid("");
                taskListModel.setSendername(applicant);

                // 判断是否可以进行智能办结
                RestResult<?> restResult = tsBizRemListService.canProcessSmart(eBaseInfo, taskListModel, bizRemListModelList);
                // 判断是否需要智能办结
                if (restResult.getCode() != 0) {
                    // 旧流程
                    AICUser aicUser = orgUM.findUserByPrimaryKey(userIdList.get(0));
                    if (userIdList.size() == 1) {
                        taskListModel = tsBizRemListService.saveAbnListStart(aicUser, taskListModel, bizRemListModelList);
                    } else {
                        taskListModel = tsBizRemListService.saveAbnListStartApp(aicUser, userIdList, taskListModel, bizRemListModelList);
                    }
                    //移动端过来的数据要更新为申请人的信息
                    taskListModel.setSenderuserid("");
                    taskListModel.setSenderorgid("");
                    taskListModel.setSendername(applicant);
                    taskListService.updateById(taskListModel);
                } else {
                    // 智能办结
                    tsBizRemListService.processSmart(eBaseInfo, taskListModel, bizRemListModelList, tsAbnListModel.getDecorg(), applicant);
                }
            }

        } catch (Exception e) {
            log.error("移动端经营异常启动流程出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if (e.getMessage().equals("受理人列表为空！"))
                throw new BusinessException("受理人列表为空！");
        }

        resultMap.put("flag", "success");
        return RestResult.ok(resultMap);

    }

    /**
     * 检验该笔件已经在申请中了
     */
    @GetMapping(value = "/checkTaskList")
    public RestResult<?> checkTaskList(@RequestParam String abnlistid) {
        List<TSBizRemList> tsBizRemList = tsBizRemListService.checkTaskList(abnlistid);
        if (tsBizRemList.size() > 0) {
            return RestResult.ok(tsBizRemList.get(0).getHandleStatus());
        } else {
            return RestResult.ok(false);
        }
    }

    @RequestMapping(value = "/intoCompanyRepairAg_ydd", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Map<String, Object> intoCompanyRepairAg_ydd(@RequestBody Map _map, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String uniscid = (String) _map.get("uniscid");

        String bizseq = (String) _map.get("bizseq");
        String pripid = (String) _map.get("pripid");


        // 封装参数
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();


        //判断是社会统一码还是注册号
        if (uniscid.length() == 18 && (uniscid.trim().startsWith("9") || uniscid.trim().startsWith("3"))) {
            wrapper.eq(EBaseinfo::getUniscid, uniscid);
        } else {
            wrapper.eq(EBaseinfo::getRegno, uniscid);
        }
        wrapper.eq(EBaseinfo::getRegstate, "1");
        wrapper.select(EBaseinfo::getPripid, EBaseinfo::getCerno,
                EBaseinfo::getUniscid, EBaseinfo::getRegno,
                EBaseinfo::getEntname, EBaseinfo::getDom,
                EBaseinfo::getName, EBaseinfo::getPhone);
        // 查询基本信息
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
        result.put("eBaseinfo", eBaseinfo);//企业基本信息

        TSBizRemList param = new TSBizRemList();
        param.setPripid(pripid);
        param.setBizseq(bizseq);
        List<TSBizRemList> tsBizRemLists = tsBizRemListService.selectBRMexptlist(param);
        if (tsBizRemLists.size() > 0) {
            result.put("TSBizRemList", tsBizRemLists.get(0));//经营异常删除业务流程信息
        }


        //查询企业经营异常信息
        TSAbnList tsAbnList = tsAbnListService.queryByAbnlistid(tsBizRemLists.get(0).getAbnlistid());
        tsAbnList.setSpecauseType(tsAbnList.getSpecauseType());
        tsAbnList.setCerno(null); // 证件号码不显示 敏感信息

        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD72");
        TRBaseCode trBaseCode = codeMap.get(tsAbnList.getSpecause());
        if (trBaseCode != null) {
            tsAbnList.setSpecauseCn(trBaseCode.getName());
        }
        result.put("tsAbnList", tsAbnList);//经营异常企业信息

        //查询文书path路径
        LambdaQueryWrapper<TSWrit> lqwWrit = Wrappers.lambdaQuery();
        lqwWrit.eq(TSWrit::getBizseq, bizseq).eq(TSWrit::getPripid, pripid);
        List<TSWrit> tsWrits = tsWritService.list(lqwWrit);
        result.put("tsWrits", tsWrits);

        //环节流程列表
        LambdaQueryWrapper<TSOpinion> lqwTso = Wrappers.lambdaQuery();
        List<TSTaskList> tsTaskLists = taskListService.selectByBizSeqID(bizseq);
        if (!tsTaskLists.isEmpty()) {
            lqwTso.eq(TSOpinion::getWorkflowid, tsTaskLists.get(0).getWorkflowid())
                    .orderByAsc(TSOpinion::getHandledate);
            List<TSOpinion> tsOpinions = tsOpinionService.list(lqwTso);
            result.put("tsOpinions", tsOpinions);
        }

        return result;
    }

    /**
     * 经营异常信用修复重新提交
     *
     * @param bizseqUp
     * @param pripid
     * @return
     */
    @Transactional
    @RequestMapping(value = "/approvalnextAg_app")
    public RestResult<?> approvalnextAg_app(String abnlistid, String applicant,
                                            String applicantNo, String applicantId, String bizseqUp, String pripid, String entertype) {
        Map<String, Object> resultMap = new HashMap<>();

        if (StringUtils.isBlank(bizseqUp) || StringUtils.isBlank(pripid)) {
            resultMap.put("flag", "fail");
            return RestResult.ok(resultMap);
        }

        String bizseqUpAg = UUID.randomUUID().toString();//上传的业务号,也是待办的业务号
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("bizseq", bizseqUp);
        paramMap.put("priPid", pripid);
        List<TSBizRemList> tsBizRemLists = null;
        try {
            TSBizRemList tsBizRemListReturn = tsBizRemListService.getOne(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, bizseqUp)
                    .eq(TSBizRemList::getHandleStatus, "2"));
            TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizseqUp)
                    .eq(TSTaskList::getBusstatus, "5"));
            if (tsBizRemListReturn != null && taskList != null) {
                //1、获取流程id
                String workflowid = taskList.getWorkflowid();

                //2、结束回退业务
                tsBizRemListReturn.setStatus("3");
                tsBizRemListReturn.setHandleStatus("5");
                tsBizRemListReturn.setLauptime(LocalDateTime.now());
                tsBizRemListService.updateById(tsBizRemListReturn);

                taskList.setBusstatus(BaseDataConstant.BUSINESS_STATUS_END);
                taskList.setSendertime(LocalDateTime.now());
                taskListService.updateById(taskList);


                if (StringUtils.isBlank(workflowid)) {
                    log.error("分派失败，找不到移除业务和待办,bizseq为：{},priPid为：{}", bizseqUp, pripid);
                    throw new BusinessException("找不到移除业务");
                }

                //3、重新分派
                //查询移出异常名录业务表
                TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
                EBaseinfo eBaseInfo = eBaseinfoService.getById(tsAbnListModel.getPripid());
                if (entertype.equals("farmerORcompany")) {
                    if ("9100".equals(eBaseInfo.getEnttype()) || "9200".equals(eBaseInfo.getEnttype())) {//农合
                        entertype = "farmer";
                    } else {
                        entertype = "company";
                    }
                }

                Temprepairinfo temprepairinfo = new Temprepairinfo();
                temprepairinfo.setApplyTime(LocalDateTime.now());
                temprepairinfo.setAbnid(abnlistid);
                temprepairinfo.setApplicant(applicant);
                temprepairinfo.setApplicantNo(applicantNo);
                temprepairinfo.setBizseq(bizseqUpAg);
                temprepairinfo.setType(entertype);
                temprepairinfoService.saveApplyInfo(temprepairinfo);

                List<TSBizRemList> bizRemListModelList = new ArrayList<>();

                //添加个体业务主体信息
                TSBizRemList tsBizRemListModel = new TSBizRemList();
                tsBizRemListModel.setBizseq(bizseqUpAg);
                tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                tsBizRemListModel.setPripid(tsAbnListModel.getPripid());
                tsBizRemListModel.setRegno(tsAbnListModel.getRegno());
                tsBizRemListModel.setEntname(tsAbnListModel.getEntname());
                tsBizRemListModel.setSpecause(tsAbnListModel.getSpecause());
                tsBizRemListModel.setAbntime(tsAbnListModel.getAbntime());
                tsBizRemListModel.setSpereasons(tsAbnListModel.getSpereasons());
                tsBizRemListModel.setApplicant(applicant);
                tsBizRemListModel.setApplicantNo(applicantNo);
                tsBizRemListModel.setApplicantId(applicantId);
                tsBizRemListModel.setCerno(eBaseInfo.getCerno());
                tsBizRemListModel.setType(entertype);
                tsBizRemListModel.setLauptime(LocalDateTime.now());
                tsBizRemListModel.setAppOrPc("0");//移动端
                tsBizRemListModel.setApplyTime(LocalDateTime.now());
                tsBizRemListModel.setHandleStatus("1");
                bizRemListModelList.add(tsBizRemListModel);

                //移动端把业务号换成新的业务号
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setBizseq(bizseqUp);
                tsAttachmentModel.setPripid(tsAbnListModel.getPripid());
                List<TSAttachment> tsAttachments = attachmentService.selectwritByPage(tsAttachmentModel);
                if (tsAttachments.size() > 0) {
                    for (int i = 0; i < tsAttachments.size(); i++) {
                        tsAttachments.get(i).setBizseq(bizseqUpAg);
                        attachmentService.saveOrUpdate(tsAttachments.get(i));
                    }
                }

                //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
                String permission = "individual".equals(entertype) ? "individualRecoverAccept" : "exptRemoveEnter";
                List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, tsAbnListModel.getDecorg(), tsAbnListModel.getIntoDecorg())
                        .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
                if (userIdList == null || userIdList.isEmpty()) {
                    log.error("分派失败，受理人列表为空,tsabnlist为：{},权限为：{}", tsAbnListModel, permission);
                    throw new BusinessException("受理人列表为空！");
                } else {
                    AICUser aicUser = orgUM.findUserByPrimaryKey(userIdList.get(0));
                    TSTaskList taskListModel = new TSTaskList();
                    taskListModel.setBizseqid(bizseqUpAg);
                    //添加待办
                    if ("individual".equals(entertype)) {
                        taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE);
                    } else if ("farmer".equals(entertype)) {
                        taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_REMOVE);
                    } else {
                        taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_REMOVE);
                    }
                    taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(tsBizRemListService.getInsertDeadlineDate(tsAbnListModel.getSpecause(), taskListModel.getBustype(), true)));
                    taskListModel.setBusname(bizRemListModelList.get(0).getEntname());

                    // 判断是否可以进行智能办结
                    RestResult<?> restResult = tsBizRemListService.canProcessSmart(eBaseInfo, taskListModel, bizRemListModelList);
                    // 判断是否需要智能办结
                    if (restResult.getCode() != 0) {
                        // 旧流程
                        if (userIdList.size() == 1) {
                            taskListModel = tsBizRemListService.saveAbnListStart(aicUser, taskListModel, bizRemListModelList);
                        } else {
                            taskListModel = tsBizRemListService.saveAbnListStartApp(aicUser, userIdList, taskListModel, bizRemListModelList);
                        }
                        // 意见迁移
                        List<TSOpinion> opinionList = opinionService.queryByWorkflowId(workflowid);
                        if (CollectionUtils.isNotEmpty(opinionList)) {
                            for (TSOpinion opinion : opinionList) {
                                opinion.setOpinionid(null);
                                opinion.setWorkflowid(taskListModel.getWorkflowid());
                                opinion.setBizseq(bizseqUpAg);
                                opinionService.save(opinion);
                            }
                        }

                        // 移动端过来的数据要更新为申请人的信息
                        taskListModel.setSenderuserid("");
                        taskListModel.setSenderorgid("");
                        taskListModel.setSendername(applicant);
                        taskListService.updateById(taskListModel);
                    } else {
                        // 智能办结
                        tsBizRemListService.processSmart(eBaseInfo, taskListModel, bizRemListModelList, tsAbnListModel.getDecorg(), applicant);
                    }
                }
            } else {
                log.error("分派失败，找不到移除业务和待办,bizseq为：{},priPid为：{}", bizseqUp, pripid);
                throw new BusinessException("找不到移除业务");
            }
        } catch (Exception e) {
            log.error("经营异常信用修复重新提交失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultMap.put("flag", "error");
            return RestResult.ok(resultMap);
        }
        paramMap.put("bizseq", bizseqUpAg);
        tsBizRemLists = tsBizRemListService.selectbizRem(paramMap);//获取回退的移除业务
        resultMap.put("flag", "success");
        resultMap.put("tsBizRemLists", tsBizRemLists);
        return RestResult.ok(resultMap);

    }

    @RequestMapping("cancelBusiness")
    public RestResult<?> cancelBusiness(String bizseq) {
        tsBizRemListService.cancelBusiness(bizseq);
        return RestResult.ok();
    }

    @PostMapping("checknb")
    public RestResult<?> checknb(String abnlistid) {
        TSAbnList tsaBnList = tsAbnListService.getById(abnlistid);
        LocalDate abntime = tsaBnList.getAbntime();
        int year = abntime.getYear();
        LocalDate boundary = LocalDate.of(year, 7, 1);
        int check = 0;
        Boolean isnb = false;
        if (abntime.isBefore(boundary)) { // 查两年前是否年报
            check = tsAbnListService.checknb(tsaBnList.getPripid(), String.valueOf(year - 2));
        } else {
            // 查去年是否年报
            check = tsAbnListService.checknb(tsaBnList.getPripid(), String.valueOf(year - 1));
        }
        if (check > 0) isnb = true;
        return RestResult.ok(isnb);
    }


    @PostMapping("checknbwsq")
    public RestResult<?> checknbwsq(String abnlistids) {
        String ids[] = abnlistids.split(",");
        Map<String, Object> result = new HashMap<>();
        Boolean isnb = false;
        Boolean havenb = false;
        for (int i = 0; i < ids.length; i++) {
            TSAbnList tsaBnList = tsAbnListService.getById(ids[i]);
            EBaseinfo eBInfo = eBaseinfoService.getById(tsaBnList.getPripid());
            int clyear = Integer.parseInt(eBInfo.getEstdate().substring(0,4)); //2021
            if ("nb".equals(tsaBnList.getSpecauseType())) {
                havenb = true;
                result.put("havenb", havenb);
                LocalDate abntime = tsaBnList.getAbntime();
                int year = abntime.getYear();
                LocalDate boundary = LocalDate.of(year, 7, 1);
                int check = 0;
                if (abntime.isBefore(boundary)) { // 查两年前是否年报
                    if (year - clyear < 2 ) {
                        check = trEntBaseInfoSplitService.getByWrapper(trEntBaseInfoSplitService.lambdaQuery()
                                        .ne(TREntBaseInfoSplit::getDstate, "2").eq(TREntBaseInfoSplit::getEntityno, tsaBnList.getPripid()).getWrapper(),
                                year- 1, false).size();
                    }else {
                        check = trEntBaseInfoSplitService.getByWrapper(trEntBaseInfoSplitService.lambdaQuery()
                                        .ne(TREntBaseInfoSplit::getDstate, "2").eq(TREntBaseInfoSplit::getEntityno, tsaBnList.getPripid()).getWrapper(),
                                year- 2, false).size();
                    }
                } else {
                    // 查去年是否年报
                    check = trEntBaseInfoSplitService.getByWrapper(trEntBaseInfoSplitService.lambdaQuery()
                                    .ne(TREntBaseInfoSplit::getDstate, "2").eq(TREntBaseInfoSplit::getEntityno, tsaBnList.getPripid()).getWrapper(),
                            year- 1, false).size();
                }
                if (check > 0) {
                    isnb = true;
                    result.put("isnb",isnb);
                } else {
                    isnb = false;
                    result.put("isnb",isnb);
                    break;
                }
            } else {
                isnb = true;
                result.put("isnb",isnb);
            }
        }
        return RestResult.ok(result);
    }

    /**
     * 检验已经在申请中了经营异常
     */
    @GetMapping(value = "/checkTaskwsqList")
    public RestResult<?> checkTaskwsqList(@RequestParam String abnlistids) {
        String ids[] = abnlistids.split(",");
        String taskids = "";
        for (int i = 0; i < ids.length; i++) {
            List<TSBizRemList> tsBizRemList = tsBizRemListService.checkTaskList(ids[i]);
            if (tsBizRemList.size() > 0) {
                taskids += tsBizRemList.get(0).getAbntime() + ",";
            }
        }
        if (taskids.length() > 0) {
            taskids = taskids.substring(0, taskids.length() - 1);
            return RestResult.ok(taskids);
        } else {
            taskids = "no";
        }
        return RestResult.ok(taskids);
    }

    /**
     * 进入个体申请信用修复页面
     *
     * @param _map
     * @author lwd
     * @since 2021年8月30日 15:11:21
     */
    @RequestMapping(value = "/intoGtCreditRepair_yddwsq", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> intoGtCreditRepair_yddwsq(@RequestBody Map _map, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String uniscid = (String) _map.get("uniscid");
        String abnlistids = (String) _map.get("abnlistids");
        String pripid = (String) _map.get("pripid");

        // 封装参数
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();


        //判断是社会统一码还是注册号
        if (uniscid.length() == 18 && (uniscid.trim().startsWith("9") || uniscid.trim().startsWith("3"))) {
            wrapper.eq(EBaseinfo::getUniscid, uniscid);
        } else {
            wrapper.eq(EBaseinfo::getRegno, uniscid);
        }
        wrapper.eq(EBaseinfo::getRegstate, "1");
        wrapper.select(EBaseinfo::getPripid, EBaseinfo::getCerno,
                EBaseinfo::getUniscid, EBaseinfo::getRegno,
                EBaseinfo::getEntname, EBaseinfo::getDom,
                EBaseinfo::getName, EBaseinfo::getPhone);
        // 查询基本信息
//        EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
        EBaseinfo eBaseinfo = eBaseinfoService.getById(pripid);
        result.put("eBaseinfo", eBaseinfo);//企业基本信息

        String ids[] = abnlistids.split(",");

        List<TSAbnList> tsAbnLists = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            //查询个体业务主体信息
            TSBizSpeList tsBizSpeList = tsBizSpeListService.selectBSPexptlistById(ids[i]);
            TSAbnList tsAbnList = tsAbnListService.selectTsAbnById(ids[i]);
            tsAbnList.setCerno(null); // 证件号码不显示 敏感信息
            String intowritid = tsAbnList.getIntowritid();
            TSWrit tsWrit = null;
            if (intowritid != null) {
                tsWrit = tsWritService.getById(intowritid);

            } else {
                if (tsBizSpeList != null) {
                    //查询文书信息
                    Map<String, Object> paramTwr = new HashMap<>();
                    paramTwr.put("bizseq", tsBizSpeList.getBizseq());
                    paramTwr.put("pripid", pripid);
                    tsWrit = tsWritService.selectTsWritByMap(paramTwr);

                }
            }
            if (tsWrit != null) {
                tsAbnList.setWritsno(tsWrit.getWritsno());
            }

            if (tsWrit != null) {
                tsAbnList.setWritsno(tsWrit.getWritsno());
            }

            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD71");
            TRBaseCode trBaseCode = codeMap.get(tsAbnList.getSpecause());
            if (trBaseCode != null) {
                tsAbnList.setSpecauseCn(trBaseCode.getName());
            }
            tsAbnList.setBizseqUp(UUID.randomUUID().toString());
            TSTaskList taskListModel = new TSTaskList();
            if ("9910".equals(eBaseinfo.getEnttype())){
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE);
            }else if ("9100".equals(eBaseinfo.getEnttype()) || "9200".equals(eBaseinfo.getEnttype())){
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_REMOVE);
            }else {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_REMOVE);
            }
            List<TSBizRemList> bizRemListModelList = new ArrayList<>();
            TSBizRemList tsBizRemListModel = new TSBizRemList();
            tsBizRemListModel.setAbnlistid(tsAbnList.getAbnlistid());
            tsBizRemListModel.setPripid(tsAbnList.getPripid());
            tsBizRemListModel.setRegno(tsAbnList.getRegno());
            tsBizRemListModel.setEntname(tsAbnList.getEntname());
            tsBizRemListModel.setSpecause(tsAbnList.getSpecause());
            tsBizRemListModel.setAbntime(tsAbnList.getAbntime());
            tsBizRemListModel.setSpereasons(tsAbnList.getSpereasons());
            String entertype = "";
            if ("9910".equals(eBaseinfo.getEnttype())){
                entertype = "individual";
            }else if ("9100".equals(eBaseinfo.getEnttype()) || "9200".equals(eBaseinfo.getEnttype())){
                tsBizRemListModel.setType("farmer");
                entertype = "farmer";
            }else {
                entertype = "company";
            }
            tsBizRemListModel.setType(entertype);
            bizRemListModelList.add(tsBizRemListModel);

            // 判断是否可以进行智能办结
            RestResult<?> restResult = tsBizRemListService.canProcessSmart(eBaseinfo, taskListModel, bizRemListModelList);

            if (restResult.getCode() != 0) {
                tsAbnList.setAutoProc("2");//不能自动办结
            }else {
                tsAbnList.setAutoProc("1");//能自动办结
            }


            tsAbnLists.add(tsAbnList);

        }
        result.put("tsAbnList", tsAbnLists);//经营异常违法失信企业信息

        return result;
    }


    /**
     * 移动端经营异常启动流程 下一步
     * @return
     * @author lwd
     * @date 2021-10-08
     */
    @Transactional
    @PostMapping(value = "/next_appwsq")
    public RestResult<?> next_appwsq(@RequestBody @Validated AbnWsqDtoAll abnWsqDtoAll, HttpServletRequest request ) {

        Map<String, Object> resultMap = new HashMap<>();
        String intoDecorg = "";
        try {
            EBaseinfo eBInfo = eBaseinfoService.getById(abnWsqDtoAll.getPripid());

            List<AbnWsqDto> abnWsqDtoList =  abnWsqDtoAll.getAbnWsqDtoList();

            for (int i = 0; i < abnWsqDtoList.size(); i++) {
                AbnWsqDto abnWsqDto = abnWsqDtoList.get(i);

                Temprepairinfo temprepairinfo = new Temprepairinfo();
                temprepairinfo.setApplyTime(LocalDateTime.now());
                temprepairinfo.setAbnid(abnWsqDto.getAbnlistid());
                temprepairinfo.setApplicant(abnWsqDtoAll.getApplicant());
                temprepairinfo.setApplicantNo(abnWsqDtoAll.getApplicantNo());
                temprepairinfo.setBizseq(abnWsqDto.getBizseqUp());
                if ("9910".equals(eBInfo.getEnttype())){
                    temprepairinfo.setType("individual");
                }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                    temprepairinfo.setType("farmer");
                }else {
                    temprepairinfo.setType("company");
                }
                temprepairinfoService.saveApplyInfo(temprepairinfo);


                List<TSBizRemList> bizRemListModelList = new ArrayList<>();
                //添加到 移出异常名录业务表
                TSAbnList tsAbnListModel = tsAbnListService.getById(abnWsqDto.getAbnlistid());
                intoDecorg = tsAbnListModel.getIntoDecorg();
                //查询个体业务主体信息
                TSBizRemList tsBizRemListModel = new TSBizRemList();
                tsBizRemListModel.setBizseq(abnWsqDto.getBizseqUp());
                tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                tsBizRemListModel.setPripid(tsAbnListModel.getPripid());
                tsBizRemListModel.setRegno(tsAbnListModel.getRegno());
                tsBizRemListModel.setEntname(tsAbnListModel.getEntname());
                tsBizRemListModel.setSpecause(tsAbnListModel.getSpecause());
                tsBizRemListModel.setAbntime(tsAbnListModel.getAbntime());
                tsBizRemListModel.setSpereasons(tsAbnListModel.getSpereasons());
                tsBizRemListModel.setApplicant(abnWsqDtoAll.getApplicant());
                tsBizRemListModel.setApplicantNo(abnWsqDtoAll.getApplicantNo());
                tsBizRemListModel.setApplicantId(abnWsqDtoAll.getApplicantId());
                tsBizRemListModel.setCerno(eBInfo.getCerno());
                if ("9910".equals(eBInfo.getEnttype())){
                    tsBizRemListModel.setType("individual");
                }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                    tsBizRemListModel.setType("farmer");
                }else {
                    tsBizRemListModel.setType("company");
                }
                tsBizRemListModel.setLauptime(LocalDateTime.now());
                tsBizRemListModel.setAppOrPc("0");//移动端
                tsBizRemListModel.setApplyTime(LocalDateTime.now());
                tsBizRemListModel.setHandleStatus("1");
                if (org.apache.commons.lang3.StringUtils.isBlank(tsAbnListModel.getSpereasons())) {
                    //默认年报
                    tsBizRemListModel.setRemexcpres(tsAbnListModel.getSpecause());
                    if ("9910".equals(eBInfo.getEnttype())){
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十三条规定被标记为经营异常状态的个体工商户，向工商行政管理部门补报纸质年度报告并申请恢复正常记载状态");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十四条规定被标记为经营异常状态的个体工商户，向工商行政管理部门报送更正后的纸质年度报告并申请恢复正常记载状态");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，依法办理经营场所、经营者住所变更登记，申请恢复正常记载状态");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，提出通过登记的经营场所或者经营者住所可以重新取得联系，申请恢复正常记载状态");
                        }
                    }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十条规定被列入经营异常名录的农民专业合作社，可以在补报未报年份的年度报告并公示后，申请移出");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十一条规定被列入经营异常名录的农民专业合作社，更正其公示的年度报告信息后，申请移出");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，依法办理住所变更登记，申请移出");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，提出通过登记的住所可以重新取得联系，申请移出");
                        }
                    }else {
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第六条规定被列入经营异常名录的企业，可以在补报未报年份的年度报告并公示后，申请移出");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第七条规定被列入经营异常名录的企业履行公示义务后，申请移出");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第八条规定被列入经营异常名录的企业更正其公示的信息后，申请移出");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，依法办理住所或者经营场所变更登记后，申请移出");
                        }else if ("5".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，提出通过登记的住所或者经营场所可以重新取得联系，申请移出");
                        }else if ("6".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录届满3年仍未履行公示义务的，列入严重违法企业名单，自动移出");
                        }
                    }

                } else if (tsAbnListModel.getSpereasons().contains("隐瞒") || tsAbnListModel.getSpereasons().contains("弄虚作假")) {
                    tsBizRemListModel.setRemexcpres(tsAbnListModel.getSpecause());
                    if ("9910".equals(eBInfo.getEnttype())){
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十三条规定被标记为经营异常状态的个体工商户，向工商行政管理部门补报纸质年度报告并申请恢复正常记载状态");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十四条规定被标记为经营异常状态的个体工商户，向工商行政管理部门报送更正后的纸质年度报告并申请恢复正常记载状态");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，依法办理经营场所、经营者住所变更登记，申请恢复正常记载状态");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，提出通过登记的经营场所或者经营者住所可以重新取得联系，申请恢复正常记载状态");
                        }
                    }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十条规定被列入经营异常名录的农民专业合作社，可以在补报未报年份的年度报告并公示后，申请移出");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十一条规定被列入经营异常名录的农民专业合作社，更正其公示的年度报告信息后，申请移出");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，依法办理住所变更登记，申请移出");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，提出通过登记的住所可以重新取得联系，申请移出");
                        }
                    }else {
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第六条规定被列入经营异常名录的企业，可以在补报未报年份的年度报告并公示后，申请移出");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第七条规定被列入经营异常名录的企业履行公示义务后，申请移出");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第八条规定被列入经营异常名录的企业更正其公示的信息后，申请移出");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，依法办理住所或者经营场所变更登记后，申请移出");
                        }else if ("5".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，提出通过登记的住所或者经营场所可以重新取得联系，申请移出");
                        }else if ("6".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录届满3年仍未履行公示义务的，列入严重违法企业名单，自动移出");
                        }
                    }
                } else if (tsAbnListModel.getSpereasons().contains("住所") || tsAbnListModel.getSpereasons().contains("联系")) {
                    if (abnWsqDto.getAddType() != null ) {
                        if ("1".equals(abnWsqDto.getAddType())) {
//                            tsBizRemListModel.setMBRemovalReason("5");//重新取得联系
                            tsBizRemListModel.setRemexcpres("5");//重新取得联系
                            if ("9910".equals(eBInfo.getEnttype())){
                                tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，提出通过登记的经营场所或者经营者住所可以重新取得联系，申请恢复正常记载状态");
                            }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                                tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，提出通过登记的住所可以重新取得联系，申请移出");
                            }else {
                                tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，提出通过登记的住所或者经营场所可以重新取得联系，申请移出");
                            }
                        }else {
//                            tsBizRemListModel.setMBRemovalReason("4");//变更地址
                            tsBizRemListModel.setRemexcpres("4");//变更地址
                            if ("9910".equals(eBInfo.getEnttype())){
                                tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，依法办理经营场所、经营者住所变更登记，申请恢复正常记载状态");
                            }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                                tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，依法办理住所变更登记，申请移出");

                            }else {
                                tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，依法办理住所或者经营场所变更登记后，申请移出");
                            }
                        }
                    }else {
                        tsBizRemListModel.setRemexcpres("5");
                        if ("9910".equals(eBInfo.getEnttype())){
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，提出通过登记的经营场所或者经营者住所可以重新取得联系，申请恢复正常记载状态");
                        }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，提出通过登记的住所可以重新取得联系，申请移出");
                        }else {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，提出通过登记的住所或者经营场所可以重新取得联系，申请移出");
                        }
                    }

                } else {
                    tsBizRemListModel.setRemexcpres(tsAbnListModel.getSpecause());
                    if ("9910".equals(eBInfo.getEnttype())){
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十三条规定被标记为经营异常状态的个体工商户，向工商行政管理部门补报纸质年度报告并申请恢复正常记载状态");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十四条规定被标记为经营异常状态的个体工商户，向工商行政管理部门报送更正后的纸质年度报告并申请恢复正常记载状态");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，依法办理经营场所、经营者住所变更登记，申请恢复正常记载状态");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《个体工商户年度报告办法》第十五条规定被标记为经营异常状态的个体工商户，提出通过登记的经营场所或者经营者住所可以重新取得联系，申请恢复正常记载状态");
                        }
                    }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十条规定被列入经营异常名录的农民专业合作社，可以在补报未报年份的年度报告并公示后，申请移出");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十一条规定被列入经营异常名录的农民专业合作社，更正其公示的年度报告信息后，申请移出");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，依法办理住所变更登记，申请移出");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("依照《农民专业合作社年度报告公示办法》第十二条规定被列入经营异常名录的农民专业合作社，提出通过登记的住所可以重新取得联系，申请移出");
                        }
                    }else {
                        if ("1".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第六条规定被列入经营异常名录的企业，可以在补报未报年份的年度报告并公示后，申请移出");
                        }else if ("2".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第七条规定被列入经营异常名录的企业履行公示义务后，申请移出");
                        }else if ("3".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第八条规定被列入经营异常名录的企业更正其公示的信息后，申请移出");
                        }else if ("4".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，依法办理住所或者经营场所变更登记后，申请移出");
                        }else if ("5".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录3年内且依照《经营异常名录管理办法》第九条规定被列入经营异常名录的企业，提出通过登记的住所或者经营场所可以重新取得联系，申请移出");
                        }else if ("6".equals(tsAbnListModel.getSpecause())) {
                            tsBizRemListModel.setRemreasons("列入经营异常名录届满3年仍未履行公示义务的，列入严重违法企业名单，自动移出");
                        }
                    }
                }

                bizRemListModelList.add(tsBizRemListModel);

                String entertype = "";
                if ("9910".equals(eBInfo.getEnttype())){
                    entertype = "individual";
                }else if ("9100".equals(eBInfo.getEnttype()) || "9200".equals(eBInfo.getEnttype())){
                    tsBizRemListModel.setType("farmer");
                    entertype = "farmer";
                }else {
                    entertype = "company";
                }
                //如果仍在原地址的，自动生成现场检查待办!
                if ("1".equals(abnWsqDto.getAddType())) {
                    Map<String,String> result = iTSUsualInspectService.savewsqTSUsualInspect(tsAbnListModel,abnWsqDto.getBizseqUp(),eBInfo);
                }


                //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
                String permission = "individual".equals(entertype) ? "individualRecoverAccept" : "exptRemoveEnter";
//                String permission = "market:dynamicsupervision";
                List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, tsAbnListModel.getDecorg(), tsAbnListModel.getIntoDecorg())
                        .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
                if (userIdList.isEmpty()) {
                    log.error("分派失败，受理人列表为空,tsabnlist为：{},权限为：{}", tsAbnListModel, permission);
                    throw new BusinessException("受理人列表为空！");
                } else {
                    TSTaskList taskListModel = new TSTaskList();
                    //添加待办
                    taskListModel.setBizseqid(abnWsqDto.getBizseqUp());
                    if ("individual".equals(entertype)) {
                        taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE);
                    } else if ("farmer".equals(entertype)) {
                        taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_REMOVE);
                    } else {
                        taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_REMOVE);
                    }
                    if (abnWsqDto.getAddType() != null) {//如果是企业还在原地址的就待现场核查完在设置工作时限
                        if (!"1".equals(abnWsqDto.getAddType())) {
                            taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(tsBizRemListService.getInsertDeadlineDate(tsAbnListModel.getSpecause(), taskListModel.getBustype(), true)));
                        }
                    }else {
                        taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(tsBizRemListService.getInsertDeadlineDate(tsAbnListModel.getSpecause(), taskListModel.getBustype(), true)));
                    }
                    taskListModel.setBusname(bizRemListModelList.get(0).getEntname());
                    //移动端过来的数据要更新为申请人的信息
                    taskListModel.setSenderuserid("");
                    taskListModel.setSenderorgid("");
                    taskListModel.setSendername(abnWsqDtoAll.getApplicant());

                    // 判断是否可以进行智能办结
                    RestResult<?> restResult = tsBizRemListService.canProcessSmart(eBInfo, taskListModel, bizRemListModelList);
                    if ("1".equals(abnWsqDto.getAddType())) {//如果还是在原地址的就不能只能办结
                        restResult.setCode(1);
                    }
                    // 判断是否需要智能办结
                    if (restResult.getCode() != 0) {
                        // 旧流程
                        AICUser aicUser = orgUM.findUserByPrimaryKey(userIdList.get(0));
                        if (userIdList.size() == 1) {
                            taskListModel = tsBizRemListService.saveAbnListStart(aicUser, taskListModel, bizRemListModelList);
                        } else {
                            taskListModel = tsBizRemListService.saveAbnListStartApp(aicUser, userIdList, taskListModel, bizRemListModelList);
                        }
                        //移动端过来的数据要更新为申请人的信息
                        taskListModel.setSenderuserid("");
                        taskListModel.setSenderorgid("");
                        taskListModel.setIsSmartProcessing("0");
                        taskListModel.setSendername(abnWsqDtoAll.getApplicant());
                        taskListService.updateById(taskListModel);
                    } else {
                        // 智能办结
                        tsBizRemListService.processSmart(eBInfo, taskListModel, bizRemListModelList, tsAbnListModel.getDecorg(), abnWsqDtoAll.getApplicant());
                    }
                }

                //自动生成信用修复申请
                Map<String, Object> map = new HashMap<>();
                map.put("userName", eBInfo.getEntname() );
                map.put("LegalPerson", eBInfo.getLerep());
                map.put("icar", eBInfo.getCerno() );
                map.put("add", eBInfo.getDom() );
                map.put("tel", abnWsqDtoAll.getLegalPhone());
                map.put("applicantNo", abnWsqDtoAll.getApplicantNo() );
                map.put("applicant", abnWsqDtoAll.getApplicant() );
                map.put("regorg", tsAbnListModel.getIntoDecorg() );
                if ("9910".equals(eBInfo.getEnttype())){
                    map.put("repType", "个体工商户经营异常状态");
                }else {
                    map.put("repType", "经营异常名录" );
                }
                map.put("reasons", tsAbnListModel.getSpereasons());
//                if (org.apache.commons.lang3.StringUtils.isBlank(tsAbnListModel.getSpereasons())) {
//                    //默认年报
//                    if ("9910".equals(eBInfo.getEnttype())){
//                        map.put("reasons", BaseDataConstant.CREDITREPAIRGT_ONE);
//                    }else {
//                        map.put("reasons", BaseDataConstant.CREDITREPAIR_ONE);
//                    }
//
//                } else if (tsAbnListModel.getSpereasons().contains("隐瞒") || tsAbnListModel.getSpereasons().contains("弄虚作假")) {
//                    if ("9910".equals(eBInfo.getEnttype())){
//                        map.put("reasons", BaseDataConstant.CREDITREPAIRGT_ONE);
//                    }else {
//                        map.put("reasons", BaseDataConstant.CREDITREPAIR_ONE);
//                    }
//                } else if (tsAbnListModel.getSpereasons().contains("住所") || tsAbnListModel.getSpereasons().contains("联系")) {
//                    if (abnWsqDto.getAddType() != null && !"".equals(abnWsqDto.getAddType())) {
//                        if ("1".equals(abnWsqDto.getAddType())) {
//                            if ("9910".equals(eBInfo.getEnttype())){
//                                map.put("reasons", BaseDataConstant.CREDITREPAIRGT_TWO);
//                            }else {
//                                map.put("reasons", BaseDataConstant.CREDITREPAIR_TWO);
//                            }
//                        }else {
//                            if ("9910".equals(eBInfo.getEnttype())){
//                                map.put("reasons", BaseDataConstant.CREDITREPAIRGT_THREE);
//                            }else {
//                                map.put("reasons", BaseDataConstant.CREDITREPAIR_THREE);
//                            }
//                        }
//                    }else {
//                        if ("9910".equals(eBInfo.getEnttype())){
//                            map.put("reasons", BaseDataConstant.CREDITREPAIRGT_TWO);
//                        }else {
//                            map.put("reasons", BaseDataConstant.CREDITREPAIR_TWO);
//                        }
//                    }
//                } else {
//                    if ("9910".equals(eBInfo.getEnttype())){
//                        map.put("reasons", BaseDataConstant.CREDITREPAIRGT_ONE);
//                    }else {
//                        map.put("reasons", BaseDataConstant.CREDITREPAIR_ONE);
//                    }
//                }


                String ext = ".docx";
                String fileName = eBInfo.getEntname() + "-" + "信用修复申请书" + ext;
                String urlFileName = UUID.randomUUID().toString() + "CreditRepairApplication" + ext;

                try {
                    ByteArrayOutputStream wordOs = new ByteArrayOutputStream(); // word输出流

                    String wordPath = "static" + File.separator + "template" + File.separator + "CreditRepairApplication.docx";

                    String resource = CreateFileServiceImpl.class.getClassLoader().getResource(wordPath).getPath();

                    String wordpath = CommonConfig.getUploadPathByDate() + File.separator + "xyxf";
                    XWPFTemplate.compile(resource).render(map).write(wordOs);
                    FileStorageService fileStorageService = SpringUtil.getBean(FileStorageService.class);
                    Boolean success = fileStorageService.writeFromStream( wordpath, urlFileName,new ByteArrayInputStream(wordOs.toByteArray()));
                    // 存在上传失败，不抛异常的情况
                    if (!success) {
                        throw new RuntimeException("文件上传失败" + wordpath);
                    }

                    String filePath = wordpath + File.separator + urlFileName;

                    TSAttachment tsAttachmentModel1 = new TSAttachment();
                    tsAttachmentModel1.setBizseq(abnWsqDto.getBizseqUp());
                    tsAttachmentModel1.setFiletype("1");
                    tsAttachmentModel1.setFileext(ext);
                    tsAttachmentModel1.setAttachtype("1");
                    tsAttachmentModel1.setPripid(abnWsqDtoAll.getPripid());
                    tsAttachmentModel1.setFilename(fileName);
                    tsAttachmentModel1.setTemppath(filePath);
                    tsAttachmentModel1.setUploaddate(LocalDate.now());
                    tsAttachmentModel1.setCreatetype("1");
                    attachmentService.saveOrUpdate(tsAttachmentModel1);


                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException("信用修复申请书附件生成出错");
                }

            }

        }catch (Exception e) {
            log.error("移动端经营异常启动流程出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if (e.getMessage().equals("受理人列表为空！"))
                throw new BusinessException("受理人列表为空！");
        }



        resultMap.put("flag", "success");
        resultMap.put("intoDecorg", intoDecorg);
        return RestResult.ok(resultMap);

    }


}
