package com.chinaweal.aiccs.aiccs.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizRemList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.AbnListExcel;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.XyxfCqDto;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.TSBizRemListMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSBizRemListService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSHwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.entity.dto.*;
import com.chinaweal.aiccs.aiccs.business.mapper.TSTaskListMapper;
import com.chinaweal.aiccs.aiccs.business.service.TSHwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
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.UuidUtil;
import com.chinaweal.aiccs.crgs.system.entity.TaskList;
import com.chinaweal.aiccs.door.service.ITUserportalService;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.mapper.AicorgMapper;
import com.chinaweal.aiccs.org.mapper.TUsersMapper;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * <p>
 * 待办列表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-01-22
 */
@Service
public class TSTaskListServiceImpl extends BaseServiceImpl<TSTaskListMapper, TSTaskList> implements TSTaskListService {

    @Autowired
    private UuidUtil uuidUtil;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private TSOpinionService opinionService;

    @Resource
    private TSTwfProcessNodeService twfProcessNodeService;
    @Resource
    private TSHwfProcessNodeService hwfProcessNodeService;

    @Lazy
    @Autowired
    private EBaseinfoService eBaseinfoService;

    @Autowired
    private AicorgMapper aicorgMapper;

    @Resource
    private ITUserportalService itUserportalService;

    @Resource
    private TREntPriseTypeService entPriseTypeService;

    @Resource
    private TUsersMapper tUsersMapper;

    @Resource
    private AreaSliceService areaSliceService;
    @Lazy
    @Resource
    private TSBizSerIllegalRemService tsBizSerIllegalRemService;
    @Lazy
    @Resource
    private TSBizRemListService tsBizRemListService;
    @Resource
    private TSBizRemListMapper tsBizRemListMapper;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    /**
     * 启动待办
     *
     * @param taskListModel  待办信息
     * @param user           当前用户
     * @param definitionName 定义名称
     * @return 启动结果
     */
    @Override
    public String startWorkFlow(TSTaskList taskListModel, AICUser user, String definitionName) {
        //受理编号
//        taskListModel.setAcceptno(user.getRegionID().substring(0, 6) + uuidUtil.getCurAcceptNo());
        //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
        LocalDateTime nowLocalDateTime = LocalDateTime.now();  // 获取当前日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
        String formattedDate = nowLocalDateTime.format(formatter);  // 将日期格式化为字符串
        String acceptno = "7" + formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        taskListModel.setAcceptno(acceptno);

        ResultMap resultMap = workFlowService.startAndClaim(user.getPrimaryKey(), null, definitionName, null);
        String workflowid = resultMap.getWorkflowid();
        taskListModel.setWorkflowid(workflowid);
        taskListModel.setLinkname(resultMap.getWorkflowName());
        save(taskListModel);
        taskListModel = baseMapper.selectByWorkflowID(workflowid);

        // 统一门户待办推送
        itUserportalService.doorTaskSend(taskListModel);
        // 信创门户待办推送
        itUserportalService.doorTaskSend_XC(taskListModel);

        return taskListModel.getTasklistid();
    }

    @Override
    public String startWorkFlow(TSTaskList taskListModel, List<String> userids, String decorg, String definitionName) {
        //受理编号
//        taskListModel.setAcceptno(decorg.substring(0, 6) + uuidUtil.getCurAcceptNo());
        //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
        LocalDateTime nowLocalDateTime = LocalDateTime.now();  // 获取当前日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
        String formattedDate = nowLocalDateTime.format(formatter);  // 将日期格式化为字符串
        String acceptno = "7" + formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        taskListModel.setAcceptno(acceptno);

        ResultMap resultMap = workFlowService.startAndClaim(userids.get(0), userids, definitionName, null);
        String workflowid = resultMap.getWorkflowid();
        taskListModel.setWorkflowid(workflowid);
        taskListModel.setLinkname(resultMap.getWorkflowName());
        taskListModel.setAcceptgroupid(resultMap.getGroupid());
        save(taskListModel);
        taskListModel = baseMapper.selectByWorkflowID(workflowid);
        return taskListModel.getTasklistid();
    }

    @Override
    public TSTaskList selectByTasklistID(String taskListId) {
        return baseMapper.selectByTasklistID(taskListId);
    }

    @Override
    public void updateWorkFlow(AICUser user, TSOpinion opinionModel, TSTaskList taskListModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        ResultMap resultMap = workFlowService.completeTaskToOther(taskListModel.getWorkflowid(), nextNodeID, Arrays.asList(nextPerformerids));

        if (resultMap.isEnd()) {//流程结束
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_END);
        } else {//非结束流程
            updateTaskList(taskListModel, resultMap, nextPerformerids, nextPerformerNames);
        }
        if (opinionModel != null) {
            opinionModel.setWorkflowid(taskListModel.getWorkflowid());  //与案件不同，不需使用 TSAuditing
            opinionModel.setHandlerid(user.getPrimaryKey());
            opinionModel.setHandler(user.getName());
            if (opinionModel.getHandledate() == null) {
                opinionModel.setHandledate(LocalDateTime.now());
            }
            if (nextNodeID.equals("exptlistEnter")) { //回退
                opinionModel.setIsagree("2");
            } else if (nextNodeID.equals("approvelist")) { //通过
                opinionModel.setIsagree("0");
            } else if (nextNodeID.equals("overExptlist")) { //不通过
                opinionModel.setIsagree("1");
            }
            opinionService.saveOrUpdate(opinionModel);
        }
        taskListModel.setSenderorgid(user.getOrgID());
        taskListModel.setSenderuserid(user.getPrimaryKey());
        taskListModel.setSendername(user.getName());
        taskListModel.setSendertime(LocalDateTime.now());
        taskListModel.setLauptime(LocalDateTime.now());
        updateById(taskListModel);

//        // 统一门户待办推送
//        itUserportalService.doorTaskSendUpdate(taskListModel, resultMap.isEnd());
//
//        // 信创门户待办推送
//        itUserportalService.doorTaskSendUpdate_XC(taskListModel, resultMap.isEnd());
    }

    @Override
    public List<TSTaskList> selectByBizSeqID(String bizSeqId) {
        return list(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizSeqId));
    }

    @Override
    public TSTaskList selectByWorkflowID(String workflowid) {
        return getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getWorkflowid, workflowid));
    }

    @Override
    public IPage<TSTaskList> searchTstaskByPage(IPage<TSTaskList> page, TSTaskList tsTaskListModel, String flag, String decorg) {
        return baseMapper.searchTstaskByPage(page, tsTaskListModel, flag, decorg);
    }

    @Override
    public IPage<TSTaskList> searchPageWithProcess(IPage<TSTaskList> page, TSTaskList tsTaskList, Map<String, Object> customParamMap) {
        return baseMapper.selectPageWithProcess(page, tsTaskList, customParamMap);
    }

    @Override
    public IPage<TaskListUnionDto> searchUnionTaskPage(IPage<TaskListUnionDto> page, TaskListUnionDto taskListUnionDto, Map<String, Object> customParamMap) {
        return baseMapper.selectUnionTaskPage(page, taskListUnionDto, customParamMap);
    }

    @Override
    public Map<String, Object> unionTaskPageStatistic(Map<String, Object> customParamMap) {
        return baseMapper.unionTaskPageStatistic(customParamMap);
    }

    @Override
    public int getRiskStatistic(Map<String, Object> params) {
        return baseMapper.getRiskStatistic(params);
    }

    @Override
    public IPage<TaskListUnionDto> searchFinishTaskUnionPage(IPage<TaskListUnionDto> page, TaskListUnionDto taskListUnionParam, Map<String, Object> customParamMap) {
        IPage<TaskListUnionDto> taskListUnionDtoIPage = baseMapper.selectFinishUnionTaskPage(page, taskListUnionParam, customParamMap);
        List<Future<?>> futureList = new ArrayList<>();
        for (TaskListUnionDto each : taskListUnionDtoIPage.getRecords()) {
            futureList.add(threadPoolTaskExecutor.submit(() -> {
                TaskListUnionDto taskListUnionDto = baseMapper.selectCurrentExecUserInfo(each.getWorkflowid());
                each.setCurruserid(taskListUnionDto.getCurruserid());
                each.setCurrusername(taskListUnionDto.getCurrusername());
                each.setOrgunitid(taskListUnionDto.getOrgunitid());
                each.setOrgunitname(taskListUnionDto.getOrgunitname());
            }));
        }
        for (Future<?> each : futureList) {
            try {
                each.get();
            } catch (InterruptedException | ExecutionException e) {
            }
        }
        return taskListUnionDtoIPage;
    }

    @Override
    public List<TaskListUnionDto> searchUnionTaskList(String yclrStr, String userId) {
        return baseMapper.searchUnionTaskList(yclrStr, userId);
    }

    @Override
    public List<TaskListUnionDto> searchUnionTaskToday(String userId) {
        return baseMapper.searchUnionTaskToday(userId);
    }

    @Override
    public int countFinishToday(String userId) {
        return baseMapper.countFinishToday(userId);
    }

    @Override
    public int countFinishAll(String userId) {
        return baseMapper.countFinishAll(userId);
    }

    @Override
    public int countByBUSTYPE(String bustype, String userId) {
        return baseMapper.countByBUSTYPE(bustype, userId);
    }

    @Override
    public int countByBUSTYPEAndsourceType(String bustype, String userId, String sourceType) {
        return baseMapper.countByBUSTYPEAndsourceType(bustype, userId, sourceType);
    }

    @Override
    public int countPD(String userId) {
        return baseMapper.countPD(userId);
    }

    @Override
    public int countByUserid(String userId) {
        return baseMapper.countByUserid(userId);
    }

    @Override
    public IPage<TaskList> getCheckPage(IPage<TaskList> page, Map<String, Object> customParamMap) {
        return baseMapper.getCheckPage(page, customParamMap);
    }

    @Override
    public List<TaskListUnionDto> searchCheckList(String aicUserId) {
        return baseMapper.searchCheckList(aicUserId);
    }


    private void updateTaskList(TSTaskList taskListModel, ResultMap resultMap, String[] nextPerformerids, String[] nextPerformerNames) {
        if (resultMap.getGroupid() != null) {
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_TOSIGN);
            taskListModel.setSignuserid(nextPerformerids[0]);//指定任意一个组里的人
            String names = String.join("、", nextPerformerNames); // “、”拼接所有接收人
            taskListModel.setSignloginname(names);
            taskListModel.setSigntime(null);
            taskListModel.setAcceptgroupid(resultMap.getGroupid());
            taskListModel.setIssignon(BaseDataConstant.NO);
            taskListModel.setLauptime(resultMap.getLaupTime());
        } else {
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_TRANSACT);
            taskListModel.setSignuserid(nextPerformerids[0]);
            taskListModel.setSignloginname(nextPerformerNames[0]);
            taskListModel.setIssignon(BaseDataConstant.YES);
            taskListModel.setAcceptgroupid("");
            taskListModel.setLauptime(resultMap.getLaupTime());
        }
    }

    @Override
    public String startWorkFlowApp(TSTaskList taskListModel, String definitionName) {
        //受理编号
//        taskListModel.setAcceptno("400000" + uuidUtil.getCurAcceptNo());
        //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
        LocalDateTime nowLocalDateTime = LocalDateTime.now();  // 获取当前日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
        String formattedDate = nowLocalDateTime.format(formatter);  // 将日期格式化为字符串
        String acceptno = "7" + formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        taskListModel.setAcceptno(acceptno);

//        ResultMap resultMap = workFlowService.startAndClaim(user.getPrimaryKey(), null, definitionName, null);
        ResultMap resultMap = workFlowService.startAndClaimApp(null, null, definitionName, null);
        String workflowid = resultMap.getWorkflowid();
        taskListModel.setWorkflowid(workflowid);
        taskListModel.setLinkname(resultMap.getWorkflowName());
        save(taskListModel);
        taskListModel = baseMapper.selectByWorkflowID(workflowid);
        return taskListModel.getTasklistid();
    }

    @Override
    public void updateWorkFlowApp(TSTaskList taskListModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        ResultMap resultMap = workFlowService.completeTaskToOther(taskListModel.getWorkflowid(), nextNodeID, Arrays.asList(nextPerformerids));

        if (resultMap.isEnd()) {//流程结束
            taskListModel.setBusstatus(BaseDataConstant.BUSINESS_STATUS_END);
        } else {//非结束流程
            updateTaskList(taskListModel, resultMap, nextPerformerids, nextPerformerNames);

        }

//        taskListModel.setSenderorgid(user.getOrgID());
//        taskListModel.setSenderuserid(user.getPrimaryKey());
//        taskListModel.setSendername(user.getName());
        taskListModel.setSendertime(LocalDateTime.now());
        updateById(taskListModel);
    }

    @Override
    public List<TSTaskList> selectTaskListByBizseqid(String bizseqid) {
        return baseMapper.selectTaskListByBizseqid(bizseqid);
    }

    @Override
    public IPage<TaskListUnionDto> queryForComprehensive(IPage<TaskListUnionDto> page, Map<String, Object> customParamMap) {
        return baseMapper.queryForComprehensive(page, customParamMap);
    }

    @Override
    public List<TSTaskList> selectByBIZSEQIDANDSIGNUSERID(String BIZSEQID, String SIGNUSERID) {
        return baseMapper.selectByBIZSEQIDANDSIGNUSERID(BIZSEQID, SIGNUSERID);
    }

    @Override
    public IPage<TaskListUnionDto> comprehensiveOptimizeQuery(Page<TaskListUnionDto> page, Map<String, Object> paramMap) {

        // 统一码、企业名称同时存在时，优先按统一码查询
        String uniscid = paramMap.get("uniscid") == null ? "" : paramMap.get("uniscid").toString();
        String searchName = paramMap.get("searchName").toString();
        List<String> bizSeqList = new ArrayList<>();
        if (StringUtils.isNotBlank(uniscid)) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isUscc(uniscid)) {
                wrapper.eq(EBaseinfo::getUniscid, uniscid);
            } else {
                wrapper.eq(EBaseinfo::getRegno, uniscid);
            }
            List<EBaseinfo> eBaseinfoList = eBaseinfoService.list(wrapper);
            if (eBaseinfoList != null && eBaseinfoList.size() > 0) {
                for (EBaseinfo eBaseinfo : eBaseinfoList) {
                    List<String> busQueryConditionByPripid = baseMapper.getBusQueryConditionByPripid(eBaseinfo.getPripid());
                    if (busQueryConditionByPripid != null) {
                        bizSeqList.addAll(busQueryConditionByPripid);
                    }
                }
                paramMap.put("pripid", "pripid");
                paramMap.remove("searchName");

                if (bizSeqList == null || bizSeqList.size() == 0) {
                    return null;
                }
            } else {
                // 输入了不存在的统一码，不再往下查询
                return null;
            }
        } else if (StringUtils.isNotBlank(searchName)) {
            bizSeqList = baseMapper.getBusQueryConditionBySearchName(searchName);
        }
        paramMap.put("bizSeqList", bizSeqList);

        Object obj = paramMap.get("searchDate");
        if (obj instanceof List) {
            List list = (List) obj;
            paramMap.put("sendertimestart", list.get(0));
            paramMap.put("sendertimeend", list.get(1));
        }

        IPage<TaskListUnionDto> data = baseMapper.comprehensiveOptimizeQuery(page, paramMap);

        for (TaskListUnionDto record : data.getRecords()) {
            record.setXzqh(tUsersMapper.queryOrgByUserid(record.getSignuserid()));
            //已办结
            if (record.getBusstatus().equals("2")) {
                LambdaQueryWrapper<TSHwfProcessNode> lqw = Wrappers.lambdaQuery();
                lqw.eq(TSHwfProcessNode::getProcessid, record.getWorkflowid());
                lqw.orderByDesc(TSHwfProcessNode::getCreatedon);
                List<TSHwfProcessNode> list = hwfProcessNodeService.list(lqw);
                if (!list.isEmpty()) {
                    record.setCurrentNodeOrBizStatus(list.get(0).getCurrentnode());
                    String nodeflow = list.get(0).getNodeflow();
                    int i = nodeflow.indexOf("_");
                    record.setLastNode(nodeflow.substring(Math.max(i + 1, 0)));
                }
            } else {
                LambdaQueryWrapper<TSTwfProcessNode> lqw = Wrappers.lambdaQuery();
                lqw.eq(TSTwfProcessNode::getProcessid, record.getWorkflowid());
                lqw.orderByDesc(TSTwfProcessNode::getCreatedon);
                List<TSTwfProcessNode> list = twfProcessNodeService.list(lqw);
                if (!list.isEmpty()) {
                    record.setCurrentNodeOrBizStatus(list.get(0).getCurrentnode());
                    String nodeflow = list.get(0).getNodeflow();
                    int i = nodeflow.indexOf("_");
                    record.setLastNode(nodeflow.substring(Math.max(i + 1, 0)));
                }
            }
        }

        return data;
    }

    @Override
    public IPage<TSAbnList> queryAbnList(Page<TSAbnList> page, Map<String, Object> paramMap) {
        String searchUscc = StringUtils.tranObject(paramMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                paramMap.put("uniscid", searchUscc);
            } else {
                paramMap.put("regno", searchUscc);
            }
        }

        Object intoObj = paramMap.get("searchIntoDate");
        if (intoObj instanceof List) {
            List list = (List) intoObj;
            paramMap.put("startIntoDate", list.get(0));
            paramMap.put("endIntoDate", list.get(1));
        }
        Object remObj = paramMap.get("searchRemDate");
        if (remObj instanceof List) {
            List list = (List) remObj;
            paramMap.put("startRemDate", list.get(0));
            paramMap.put("endRemDate", list.get(1));
        }

        if (StringUtils.isNotBlank(StringUtils.tranObject(paramMap.get("regulatory")))) {
            List<String> regulatory = (List<String>) paramMap.get("regulatory");
            if (regulatory.size() > 0) {
                String suporg = regulatory.get(regulatory.size() - 1);
                List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                idsByParentId.add(suporg);      //加上父id
                paramMap.put("sliceIds", idsByParentId);
            }
        }

        IPage<TSAbnList> data = null;
        data = baseMapper.queryAbnList(page, paramMap);
        //封装主体类型名称
        data.getRecords().forEach(each -> {
            TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
            if (type != null) {
                each.setEnttypeCN(type.getDisplayvalue());
            }
        });
        return data;
    }

    @Override
    public List<AbnListExcel> exportAbnList(Map<String, Object> paramMap) {
        String searchUscc = StringUtils.tranObject(paramMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                paramMap.put("uniscid", searchUscc);
            } else {
                paramMap.put("regno", searchUscc);
            }
        }

        Object intoObj = paramMap.get("searchIntoDate");
        if (intoObj instanceof List) {
            List list = (List) intoObj;
            paramMap.put("startIntoDate", list.get(0));
            paramMap.put("endIntoDate", list.get(1));
        }
        Object remObj = paramMap.get("searchRemDate");
        if (remObj instanceof List) {
            List list = (List) remObj;
            paramMap.put("startRemDate", list.get(0));
            paramMap.put("endRemDate", list.get(1));
        }

        if (StringUtils.isNotBlank(StringUtils.tranObject(paramMap.get("regulatory")))) {
            List<String> regulatory = (List<String>) paramMap.get("regulatory");
            if (regulatory.size() > 0) {
                String suporg = regulatory.get(regulatory.size() - 1);
                List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                idsByParentId.add(suporg);      //加上父id
                paramMap.put("sliceIds", idsByParentId);
            }
        }

        List<AbnListExcel> data = null;
        data = baseMapper.exportAbnList(paramMap);
        return data;
    }

    @Override
    public List<OrgUnits> queryAllOrg() {
        return aicorgMapper.queryAllOrg();
    }

    @Override
    public IPage<TaskListUnionDto> queryOldeBusness(Page<TaskListUnionDto> page, Map<String, Object> paramMap) {
        String uniscid = paramMap.get("uniscid") == null ? "" : paramMap.get("uniscid").toString();
        if (StringUtils.isNotBlank(uniscid)) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isUscc(uniscid)) {
                wrapper.eq(EBaseinfo::getUniscid, uniscid);
            } else {
                wrapper.eq(EBaseinfo::getRegno, uniscid);
            }
            List<EBaseinfo> eBaseinfos = eBaseinfoService.list(wrapper);

            if (eBaseinfos != null && eBaseinfos.size() > 0) {
                paramMap.put("pripids", eBaseinfos.stream().map(EBaseinfo::getPripid).collect(Collectors.toList()));
            } else {
                // 输入了不存在的统一码，不再往下查询
                return null;
            }
        }
        Object obj = paramMap.get("searchDate");
        if (obj instanceof List) {
            List list = (List) obj;
            paramMap.put("sendertimestart", list.get(0));
            paramMap.put("sendertimeend", list.get(1));
        }
        String busStatus = paramMap.get("busStatus") == null ? "" : paramMap.get("busStatus").toString();
        if (StringUtils.isNotBlank(busStatus)) {
            if (!"4".equals(busStatus)) return null;
        }
        IPage<TaskListUnionDto> data = null;
        data = baseMapper.queryOldeBusness(page, paramMap);
        return data;
    }

    @Override
    public IPage<RepairTaskListDto> repairTaskQuery(Page<RepairTaskListDto> page, Map<String, Object> paramMap) {
        boolean isGzrNum = paramMap.containsKey("gzrNumSwitch") && (boolean) paramMap.get("gzrNumSwitch");
        if (isGzrNum) {
            int gzrNum = (int) paramMap.get("gzrNum");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (gzrNum < 0) {
                paramMap.put("gzrDate", LocalDateTime.now().format(formatter));
            } else {
                LocalDateTime gzrEndDate = gzrNum == 0 ? LocalDateTime.now().withHour(23).withMinute(59).withSecond(59) : HolidaysUtil.getNextWorkingDay(gzrNum);
                LocalDateTime gzrStartDate = gzrEndDate.withHour(0).withMinute(0).withSecond(0);
                paramMap.put("gzrStartDate", gzrStartDate.format(formatter));
                paramMap.put("gzrEndDate", gzrEndDate.format(formatter));
            }
        }
        IPage<RepairTaskListDto> data = baseMapper.repairTaskQuery(page, paramMap);
        Map<String, String> params = new HashMap<>();
        params.put("deleted", "0");
        params.put("unittype", "1");
        for (RepairTaskListDto repairTaskListDto : data.getRecords()) {
            params.put("orgNumber", repairTaskListDto.getAreaCode());
            OrgUnits orgUnits = aicorgMapper.queryByOrgNumberMap(params);
            repairTaskListDto.setOrgName(orgUnits == null ? "" : orgUnits.getOrgUnitName());

            if (BaseDataConstant.CREDIT_REPAIR_ILLEGAL_BIZ.equals(repairTaskListDto.getBustype())) {
                List<TSBizSerIllegalRem> tsBizSerIllegalRemList = tsBizSerIllegalRemService.selectbizRembizseq(repairTaskListDto.getBizseqid());
                if (CollUtil.isNotEmpty(tsBizSerIllegalRemList)) {
                    repairTaskListDto.setStatus(tsBizSerIllegalRemList.get(0).getStatus());
                }
            } else {
                List<TSBizRemList> tsBizRemList = tsBizRemListService.selectbizRembizseq(repairTaskListDto.getBizseqid());
                if (CollUtil.isNotEmpty(tsBizRemList)) {
                    repairTaskListDto.setStatus(tsBizRemList.get(0).getStatus());
                }
            }

            if (repairTaskListDto.getDeadlineDate() != null) {
                Date startDate = new DateTime(repairTaskListDto.getDeadlineDate());
                Date endDate = new DateTime(LocalDateTime.now());
                int days = HolidaysUtil.getWorkingDaysBetweenDates(startDate, endDate);
                if (startDate.before(endDate)) {
                    days = days * -1;
                }
                repairTaskListDto.setDeadlineDay(days);
            }
        }
        return data;
    }

    @Override
    public IPage<XyxfCqDto> queryxyxfCqList(Page<XyxfCqDto> page, Map<String, Object> paramMap) {
        String entType = StringUtils.tranObject(paramMap.get("entType"));


        Object intoObj = paramMap.get("searchIntoDate");
        if (intoObj instanceof List) {
            List list = (List) intoObj;
            paramMap.put("startIntoDate", list.get(0));
            paramMap.put("endIntoDate", list.get(1));
        }

        IPage<XyxfCqDto> data = null;
        if ("0".equals(entType)) {
            data = tsBizRemListMapper.queryxyxfCqList(page, paramMap);
        } else {
            data = tsBizRemListMapper.queryxyxfCqYzfwList(page, paramMap);
        }
        if (data != null) {
            // 2. 获取分页数据列表
            List<XyxfCqDto> records = data.getRecords();

            // 3. 遍历数据
            for (XyxfCqDto item : records) {
                // 处理每条数据
                if ("12".equals(item.getBustype())) {
                    item.setBustype("个体工商户恢复");
                } else if ("7".equals(item.getBustype())) {
                    item.setBustype("移除企业异常名录");
                } else if ("14".equals(item.getBustype())) {
                    item.setBustype("农民专业合作社移除");
                } else if ("33".equals(item.getBustype())) {
                    item.setBustype("移出严重违法失信");
                } else {
                    item.setBustype(null);
                }
            }
            data.setRecords(records);
        }
        return data;
    }

    @Override
    public List<XyxfCqDto> exportxyxfCqList(Map<String, Object> paramMap) {
        String entType = StringUtils.tranObject(paramMap.get("entType"));


        Object intoObj = paramMap.get("searchIntoDate");
        if (intoObj instanceof List) {
            List list = (List) intoObj;
            paramMap.put("startIntoDate", list.get(0));
            paramMap.put("endIntoDate", list.get(1));
        }

        List<XyxfCqDto> data = null;
        if ("0".equals(entType)) {
            data = tsBizRemListMapper.exportqueryxyxfCqList(paramMap);
        } else {
            data = tsBizRemListMapper.exportqueryxyxfCqYzfwList(paramMap);
        }

        if (data != null) {
            // 3. 遍历数据
            for (XyxfCqDto item : data) {
                // 处理每条数据
                if ("12".equals(item.getBustype())) {
                    item.setBustype("个体工商户恢复");
                } else if ("7".equals(item.getBustype())) {
                    item.setBustype("移除企业异常名录");
                } else if ("14".equals(item.getBustype())) {
                    item.setBustype("农民专业合作社移除");
                } else if ("33".equals(item.getBustype())) {
                    item.setBustype("移出严重违法失信");
                } else {
                    item.setBustype(null);
                }
            }
        }
        return data;
    }

    @Override
    public TSTaskList searchTaskListByBizId(String bizId) {
        return getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizId));
    }

    @Override
    public List<RepairTaskStatisticDto> repairTaskStatistic(Map<String, Object> paramMap, AICUser aicUser) {
        //判断有没有受理机关的条件
        String orgNumber = (String) paramMap.get("orgNumber");
        Map<String, String> params = new HashMap<>();
        params.put("deleted", "0");
        params.put("unittype", "1");
        if (StringUtils.isEmpty(orgNumber)) {
            params.put("orgNumber", aicUser.getRegionID());
            OrgUnits org = aicorgMapper.queryByOrgNumberMap(params);
            Integer orgLevel = org.getOrgLevel();
            //根据机构等级判断
            if (orgLevel == 1) {    //省局
                paramMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 2) + "%");
            } else if (orgLevel == 2) {    //市局
                paramMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 4) + "%");
            } else if (orgLevel == 3) {    //区局
                paramMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 6) + "%");
            } else if (orgLevel >= 4) {    //所
                paramMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 6) + "%");
            }
        }

        boolean isGzrNum = paramMap.containsKey("gzrNumSwitch") && (boolean) paramMap.get("gzrNumSwitch");
        if (isGzrNum) {
            int gzrNum = (int) paramMap.get("gzrNum");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (gzrNum < 0) {
                paramMap.put("gzrDate", LocalDateTime.now().format(formatter));
            } else {
                LocalDateTime gzrEndDate = gzrNum == 0 ? LocalDateTime.now().withHour(23).withMinute(59).withSecond(59) : HolidaysUtil.getNextWorkingDay(gzrNum);
                LocalDateTime gzrStartDate = gzrEndDate.withHour(0).withMinute(0).withSecond(0);
                paramMap.put("gzrStartDate", gzrStartDate.format(formatter));
                paramMap.put("gzrEndDate", gzrEndDate.format(formatter));
            }
        }

        List<RepairTaskStatisticDto> repairTaskStatisticDtos = baseMapper.repairTaskStatistic(paramMap);
        for (RepairTaskStatisticDto dto : repairTaskStatisticDtos) {
            params.put("orgNumber", dto.getOrgNumber());
            OrgUnits orgUnits = aicorgMapper.queryByOrgNumberMap(params);
            dto.setOrgName(orgUnits == null ? "" : orgUnits.getOrgUnitName());
        }
        return repairTaskStatisticDtos;
    }

    @Override
    public Map<String, Object> indexPageStatistic(Map<String, Object> customParamMap, AICUser aicUser) {
        Map<String, Object> map = new HashMap<>();
        customParamMap.put("areaCode", aicUser.getRegionID());
        //统计信用修复正常、即将超期、超期的数量
        Map<String, Object> repairStatistic = baseMapper.indexPageRepairStatistic(customParamMap);
        map.put("repairStatistic", repairStatistic);

        //统计经营异常主体类型分布
        Map<String, Object> entTypeStatistic = baseMapper.tsAbnEntTypeStatistic();
        map.put("entTypeStatistic", entTypeStatistic);

        //统计各地区经营异常主体数量
        List<OrgUnits> orgList = aicorgMapper.selectList(new LambdaQueryWrapper<OrgUnits>()
                .eq(OrgUnits::getParentId, aicUser.getOrgID())
                .eq(OrgUnits::getDeleted, "0")
                .eq(OrgUnits::getUnitType, "1"));
        //提取出机构ID
        List<String> orgUnitIds = orgList.stream()
                .map(OrgUnits::getOrgNumber)
                .collect(Collectors.toList());
        orgUnitIds.add(0, aicUser.getRegionID()); // 在索引0位置插入当前用户的regionID
        customParamMap.put("orgList", orgUnitIds);

        List<AbnEntLocStatistic> abnEntLocStatistic = baseMapper.tsAbnEntLocStatistic(customParamMap);
        //处理机构名称
        Map<String, String> params = new HashMap<>();
        params.put("deleted", "0");
        params.put("unittype", "1");
        params.put("parentID", aicUser.getOrgID());
        for (AbnEntLocStatistic item : abnEntLocStatistic) {
            params.put("orgNumber", item.getOrgNumber());
            OrgUnits orgUnits = aicorgMapper.queryByOrgNumberMap(params);
            item.setOrgName(orgUnits == null ? "" : orgUnits.getOrgUnitName());
        }
        map.put("abnEntLocStatistic", abnEntLocStatistic);

        return map;
    }

}
