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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaweal.aiccs.aiccs.abnormal.controller.BizRemListAppController;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizRemList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
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.rules.model.SequenceFlowModel;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegal;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalDiss;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalDissService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.DeadlinestasService;
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.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.HolidaysUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.outside.service.SMSServiceImpl;
import com.chinaweal.aiccs.outside.vo.Personnel;
import com.chinaweal.aiccs.redis.RedisService;
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.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
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.web.bind.annotation.*;

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

@Slf4j
@RestController
@RequestMapping("/wx/bizSerIllegalRemApp")
public class BizSerIllegalRemAppController {

    @Resource
    private EBaseinfoService eBaseinfoService;
    @Resource
    private TRBaseCodeService baseCodeService;
    @Resource
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TUsersService usersService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TSBizSerIllegalDissService tsBizSerIllegalDissService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSBizSerIllegalRemService tsBizSerIllegalRemService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Resource
    private TSBizSerIllegalService tsBizSerIllegalService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private TSOpinionService tsOpinionService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private TemprepairinfoService temprepairinfoService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private AicorgService aicorgService;

    /**
     * 身份登陆认证
     * @param data
     * @return
     */
    @PostMapping(value = "/login")
    public RestResult<?> login(@RequestBody Map<String, String> data) {
        String uscc = data.get("uscc");
        String name = data.get("name");
        String certType = data.get("certType");
        String certNo = data.get("certNo");
        String type = data.get("type");
        return tsBizSerIllegalService.isLegalCorrect(uscc, name, certType, certNo, type);
    }


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

        String bizseqUp = UUID.randomUUID().toString();//上传的业务号,也是待办的业务号
        result.put("bizseqUp",bizseqUp);

        // 封装参数
        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);//企业基本信息

        Map<String,Object> param = new HashMap<>();
        param.put("bizseq",bizseq);
        param.put("pripid",pripid);

        //查询严重违法失信信息
        TSSerIllegalList illegalList = tsSerIllegalListService.selecttsSerIllegalAppByMap(param);
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        TRBaseCode trBaseCode = codeMap.get(illegalList.getSerillrea());
        if (trBaseCode != null){
            illegalList.setSerillreaString(trBaseCode.getName());
        }
        result.put("illegalList",illegalList);//严重违法失信企业信息
        return result;
    }

    /**
     * 根据统一信用代码查询企业的基础信息
     */
    @GetMapping("/getEntByUscc")
    public RestResult<EBaseinfo> getEntByUscc(@RequestParam String uscc) {
        LambdaQueryWrapper<EBaseinfo> lqw = Wrappers.lambdaQuery();
        //判断是社会统一码还是注册号
        if (uscc.length() == 18 && (uscc.trim().startsWith("9") || uscc.trim().startsWith("3"))) {
            lqw.eq(EBaseinfo::getUniscid, uscc);
        } else {
            lqw.eq(EBaseinfo::getRegno, uscc);
        }
        lqw.select(EBaseinfo::getPripid, EBaseinfo::getCerno,
                EBaseinfo::getUniscid, EBaseinfo::getRegno,
                EBaseinfo::getEntname, EBaseinfo::getDom,
                EBaseinfo::getName, EBaseinfo::getPhone);
        lqw.eq(EBaseinfo::getRegstate,'1');//查询在营企业
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(lqw);
        return RestResult.ok(eBaseinfo);
    }

    /**
     * 根据统一信用代码查询企业的严重违法失信企业信用修复列表
     */
    @GetMapping("/listTsserillegallist")
    public RestResult<List<TSSerIllegalList>> listYzwf(@RequestParam String uscc, String regNo) {
        LambdaQueryWrapper<TSSerIllegalList> lqw = Wrappers.lambdaQuery();
        lqw.and(w -> w.eq(StringUtils.isNotBlank(uscc), TSSerIllegalList::getUniscid, uscc)
                        .or().eq(StringUtils.isNotBlank(regNo), TSSerIllegalList::getRegno, regNo)
                ).and(w -> w.isNull(TSSerIllegalList::getRemdate))
                .isNull(TSSerIllegalList::getRemdate)
                .orderByAsc(TSSerIllegalList::getAbntime);
        List<TSSerIllegalList> list = tsSerIllegalListService.list(lqw);

        for (TSSerIllegalList tsSerIllegalList : list) {
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
            TRBaseCode code = codeMap.get(tsSerIllegalList.getSerillrea());
            if (code != null) {
                tsSerIllegalList.setSerillreaString(code.getName());
            }

            int days = (int) ((int) LocalDate.now().toEpochDay() - tsSerIllegalList.getAbntime().toEpochDay());
            if (days < 365){
                tsSerIllegalList.setIsRepair("0");//之前是设置为1的，现在需求改了，不做这个判断，所以都设置为0
            }else {
                tsSerIllegalList.setIsRepair("0");
            }

        }



        return RestResult.ok(list);
    }

    /**
     * lwd
     * 移出前 信息验证
     * 2021-08-31
     */
    @RequestMapping(value = "/validateBiz_app", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public RestResult<?> validateBiz_app(@RequestBody Map _map) {

        String illegallistids = (String) _map.get("illegallistids");

        Map<String, String> resultMap = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        String[] illegallistidArr = illegallistids.split(Constant.SEMICOLON);
        for (String illegallistid : illegallistidArr) {
            String validateResult = this.validate(illegallistid);
            TSSerIllegalList serIllegalListModel = tsSerIllegalListService.getById(illegallistid);
            if (!"success".equals(validateResult)) {
                resultMap.put("pripid", serIllegalListModel.getPripid());
                resultMap.put("illegallistid", illegallistid);
                resultMap.put("regno", serIllegalListModel.getRegno());
                resultMap.put("entname", serIllegalListModel.getEntname());
                resultMap.put("reason", validateResult);
                resultMap.put("error", "1");
                list.add(resultMap);
            }
        }
        if (CollectionUtils.isNotEmpty(list)) return RestResult.ok(list);

        resultMap.put("success","0");
        list.add(resultMap);
        return RestResult.ok(list);
    }

    /**
     * 移出前信息验证 方法
     */
    private String validate(String illegallistid) {

        //由于行政处罚被列严，不准在移动端申请办理移出，只能请携带相关材料前往列入机关的信用部门办理
        TSBizSerIllegal tsBizSerIllegal = tsBizSerIllegalService.getById(illegallistid);
        //判断之前列入是在我们系统做的数据
//        if (tsBizSerIllegal != null && "2".equals(tsBizSerIllegal.getSourceType())) {
//            return "该企业因行政处罚被列入严重违法失信名单，如需进行信用修复，请携带相关材料前往列入机关的信用部门办理。";
//        }

        //验证 是否存在移出待办
        TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
        tsBizSerIllegalRemModel.setIllegalListID(illegallistid);
        List<TSBizSerIllegalRem> resultList = tsBizSerIllegalRemService.queryBRMserIllegalList(tsBizSerIllegalRemModel);
        if (CollectionUtils.isEmpty(resultList)) {
            return "success";  //移出业务表不存在记录 通过
        }
        //业务表不空的情况下：
        for (TSBizSerIllegalRem bizSerIllegalRemModel : resultList) {
            if ("3".equals(bizSerIllegalRemModel.getStatus())) {
                return "success";  //移出业务表存在记录 --审批未通过状态→ 通过
            }
            if ("1".equals(bizSerIllegalRemModel.getHandleStatus()) || "2".equals(bizSerIllegalRemModel.getHandleStatus())) {
                return "该记录正在被移出";//存在待办中 处于经办或审查状态，不通过
            }else {
                return "success";
            }
        }

        //校验是否存在 异议待办
        TSBizSerIllegalDiss paramModel = new TSBizSerIllegalDiss();
        paramModel.setIllegalListID(illegallistid);
        List<TSBizSerIllegalDiss> tsBizDissentList = tsBizSerIllegalDissService.selectbizDissentList(paramModel);
        if (CollectionUtils.isNotEmpty(tsBizDissentList)) {
            for (TSBizSerIllegalDiss bizSerIllegalDissModel : tsBizDissentList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(bizSerIllegalDissModel.getBizSeq());
                for (TSTaskList tsTaskListModel : tsTaskListModels) {
                    if (BaseDataConstant.BUSINESS_STATUS_TRANSACT.equals(tsTaskListModel.getBusstatus())) {
                        return "该记录正在进行异议业务";
                    }
                }
            }
        }
        return "success";
    }

    /**
     * 严重违法启动流程下一步
     * @author ???
     * @date 2023年5月31日 17:06
     * @param illegallistid
     * @param type
     * @param applicant
     * @param applicantNo
     * @param applicantId
     * @param cerno
     * @param bizseqUp
     * @return
     */
    @Transactional
    @RequestMapping(value = "/approvalnext_app")
    public RestResult<?> approvalnext_app(String illegallistid, String type,String applicant,
                                          String applicantNo, String applicantId, String cerno, String bizseqUp) {

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

        try {

            //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
            TSSerIllegalList tsSerIllegalListModel = tsSerIllegalListService.getById(illegallistid);
            List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsSerIllegalListModel.getPripid(),
                    "illegalRemoveAccept", tsSerIllegalListModel.getDecorg(), null).stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
            if (userIdList == null || userIdList.isEmpty()) {
                log.error("分派失败，受理人列表为空,tsSerIllegalListModel为：{},权限为：{}", tsSerIllegalListModel, "illegalRemoveAccept");
                throw new BusinessException("受理人列表为空！");
            } else {
                AICUser user = orgUM.findUserByPrimaryKey(userIdList.get(0));

                List<TSBizSerIllegalRem> bizRemList = new ArrayList<>();
                String decorgCode = aicorgService.getRegionCodeByUser(user);

                tsSerIllegalListModel.setYcbizseq(bizseqUp);
                tsSerIllegalListService.saveOrUpdate(tsSerIllegalListModel);

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

                //添加到 移出业务表
                TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
                tsBizSerIllegalRemModel.setBizSeq(bizseqUp);
                tsBizSerIllegalRemModel.setIllegalListID(tsSerIllegalListModel.getIllegallistid());
                tsBizSerIllegalRemModel.setPriPID(tsSerIllegalListModel.getPripid());
                tsBizSerIllegalRemModel.setRegNO(tsSerIllegalListModel.getRegno());
                tsBizSerIllegalRemModel.setEntName(tsSerIllegalListModel.getEntname());
                tsBizSerIllegalRemModel.setSerIllRea(tsSerIllegalListModel.getSerillrea());
                tsBizSerIllegalRemModel.setAbnTime(tsSerIllegalListModel.getAbntime());
                tsBizSerIllegalRemModel.setLauptime(LocalDateTime.now());
                tsBizSerIllegalRemModel.setApplyTime(LocalDateTime.now());
                tsBizSerIllegalRemModel.setDecOrg(decorgCode);
                tsBizSerIllegalRemModel.setAreaCode(decorgCode);
                tsBizSerIllegalRemModel.setApplicant(applicant);
                tsBizSerIllegalRemModel.setApplicantNo(applicantNo);
                tsBizSerIllegalRemModel.setApplicantId(applicantId);
                tsBizSerIllegalRemModel.setCerno(cerno);
                tsBizSerIllegalRemModel.setAppOrPc("0");//移动端0，pc端1
                tsBizSerIllegalRemModel.setHandleStatus("1");
                // 01-依申请移出，02-期限届满移出, 03-信用修复移出
                if ("apply".equals(type)) {
                    tsBizSerIllegalRemModel.setRemType("01");
                } else if ("timeout".equals(type)) {
                    tsBizSerIllegalRemModel.setRemType("02");
                } else if ("credit".equals(type)) {
                    tsBizSerIllegalRemModel.setRemType("03");
                }
                bizRemList.add(tsBizSerIllegalRemModel);

                //添加待办
                TSTaskList taskListModel = new TSTaskList();
                taskListModel.setBizseqid(bizseqUp);
                if ("credit".equals(type)) {
                    taskListModel.setBustype(BaseDataConstant.CREDIT_REPAIR_ILLEGAL_BIZ);
                } else {
                    taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_REMOVE); //移出严重违法失信
                }
                taskListModel.setBusname(bizRemList.get(0).getEntName());
                if (userIdList.size() == 1) {
                    taskListModel = tsBizSerIllegalRemService.saveSerListStart(user, taskListModel, bizRemList);
                } else {
                    taskListModel = tsBizSerIllegalRemService.saveSerListStartApp(user, userIdList, taskListModel, bizRemList);
                }
                //移动端过来的数据要更新为申请人的信息
                taskListModel.setSenderuserid("");
                taskListModel.setSenderorgid("");
                taskListModel.setSendername(applicant);
                taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(15));
                taskListService.updateById(taskListModel);
            }
        } catch (Exception e) {
            log.error("移出严重违法失信申请提交失败", e);
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if(e.getMessage().equals("受理人列表为空！"))
                throw new BusinessException("受理人列表为空！");
        }

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

    /**
     * 根据企业主键查询严重违法移除业务表数据
     */
    @GetMapping("/listBizSerIllegalRem")
    public RestResult<?> listBizSerIllegalRem(@RequestParam String priPid,String type) {

        Map<String, Object> parm = new HashMap<>();
        Map<String,Object> resultMap = new HashMap<>();
        parm.put("priPid",priPid);

        List<TSBizSerIllegalRem> bizSerIllegalRemList = tsBizSerIllegalRemService.selectbizRemByPriPidAndBizseq(parm);

        List<String> bizSerList = new ArrayList<>();
        List<TSBizSerIllegalRem> bizSerIllegalRemListNew = new ArrayList<>();
        //根据存储的业务号与办理状态字符串剔除重复的移除信息
        for (int i = 0; i < bizSerIllegalRemList.size(); i++) {
            String bizAndHandingNew = bizSerIllegalRemList.get(i).getBizSeq() + bizSerIllegalRemList.get(i).getHandleStatus()+"";
            if (!bizSerList.contains(bizAndHandingNew)){
                bizSerList.add(bizAndHandingNew);
                bizSerIllegalRemListNew.add(bizSerIllegalRemList.get(i));
            }
        }

        resultMap.put("TSBizSerIllegalRemList",bizSerIllegalRemListNew);

        List<TSBizRemList> tsBizRemLists = tsBizRemListService.selectbizRemByPriPidAndBIZSEQ(parm);

        List<String> bizSerAbnList = new ArrayList<>();
        List<TSBizRemList> bizRemListArrayListNew = new ArrayList<>();

        //根据存储的业务号与办理状态字符串剔除重复的移除信息
        for (int i = 0; i < tsBizRemLists.size(); i++) {
            String bizAndHandingNew = tsBizRemLists.get(i).getBizseq() + tsBizRemLists.get(i).getHandleStatus()+"";
            if (!bizSerAbnList.contains(bizAndHandingNew)){
                bizSerAbnList.add(bizAndHandingNew);
                bizRemListArrayListNew.add(tsBizRemLists.get(i));
            }
        }

        resultMap.put("TSBizRemList",bizRemListArrayListNew);

        return RestResult.ok(resultMap);

    }


    /**
     * 进入申请退回重新提交信用修复页面
     *
     * @param   _map
     * @author lwd
     * @since 2021年9月28日 15:51:25
     */
    @RequestMapping(value = "/intoCreditRepairAg_ydd", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> intoCreditRepairAg_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);//企业基本信息

        //查询经营异常删除业务流程信息
        Map<String,Object> parambizRem = new HashMap<>();
        parambizRem.put("bizseq",bizseq);
        parambizRem.put("priPid",pripid);
        List<TSBizSerIllegalRem> bizSerIllegalRemList = tsBizSerIllegalRemService.selectbizRemByPriPid(parambizRem);
        if (bizSerIllegalRemList.size()>0){
            result.put("TSBizSerIllegalRem",bizSerIllegalRemList.get(0));//经营异常删除业务流程信息
        }


        //查询严重违法失信信息
        TSSerIllegalList illegalList = tsSerIllegalListService.selecttsSerIllegalAppByid(bizSerIllegalRemList.get(0).getIllegalListID());

        Map<String,Object> param = new HashMap<>();
        param.put("bizseq",illegalList.getBizseq());
        param.put("pripid",illegalList.getPripid());

        TSSerIllegalList illegalLists = tsSerIllegalListService.selecttsSerIllegalAppByMap(param);
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        TRBaseCode trBaseCode = codeMap.get(illegalLists.getSerillrea());
        if (trBaseCode != null){
            illegalLists.setSerillreaString(trBaseCode.getName());
        }
        result.put("illegalList",illegalLists);//严重违法失信企业信息

        //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
        List<AICUser> userList = iGzaiccodeService.byPermissionListHandleUserList(eBaseinfo.getPripid(), "illegalRemoveAccept", illegalList.getDecorg(), illegalList.getDecorgCn());

        if (userList == null || userList.isEmpty()) {
            log.error("分派失败，受理人列表为空,illegalList为：{},权限为：{}", illegalList, "illegalRemoveAccept");
            throw new BusinessException("受理人列表为空！");
        }

        result.put("userList",userList);//权限人员列表

        //查询文书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;
    }

    /**
     * 根据手机号与企业名查询经办信息列表
     */
    @GetMapping("/listBizSerIllegalRemByPhoneOrName")
    public RestResult<Map> listBizSerIllegalRemByPhoneOrName(@RequestParam String applicantidOrCerno, @RequestParam String phone, String name) {
        LambdaQueryWrapper<TSBizSerIllegalRem> lqwTbtr = Wrappers.lambdaQuery();
        lqwTbtr.and(i -> i.eq(TSBizSerIllegalRem::getApplicantNo, phone)
                        .or().eq(StringUtils.isNotBlank(applicantidOrCerno), TSBizSerIllegalRem::getApplicantId, applicantidOrCerno)
                        .or().eq(StringUtils.isNotBlank(applicantidOrCerno), TSBizSerIllegalRem::getCerno, applicantidOrCerno))
                .like(StringUtils.isNotBlank(name), TSBizSerIllegalRem::getEntName, name)
                .isNotNull(TSBizSerIllegalRem::getBizSeq).ne(TSBizSerIllegalRem::getBizSeq,"");
        List<TSBizSerIllegalRem> tsBizSerIllegalRems = tsBizSerIllegalRemService.list(lqwTbtr);

        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("TSBizSerIllegalRemList", tsBizSerIllegalRems);
        LambdaQueryWrapper<TSBizRemList> lqwTbr=Wrappers.lambdaQuery();
        lqwTbr.and(i -> i.eq(TSBizRemList::getApplicantNo, phone)
                        .or().eq(StringUtils.isNotBlank(applicantidOrCerno), TSBizRemList::getApplicantId, applicantidOrCerno)
                        .or().eq(StringUtils.isNotBlank(applicantidOrCerno), TSBizRemList::getCerno, applicantidOrCerno))
                .like(StringUtils.isNotBlank(name), TSBizRemList::getEntname, name)
                .isNotNull(TSBizRemList::getBizseq).ne(TSBizRemList::getBizseq,"");
        List<TSBizRemList> tsBizRemLists = tsBizRemListService.list(lqwTbr);
        ArrayList<TSBizRemList> collect = tsBizRemLists.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TSBizRemList::getBizseq))), ArrayList<TSBizRemList>::new));

        resultMap.put("TSBizRemList",collect);

        return RestResult.ok(resultMap);
    }


    /**
     * 根据法人身份证号与企业名查询经办信息列表
     */
    @GetMapping("/listBizSerIllegalRemByCerNoOrName")
    public RestResult<Map> listBizSerIllegalRemByCerNoOrName(HttpServletRequest request,@RequestParam String cerno, String name) {
        LambdaQueryWrapper<TSBizSerIllegalRem> lqwTbtr = Wrappers.lambdaQuery();
        lqwTbtr.eq(TSBizSerIllegalRem::getCerno, cerno)
                .like(StringUtils.isNotBlank(name), TSBizSerIllegalRem::getEntName, name)
                .isNotNull(TSBizSerIllegalRem::getBizSeq).ne(TSBizSerIllegalRem::getBizSeq,"");
        List<TSBizSerIllegalRem> tsBizSerIllegalRems = tsBizSerIllegalRemService.list(lqwTbtr);
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("TSBizSerIllegalRemList", tsBizSerIllegalRems);

        LambdaQueryWrapper<TSBizRemList> lqwTbr=Wrappers.lambdaQuery();
        lqwTbr.eq(TSBizRemList::getCerno, cerno)
                .like(StringUtils.isNotBlank(name), TSBizRemList::getEntname, name)
                .isNotNull(TSBizRemList::getBizseq).ne(TSBizRemList::getBizseq,"");
        List<TSBizRemList> tsBizRemLists = tsBizRemListService.list(lqwTbr);
        ArrayList<TSBizRemList> collect = tsBizRemLists.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TSBizRemList::getBizseq))), ArrayList<TSBizRemList>::new));
        resultMap.put("TSBizRemList",collect);

        return RestResult.ok(resultMap);
    }

    /**
     * lwd
     * 从新提交申请
     * 2021-10-13
     */
    @Transactional
    @RequestMapping(value = "/approvalnextAg_app")
    public RestResult<?> approvalnextAg_app(String illegallistid, String type,String applicant,
                                            String applicantNo, String applicantId, String cerno,String bizseqUp, String priPid) {

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("bizseq",bizseqUp);
        paramMap.put("priPid",priPid);

        String bizseqUpAg = UUID.randomUUID().toString();//上传的业务号,也是待办的业务号
        Map<String, Object> resultMap = new HashMap<>();
        List<TSBizSerIllegalRem> tsBizSerIllegalRem = null;
        TSSerIllegalList tsSerIllegalListModel = null;
        String workflowid = "";
        try {
            TSBizSerIllegalRem serIllegalRemReturn = tsBizSerIllegalRemService.getOne(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq,bizseqUp)
                    .eq(TSBizSerIllegalRem::getHandleStatus,"2"));
            TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid,bizseqUp)
                    .eq(TSTaskList::getBusstatus,"5"));
            //根据移除业务，找到待办数据和业务数据
            if (serIllegalRemReturn != null && taskList != null){
                workflowid = taskList.getWorkflowid();
                //结束回退业务
                serIllegalRemReturn.setStatus("3");
                serIllegalRemReturn.setHandleStatus("5");
                serIllegalRemReturn.setLauptime(LocalDateTime.now());
                tsBizSerIllegalRemService.updateById(serIllegalRemReturn);

                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("找不到移除业务");
                }

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

                //根据主体机关和权限标识，分配对应部门，拿到对应的用户列表
                tsSerIllegalListModel = tsSerIllegalListService.getById(illegallistid);
                List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsSerIllegalListModel.getPripid(),
                        "illegalRemoveAccept", tsSerIllegalListModel.getDecorg(), null).stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
                if (userIdList == null || userIdList.isEmpty()) {
                    log.error("分派失败，受理人列表为空,tsSerIllegalListModel为：{},权限为：{}", tsSerIllegalListModel, "illegalRemoveAccept");
                    throw new BusinessException("受理人列表为空！");
                } else {
                    tsSerIllegalListModel.setYcbizseq(bizseqUpAg);
                    tsSerIllegalListService.saveOrUpdate(tsSerIllegalListModel);
                    AICUser user = orgUM.findUserByPrimaryKey(userIdList.get(0));

                    List<TSBizSerIllegalRem> bizRemList = new ArrayList<>();
                    String decorgCode = aicorgService.getRegionCodeByUser(user);

                    //移动端把业务号换成新的业务号
                    TSAttachment tsAttachmentModel = new TSAttachment();
                    tsAttachmentModel.setBizseq(bizseqUp);
                    tsAttachmentModel.setPripid(tsSerIllegalListModel.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));
                        }
                    }
                    //添加到 移出业务表
                    TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
                    tsBizSerIllegalRemModel.setBizSeq(bizseqUpAg);
                    tsBizSerIllegalRemModel.setIllegalListID(tsSerIllegalListModel.getIllegallistid());
                    tsBizSerIllegalRemModel.setPriPID(tsSerIllegalListModel.getPripid());
                    tsBizSerIllegalRemModel.setRegNO(tsSerIllegalListModel.getRegno());
                    tsBizSerIllegalRemModel.setEntName(tsSerIllegalListModel.getEntname());
                    tsBizSerIllegalRemModel.setSerIllRea(tsSerIllegalListModel.getSerillrea());
                    tsBizSerIllegalRemModel.setAbnTime(tsSerIllegalListModel.getAbntime());
                    tsBizSerIllegalRemModel.setLauptime(LocalDateTime.now());
                    tsBizSerIllegalRemModel.setApplyTime(LocalDateTime.now());
                    tsBizSerIllegalRemModel.setDecOrg(decorgCode);
                    tsBizSerIllegalRemModel.setAreaCode(decorgCode);
                    tsBizSerIllegalRemModel.setApplicant(applicant);
                    tsBizSerIllegalRemModel.setApplicantNo(applicantNo);
                    tsBizSerIllegalRemModel.setApplicantId(applicantId);
                    tsBizSerIllegalRemModel.setCerno(cerno);
                    tsBizSerIllegalRemModel.setAppOrPc("0");
                    tsBizSerIllegalRemModel.setHandleStatus("1");
                    // 01-依申请移出，02-期限届满移出, 03-信用修复移出
                    if ("apply".equals(type)) {
                        tsBizSerIllegalRemModel.setRemType("01");
                    } else if ("timeout".equals(type)) {
                        tsBizSerIllegalRemModel.setRemType("02");
                    } else if ("credit".equals(type)) {
                        tsBizSerIllegalRemModel.setRemType("03");
                    }
                    bizRemList.add(tsBizSerIllegalRemModel);

                    //添加待办
                    TSTaskList taskListModel = new TSTaskList();
                    taskListModel.setBizseqid(bizseqUpAg);
                    if ("credit".equals(type)) {
                        taskListModel.setBustype(BaseDataConstant.CREDIT_REPAIR_ILLEGAL_BIZ);
                    } else {
                        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_REMOVE); //移出严重违法失信
                    }
                    taskListModel.setBusname(bizRemList.get(0).getEntName());
                    if (userIdList.size() == 1) {
                        taskListModel = tsBizSerIllegalRemService.saveSerListStart(user, taskListModel, bizRemList);
                    } else {
                        taskListModel = tsBizSerIllegalRemService.saveSerListStartApp(user, userIdList, taskListModel, bizRemList);
                    }
                    //移动端过来的数据要更新为申请人的信息
                    taskListModel.setSenderuserid("");
                    taskListModel.setSenderorgid("");
                    taskListModel.setSendername(applicant);
                    taskListModel.setWorkflowid(workflowid);
                    taskListModel.setDeadlineDate(HolidaysUtil.getNextWorkingDay(15));
                    taskListService.updateById(taskListModel);
                }
            } 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);
        tsBizSerIllegalRem = tsBizSerIllegalRemService.selectbizRemByPriPid(paramMap);
        resultMap.put("flag","success");
        resultMap.put("tsBizSerIllegalRem",tsBizSerIllegalRem);
        return RestResult.ok(resultMap);

    }

    /**
     * 申请人在被退回后撤销业务
     * @param bizseq
     * @return
     */
    @RequestMapping("cancelBusiness")
    public RestResult<?> cancelBusiness(String bizseq) {
        tsBizSerIllegalRemService.cancelBusiness(bizseq);
        return RestResult.ok();
    }

    @PostMapping("querybyperson")
    public RestResult<?> querybyperson(String name, String cerno, String type) {
        return RestResult.ok(eBaseinfoService.querybyperson(name, cerno, type));
    }

}
