package com.chinaweal.aiccs.aiccs.business.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
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.TSAbnList;
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.mapper.ToincludeabnMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSTaskListEnterType;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.auditing.service.TSTaskListEnterTypeService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.entity.dto.RepairTaskListDto;
import com.chinaweal.aiccs.aiccs.business.entity.dto.RepairTaskStatisticDto;
import com.chinaweal.aiccs.aiccs.business.entity.dto.TaskListUnionDto;
import com.chinaweal.aiccs.aiccs.business.entity.excel.TaskListRepairData;
import com.chinaweal.aiccs.aiccs.business.mapper.TSTaskListMapper;
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.fraudreg.entity.TFraudCheck;
import com.chinaweal.aiccs.aiccs.fraudreg.service.ITFraudCheckService;
import com.chinaweal.aiccs.aiccs.market.entity.TSUsualInspect;
import com.chinaweal.aiccs.aiccs.market.service.ITSSueInspectService;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.system.entity.DeadlineStas;
import com.chinaweal.aiccs.aiccs.system.service.DeadlinestasService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.DateUtils;
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.org.entity.OrgUnits;
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.service.TfRevokeServicelmpl;
import com.chinaweal.aicorg.model.AICUser;
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.AssertUtils;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 待办任务控制器
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/2/7 8:59
 **/
@RestController
@RequestMapping("task")
public class TaskController extends BaseController {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSTaskListEnterTypeService taskListEnterTypeService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TSTwfProcessNodeService twfProcessNodeService;
    @Autowired
    private TfRevokeServicelmpl tfRevokeServicelmpl;
    @Resource
    private SMSServiceImpl smsService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService tsOpinionService;
    @Autowired
    private DeadlinestasService deadlinestasService;
    @Resource
    private TSTaskListMapper tsTaskListMapper;
    @Resource
    private TUsersService tUsersService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private ToincludeabnMapper toincludeabnMapper;
    @Resource
    private ITFraudCheckService itFraudCheckService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Resource
    private TSBizRemListMapper tsBizRemListMapper;
    @Autowired
    private ITSUsualInspectService itsUsualInspectService;
    @Resource
    private ITSSueInspectService iTSSueInspectService;
    @Autowired
    private AicorgService aicorgService;

    /**
     * 代办分页
     *
     * @param pageRequestDto 分页参数
     * @param request        分页请求
     * @return 分页结果
     * @author lroyia
     * @since 2021年2月7日 09:02:33
     */
    @PostMapping("common_page")
    public RestResult<?> getTaskPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        pageRequestDto.checkDefault(null, null, "SENDERTIME");
        AICUser curUser = getLoginUser(request);
//        String appid = "2cc35f3016b6470684d67a0dcc85b223";
//        String appsecret = "istUFExQqyZLGzoquzUTIVnsUvZplfmK5sa2qOougPrV7jJKeZ+QJvRjOuUIRVqA0WwFMhSkO6AFE1w89iwXD9Ji/ZwH0tvsQq3ei6O1aWs6+E+IcGn1aqJzh/iC75iomcW5ZFWQ8WcuokP+0Z+vqj2v4NN0Vdm9hCGAKZrO+6O733YrmHxEI1O66EqOOZzPiYTqgWCkugo1P3jlryDRm3Nua0lUlMcuQ89wtsTBfkpnxDRVday1NqN9+oodXNlokI4ktihLWkpY1jFtAU9Q1BgluvPXBWh4e5z4N8kGgxT4Q2cK/LoxFEiI0cofcrS9HhZn3OP4sOE16Mh0tlloNg==";
//
//        String token = tfRevokeServicelmpl.queryTfToken(appid, appsecret);
//        Map<String,Object> param = new HashMap<>();
//        Map<String,Object> params = new HashMap<>();
//        param.put("pripid","440106106012019060653262");
//        param.put("uniscid","91440101MA5CRTA310");
//        param.put("entname","广东德培利文化旅游发展有限公司");
//        param.put("revokerea","001");
//        param.put("revokedate","2021-06-16");
//        param.put("apprdocno","1234567");
//        param.put("apprdept","市场部门");
//        param.put("affwriteno","无");
//        param.put("pubnewsname","无");
//        param.put("userid","213123123");
//        param.put("username","张三");
//
//        params.put("aicode","revocationAiccode");
//        params.put("param",param);
//
//        String result = tfRevokeServicelmpl.pushRevocation(token, params);


        // 封装分页参数
        TSTaskList taskListParam = new TSTaskList();
        taskListParam.setSignuserid(curUser.getPrimaryKey());

        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
//        customParamMap.put("bustype","33");
        // 获取待办分页
        IPage<TSTaskList> page = taskListService.searchPageWithProcess(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), taskListParam, customParamMap);

        // 补充主体类型
        List<TSTaskList> records = page.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            List<String> workflowIds = records.stream().map(TSTaskList::getWorkflowid).collect(Collectors.toList());
            List<TSTaskListEnterType> taskListEnterTypes = taskListEnterTypeService.list(new LambdaQueryWrapper<TSTaskListEnterType>().in(TSTaskListEnterType::getWorkflowId, workflowIds));
            Map<String, String> typeMap = new HashMap<>();
            for (TSTaskListEnterType each : taskListEnterTypes) {
                typeMap.put(each.getWorkflowId(), each.getEnterType());
            }
            for (TSTaskList each : records) {
                each.setEnterType(typeMap.get(each.getWorkflowid()));
            }
        }
        return RestResult.ok(page);
    }

    /**
     * 代办分页
     *
     * @param pageRequestDto 分页参数
     * @param request        分页请求
     * @return 分页结果
     * @author Lee
     * @since 2021年6月1日 09:32:33
     */
    @PostMapping("taskUnionPage")
    public RestResult<?> taskUnionPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        IPage<TaskListUnionDto> page = getTaskUnionPage(pageRequestDto, request);
        return RestResult.ok(page);
    }

    /**
     * 获取分页待办数据
     */
    private IPage<TaskListUnionDto> getTaskUnionPage(PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);

        // 封装分页参数
        TaskListUnionDto taskListParam = new TaskListUnionDto();
        taskListParam.setSignuserid(curUser.getPrimaryKey());

        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        if (customParamMap != null && customParamMap.get("UNISCIDORREGNO") != null) {
            if (StringUtils.isNotBlank(customParamMap.get("UNISCIDORREGNO").toString())) {
                String uscc = customParamMap.get("UNISCIDORREGNO").toString();
                if (StringUtils.isUscc(uscc)) {
                    customParamMap.put("UNISCID", uscc);
                } else {
                    customParamMap.put("REGNO", uscc);
                }
            }
        }
        // 处理业务类型、业务状态查询参数
        AICUser aicUser = getLoginUser(request);
        if (customParamMap != null && customParamMap.get("bustype") != null && customParamMap.get("busstatus") != null && customParamMap.get("bustypeAndCurrentNode") != null) {
            Object bustypeAndStatus1 = customParamMap.get("bustypeAndStatus");
            if (bustypeAndStatus1 instanceof List<?>) {
                if (((List<?>) bustypeAndStatus1).size() > 0) {
                    String bustype = StringUtils.tranObject(((List<?>) bustypeAndStatus1).get(0));
                    customParamMap.put("bustype", bustype);
                    if (((List<?>) bustypeAndStatus1).size() > 1) {
                        String currentNodeOrBizStatus = StringUtils.tranObject(((List<?>) bustypeAndStatus1).get(1));
                        customParamMap.put("currentNodeOrBizStatus", currentNodeOrBizStatus);
                    }
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("deleted", "0");
        map.put("unittype", "1");
        // 信用修复
        if (customParamMap != null && customParamMap.get("type") != null && "repair".equals(customParamMap.get("type"))) {
            //处理年报申请过来的信用修复待办
            //倒计时工作日开关
            boolean isGzrNum = customParamMap.containsKey("gzrNumSwitch") && (boolean) customParamMap.get("gzrNumSwitch");
            if (isGzrNum) {
                int gzrNum = (int) customParamMap.get("gzrNum");
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                if (gzrNum < 0) {
                    customParamMap.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);
                    customParamMap.put("gzrStartDate", gzrStartDate.format(formatter));
                    customParamMap.put("gzrEndDate", gzrEndDate.format(formatter));
                }
            }
            //是否显示下级单位的待办
            boolean isChildUnit = customParamMap.containsKey("childUnitSwitch") && (boolean) customParamMap.get("childUnitSwitch");
            if (isChildUnit) {  //查下级待办
                customParamMap.put("checkChildUnit", "1");
                //这一步进行判断，且允许上级办理下级的信用修复
                map.put("orgNumber", aicUser.getRegionID());
                OrgUnits org = aicorgService.queryByOrgNumberMap(map);
                Integer orgLevel = org.getOrgLevel();
                //根据机构等级判断
                if (orgLevel == 1) {    //省局
                    customParamMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 2) + "%");
                } else if (orgLevel == 2) {    //市局
                    customParamMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 4) + "%");
                } else if (orgLevel == 3) {    //区局
                    customParamMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 6) + "%");
                } else if (orgLevel >= 4) {    //所
                    customParamMap.put("areaCode", StringUtils.substring(aicUser.getRegionID(), 0, 6) + "%");
                }
            } else {
                customParamMap.put("checkChildUnit", "0");
                customParamMap.put("areaCode", aicUser.getRegionID());
            }
        }

        // 获取待办分页
        if (customParamMap != null && !customParamMap.containsKey("areaCode")) {    //判断如果没有加区域的值，就给用户所在区局
            customParamMap.put("areaCode", aicUser.getRegionID());
        }
        IPage<TaskListUnionDto> page = taskListService.searchUnionTaskPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), taskListParam, customParamMap);
        List<TaskListUnionDto> taskListUnionDtoList = page.getRecords();
        for (TaskListUnionDto taskListUnionDto : taskListUnionDtoList) {
            List<TSOpinion> tsOpinions = tsOpinionService.queryByWorkflowId(taskListUnionDto.getWorkflowid());
            if (tsOpinions.size() > 0) {
                TSOpinion tsOpinion = tsOpinions.get(0);
                taskListUnionDto.setIsagree(tsOpinion.getIsagree());
            }
            // 个体户名称为空导致待办名称为空，将个体户经营者回显
            if (StringUtils.isBlank(taskListUnionDto.getBusname())) {
                String bustype = taskListUnionDto.getBustype();
                switch (bustype) {
                    case "12":
                        taskListUnionDto.setBusname(tsBizRemListMapper.queryLerep(taskListUnionDto.getBizseqid()));
                        break;
                    default:
                        break;
                }
            }
            if (BaseDataConstant.MARKET_INSPECT.equals(taskListUnionDto.getBustype())) {
                TSUsualInspect tsUsualInspect = itsUsualInspectService.getById(taskListUnionDto.getBizseqid());
                // 回退待核查
                if (tsUsualInspect != null && StringUtils.isNotBlank(tsUsualInspect.getBackOpinion()))
                    taskListUnionDto.setCurrentNodeOrBizStatus("bak-startInspect");
            }
            if (taskListUnionDto.getDeadlineDate() != null) {
                Date startDate = new DateTime(taskListUnionDto.getDeadlineDate());
                Date endDate = new DateTime(LocalDateTime.now());
                int days = HolidaysUtil.getWorkingDaysBetweenDates(startDate, endDate);
                if (startDate.before(endDate)) {
                    days = days * -1;
                }
                taskListUnionDto.setDeadlineDay(days);
            }

            //补充受理机关中文（信用修复）
            map.put("orgNumber", taskListUnionDto.getAreaCode());
            OrgUnits org = aicorgService.queryByOrgNumberMap(map);
            taskListUnionDto.setAreaCode(org == null ? "" : org.getOrgUnitName());
        }
        return page;
    }

    @PostMapping("taskUnionPageStatistic")
    public RestResult<?> getTaskUnionPageStatistic(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);

        // 封装分页参数
        TaskListUnionDto taskListParam = new TaskListUnionDto();
        taskListParam.setSignuserid(curUser.getPrimaryKey());

        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        customParamMap.put("areaCode", curUser.getRegionID());

        if (customParamMap != null && customParamMap.get("UNISCIDORREGNO") != null) {
            if (StringUtils.isNotBlank(customParamMap.get("UNISCIDORREGNO").toString())) {
                String uscc = customParamMap.get("UNISCIDORREGNO").toString();
                if (StringUtils.isUscc(uscc)) {
                    customParamMap.put("UNISCID", uscc);
                } else {
                    customParamMap.put("REGNO", uscc);
                }
            }
        }

        // 处理业务类型、业务状态查询参数
        if (customParamMap != null && customParamMap.get("bustypeAndStatus") != null) {
            Object bustypeAndStatus1 = customParamMap.get("bustypeAndStatus");
            if (bustypeAndStatus1 instanceof List<?>) {
                if (((List<?>) bustypeAndStatus1).size() > 0) {
                    String bustype = StringUtils.tranObject(((List<?>) bustypeAndStatus1).get(0));
                    customParamMap.put("bustype", bustype);
                    if (((List<?>) bustypeAndStatus1).size() > 1) {
                        String currentNodeOrBizStatus = StringUtils.tranObject(((List<?>) bustypeAndStatus1).get(1));
                        customParamMap.put("currentNodeOrBizStatus", currentNodeOrBizStatus);
                    }
                }
            }
        }

        //信用风险分类
        // 单独获取信用风险分类监管待办
        int risk = taskListService.getRiskStatistic(customParamMap);

        Map<String, Object> map = new HashMap<>();
        map = taskListService.unionTaskPageStatistic(customParamMap);
        map.put("risknum", risk);

        return RestResult.ok(map);
    }


    /**
     * 已办分页
     *
     * @param pageRequestDto 分页参数
     * @param request        分页请求
     * @return 分页结果
     * @author Lee
     * @since 2021年5月26日 15点59分
     */
    @PostMapping("taskFinishPage")
    public RestResult<?> getTaskFinishPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        pageRequestDto.checkDefault(null, null, "SENDERTIME");
        AICUser curUser = getLoginUser(request);

        // 封装分页参数
        TSTaskList taskListParam = new TSTaskList();
        taskListParam.setSignuserid(curUser.getPrimaryKey());

        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String bustype = "";
        String searchName = "";
        String acceptno = "";

        if (customParamMap != null) {
            bustype = StringUtils.tranObject(customParamMap.get("bustype"));
            searchName = StringUtils.tranObject(customParamMap.get("searchName"));
            acceptno = StringUtils.tranObject(customParamMap.get("acceptno"));
        }
        // 获取待办分页
        LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSTaskList::getBusstatus, "2")
                .eq(StringUtils.isNotBlank(bustype), TSTaskList::getBustype, bustype)
                .eq(StringUtils.isNotBlank(acceptno), TSTaskList::getAcceptno, acceptno)
                .eq(StringUtils.isNotBlank(searchName), TSTaskList::getBusname, searchName)
                .orderByDesc(TSTaskList::getLauptime);
        IPage<TSTaskList> page = taskListService.page(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), wrapper);

//        IPage<TSTaskList> page = taskListService.searchPageWithProcess(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), taskListParam, customParamMap);

        // 补充主体类型
        List<TSTaskList> records = page.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            List<String> workflowIds = records.stream().map(TSTaskList::getWorkflowid).collect(Collectors.toList());
            List<TSTaskListEnterType> taskListEnterTypes = taskListEnterTypeService.list(new LambdaQueryWrapper<TSTaskListEnterType>().in(TSTaskListEnterType::getWorkflowId, workflowIds));
            Map<String, String> typeMap = new HashMap<>();
            for (TSTaskListEnterType each : taskListEnterTypes) {
                typeMap.put(each.getWorkflowId(), each.getEnterType());
            }
            for (TSTaskList each : records) {
                each.setEnterType(typeMap.get(each.getWorkflowid()));
            }
        }
        return RestResult.ok(page);
    }

    /**
     * 已办分页 汇总
     *
     * @param pageRequestDto 分页参数
     * @param request        分页请求
     * @return 分页结果
     * @author Lee
     * @since 2021年6月4日 09:35:00
     */
    @PostMapping("finishTaskUnionPage")
    public RestResult<?> finishTaskUnionPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);

        // 封装分页参数
        TaskListUnionDto taskListParam = new TaskListUnionDto();
        taskListParam.setSignuserid(curUser.getPrimaryKey());

        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();

        if (customParamMap != null && customParamMap.get("UNISCIDORREGNO") != null) {
            if (StringUtils.isNotBlank(customParamMap.get("UNISCIDORREGNO").toString())) {
                String uscc = customParamMap.get("UNISCIDORREGNO").toString();
                if (StringUtils.isUscc(uscc)) {
                    customParamMap.put("UNISCID", uscc);
                } else {
                    customParamMap.put("REGNO", uscc);
                }
            }
        }

        // 处理业务类型、业务状态查询参数
        if (customParamMap != null && customParamMap.get("bustypeAndCurrentNode") != null) {
            Object bustypeAndCurrentNode = customParamMap.get("bustypeAndCurrentNode");
            if (bustypeAndCurrentNode instanceof List<?>) {
                if (((List<?>) bustypeAndCurrentNode).size() > 0) {
                    String bustype = StringUtils.tranObject(((List<?>) bustypeAndCurrentNode).get(0));
                    customParamMap.put("bustype", bustype);
                    if (((List<?>) bustypeAndCurrentNode).size() > 1) {
                        String currentNode = StringUtils.tranObject(((List<?>) bustypeAndCurrentNode).get(1));
                        if ("noAccept".equals(currentNode)) {
                            customParamMap.put("currentNode", "endDissent");
                            customParamMap.put("lastNode", "handleDissentAccept");
                        } else if ("noRegister".equals(currentNode)) {
                            customParamMap.put("currentNode", "endRevoke");
                            customParamMap.put("lastNode", "noRegister");
                        } else {
                            customParamMap.put("currentNode", currentNode);
                        }
                    }
                }
            }
        }

        if (customParamMap != null && customParamMap.get("createDate") != null) {
            Object searchDate = customParamMap.get("createDate");
            if (searchDate instanceof List) {
                List<String> list = (List<String>) searchDate;
                customParamMap.put("startDate", list.get(0));
                customParamMap.put("endDate", list.get(1));
            }
        }

        if (customParamMap != null && customParamMap.containsKey("childUnitSwitch")) {
            String myOrgNumber = StringUtils.clearRegionZero(curUser.getRegionID());
            if (StringUtils.isNotBlank(myOrgNumber)) {
                customParamMap.put("myOrgNumber", myOrgNumber);
                customParamMap.put("myOrgNumberLike", myOrgNumber + "%");
            }
        }

        // 获取已办分页
        IPage<TaskListUnionDto> page = taskListService.searchFinishTaskUnionPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), taskListParam, customParamMap);

        page.getRecords().forEach(each -> {
            if (BaseDataConstant.SERILLEGAL_TYPE_ENTERSERILLEGAL.equals(each.getBustype())) { // 严重违法列入
                if (!FlowUtil.SERIOUS_ILLEGAL_CITY_EXAMINE_SUCCESS.equals(each.getCurrentNodeOrBizStatus()) &&
                        !FlowUtil.SERIOUS_ILLEGAL_ENDARCHIVES.equals(each.getCurrentNode())) { // 不是市局的审批通过待归档 和 归档状态
                    // 判断是否通过第一伦区局审批
                    List<TSTwfProcessNode> nodes = tsTwfProcessNodeService.list(
                            new LambdaQueryWrapper<TSTwfProcessNode>().eq(TSTwfProcessNode::getProcessid, each.getWorkflowid())
                                    .eq(TSTwfProcessNode::getCurrentnode, FlowUtil.SERIOUS_ILLEGAL_BUREAU_EXAMINE_SUCCESS));
                    if (nodes.size() > 0) {
                        each.setIsPrint("1");
                    }
                }
            }
        });
        return RestResult.ok(page);
    }

    /**
     * 任务处办记录列表
     *
     * @param workflowId 工作流id
     * @return 处办记录列表
     * @author lroyia
     * @since 2021年2月8日 09:37:32
     */
    @RequestMapping("opinion")
    public RestResult<List<TSOpinion>> getTaskOpinion(String workflowId) {
        AssertUtils.isNotBlank(workflowId);
        return RestResult.ok(opinionService.getOpinionsWithOrg(workflowId));
    }

    /**
     * 打印审批表同意意见列表 要改
     *
     * @param workflowId 工作流id
     * @return 意见列表
     */
    @RequestMapping("opinionPrint")
    public RestResult<List<TSOpinion>> getTaskOpinionPrint(String workflowId) {
        AssertUtils.isNotBlank(workflowId);
        TSTaskList tsTaskList = taskListService.selectByWorkflowID(workflowId);
        //获取按时间降序，意见流程0 1 2排序好的意见列表
        List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                .eq(TSOpinion::getWorkflowid, workflowId)
                .orderByAsc(TSOpinion::getOpiniontype).orderByDesc(TSOpinion::getLauptime));
        ArrayList<TSOpinion> resultList = new ArrayList<>();
        boolean flag0 = false;
        boolean flag1 = false;
        boolean flag2 = false;
        if (tsTaskList.getBustype().equals("5") || tsTaskList.getBustype().equals("71")) {
            //将最新同意意见加入结果resultList
            for (TSOpinion item : list) {
                if ("1".equals(item.getOpiniontype()) && !flag0) {
                    resultList.add(item);
                    flag0 = true;
                }
                if ("2".equals(item.getOpiniontype()) && !flag1) {
                    resultList.add(item);
                    flag1 = true;
                }
                if ("3".equals(item.getOpiniontype()) && !flag2) {
                    resultList.add(item);
                    flag2 = true;
                }
            }
        } else {
            //将最新同意意见加入结果resultList
            for (TSOpinion item : list) {
                if ("0".equals(item.getOpiniontype()) && !flag0) {
                    resultList.add(item);
                    flag0 = true;
                }
                if ("1".equals(item.getOpiniontype()) && !flag1) {
                    resultList.add(item);
                    flag1 = true;
                }
                if ("2".equals(item.getOpiniontype()) && !flag2) {
                    resultList.add(item);
                    flag2 = true;
                }
            }
        }

        return RestResult.ok(resultList);
    }

    /**
     * 通过待办id获取待办信息
     *
     * @param taskListId 待办id
     * @return 待办信息
     * @author lroyia
     * @since 2021年3月12日 10:52:39
     */
    @GetMapping("/{taskListId}")
    public RestResult<TSTaskList> getTaskList(@ApiParam("待办列表id") @PathVariable String taskListId) {
        return RestResult.ok(taskListService.getById(taskListId));
    }

    /**
     * 获取流程节点信息
     *
     * @param workflowId 流程id
     * @return 获取结果
     * @author lroyia
     * @since 2021年3月12日 11:16:39
     */
    @GetMapping("processNodeList/{workflowId}")
    public RestResult<List<TSTwfProcessNode>> getProcessNodeList(@ApiParam("工作流id") @PathVariable String workflowId) {
        return RestResult.ok(twfProcessNodeService.list(new LambdaQueryWrapper<TSTwfProcessNode>()
                .eq(TSTwfProcessNode::getProcessid, workflowId)
                .orderByDesc(TSTwfProcessNode::getCreatedon, TSTwfProcessNode::getLauptime)));
    }

    /**
     * 信用惩戒与联合惩戒待办总数
     *
     * @author lwd
     * @since 2021年6月29日 21:32:33
     */
    @PostMapping("getAbnormal2")
    public RestResult<?> getAbnormal2(String aicUserId) {

        Map<String, Object> resultMap = new HashMap<>();
        //企业异常名录列入
        String yclrStr = "5";
        List<TaskListUnionDto> yclr = taskListService.searchUnionTaskList(yclrStr, aicUserId);
        //企业异常名录异议
        String ycyyStr = "6";
        List<TaskListUnionDto> ycyy = taskListService.searchUnionTaskList(ycyyStr, aicUserId);
        //企业异常名录移除
        String ycycStr = "7";
        List<TaskListUnionDto> ycyc = taskListService.searchUnionTaskList(ycycStr, aicUserId);
        //个体工商户标记
        String gtbjStr = "11";
        List<TaskListUnionDto> gtbj = taskListService.searchUnionTaskList(gtbjStr, aicUserId);
        //个体工商户恢复
        String gthfStr = "12";
        List<TaskListUnionDto> gthf = taskListService.searchUnionTaskList(gthfStr, aicUserId);
        //农专列入
        String nzlrStr = "13";
        List<TaskListUnionDto> nzlr = taskListService.searchUnionTaskList(nzlrStr, aicUserId);
        //农专移出
        String nzycStr = "14";
        List<TaskListUnionDto> nzyc = taskListService.searchUnionTaskList(nzycStr, aicUserId);
        //严重违法列入
        String yzwflrStr = "15";
        List<TaskListUnionDto> yzwflr = taskListService.searchUnionTaskList(yzwflrStr, aicUserId);
        //严重违法异议
        String yzwfyyStr = "16";
        List<TaskListUnionDto> yzwfyy = taskListService.searchUnionTaskList(yzwfyyStr, aicUserId);
        //严重违法移除
        String yzwfycStr = "17";
        List<TaskListUnionDto> yzwfyc = taskListService.searchUnionTaskList(yzwfycStr, aicUserId);
        //冒用他人信息
        String myxxcStr = "31";
        List<TaskListUnionDto> myxx = taskListService.searchUnionTaskList(myxxcStr, aicUserId);
        //批量吊销
        String pldxStr = "51";
        List<TaskListUnionDto> pldx = taskListService.searchUnionTaskList(pldxStr, aicUserId);
        //问题处置反馈
        String wtczfk = "32";
        List<TaskListUnionDto> wtcz = taskListService.searchUnionTaskList(wtczfk, aicUserId);
        //信用修复
        String xyxf = "33";
        List<TaskListUnionDto> xyxF = taskListService.searchUnionTaskList(xyxf, aicUserId);
        //总局一体化
        String zjyth = "30";
        List<TaskListUnionDto> zjytH = taskListService.searchUnionTaskList(zjyth, aicUserId);
        //异议申请
        List<TaskListUnionDto> yysq = taskListService.searchCheckList(aicUserId);
        //联合惩戒锁定
        String lhcjsd = "61";
        List<TaskListUnionDto> lhcjsD = taskListService.searchUnionTaskList(lhcjsd, aicUserId);
        //联合惩戒解锁
        String lhcjjs = "62";
        List<TaskListUnionDto> lhcjjS = taskListService.searchUnionTaskList(lhcjjs, aicUserId);

        //经营异常拟列入列表总数
        int nlrjyyc = 0;
        AICUser curUser = SSOUtil.getUser();

        // 不再用假待办
//        Map<String, AICPermission> aicPermissions = curUser.getAicPermissions();
//        if (aicPermissions.get("exptInclueEnter") != null) {
//            //获取当前用户的机构，判断是区局还是所级，获取对应的机构单位ID列表
//            LambdaQueryWrapper<Gzaiccode> lqw = Wrappers.lambdaQuery();
//            List<String> orgunitids = new ArrayList<>();
//            Map<String, Object> customParamMap = new HashMap<>();
//            if ("001".equals(curUser.getOrgID())) {
//                //市局的账号
//                //判断是不是登记注册二处
//                if ("f7b2117a-ee80-4470-930e-03f106f3e031".equals(curUser.getUnitID())) {
//                    customParamMap.put("twoPlaces", "440129");//查询受理机关
//                } else {
//                    customParamMap.put("regOrg", "440101");//查询登记机关
//                }
//            } else {
//                //非市局登记的主体，先按照登记机关分派至区局经办人岗，再按照属地监管所进行判断，分派至属地监管所的经办人岗，状态为待受理；区局的则查自己还有下面的子级所，所的用户则查询所有
//                List<OrgUnits> orgUnits = tUsersService.byNextLevelPlace(curUser.getOrgID());
//                List<String> collect = orgUnits.stream().map(OrgUnits::getOrgUnitId).collect(Collectors.toList());
//                orgunitids.addAll(collect);
//                lqw.in(Gzaiccode::getOrgunitid, orgunitids);
//                List<Gzaiccode> gzaiccodeList = iGzaiccodeService.list(lqw);
//                //对应企业主体机属地监管机构代码列表
//                List<String> scountrycodes = gzaiccodeList.stream().map(Gzaiccode::getScountrycode).collect(Collectors.toList());
//                customParamMap.put("scountrycodes", scountrycodes);//监管机关
//            }
//            IPage<ToIncludeAbnDto> page = toincludeabnMapper.listByOrg(new Page<>(1, 1), customParamMap);
//            nlrjyyc = (int) page.getTotal();
//        }

        // 撤销登记实地核查
        Integer cxdjsdhc = 0;
        if (curUser.getAicPermissions().containsKey("fraudRegOneAssign")) {
            if (curUser.getRegionID().length() == 6) {
                cxdjsdhc = itFraudCheckService.lambdaQuery().ne(TFraudCheck::getStatus, "4").eq(TFraudCheck::getDomdistrict, curUser.getRegionID()).count();
            } else {
                cxdjsdhc = itFraudCheckService.lambdaQuery().eq(TFraudCheck::getStatus, "1").eq(TFraudCheck::getSendOrg, curUser.getRegionID()).count();
            }
            resultMap.put("cxdjsdhc", cxdjsdhc);
        }

        // 每日新增待办
        int mrxz = taskListService.searchUnionTaskToday(aicUserId).size();
        // 已办数量
        int yb = taskListService.countFinishAll(aicUserId);
        // 每日新增已办
        int mryb = taskListService.countFinishToday(aicUserId);
        //待办总数
        int dbzs = Integer.valueOf(yclr.size()) + Integer.valueOf(ycyy.size()) + Integer.valueOf(ycyc.size())
                + Integer.valueOf(gtbj.size()) + Integer.valueOf(gthf.size()) + Integer.valueOf(nzlr.size()) + Integer.valueOf(nzyc.size())
                + Integer.valueOf(yzwflr.size()) + Integer.valueOf(yzwfyy.size()) + Integer.valueOf(yzwfyc.size())
                + Integer.valueOf(pldx.size()) + Integer.valueOf(myxx.size())
                + Integer.valueOf(wtcz.size())
                + Integer.valueOf(xyxF.size()) + Integer.valueOf(zjytH.size()) + Integer.valueOf(yysq.size())
                + Integer.valueOf(lhcjsD.size()) + Integer.valueOf(lhcjjS.size()) + cxdjsdhc;


        resultMap.put("jyyc", Integer.valueOf(yclr.size()) + Integer.valueOf(ycyy.size()) + Integer.valueOf(ycyc.size())
                + Integer.valueOf(gtbj.size()) + Integer.valueOf(gthf.size()) + Integer.valueOf(nzlr.size()) + Integer.valueOf(nzyc.size()));
        resultMap.put("yzwfsx", Integer.valueOf(yzwflr.size()) + Integer.valueOf(yzwfyy.size()) + Integer.valueOf(yzwfyc.size()));
        resultMap.put("pldx", Integer.valueOf(pldx.size()));
        resultMap.put("mytrxx", Integer.valueOf(myxx.size()));
        resultMap.put("qyjyycml", Integer.valueOf(yclr.size()) + Integer.valueOf(ycyy.size()) + Integer.valueOf(ycyc.size()));
        resultMap.put("gthjyyczt", Integer.valueOf(gtbj.size()) + Integer.valueOf(gthf.size()));
        resultMap.put("nzsjyycml", Integer.valueOf(nzlr.size()) + Integer.valueOf(nzyc.size()));
        resultMap.put("yzwflr", Integer.valueOf(yzwflr.size()));
        resultMap.put("yzwfyy", Integer.valueOf(yzwfyy.size()));
        resultMap.put("yzwfyc", Integer.valueOf(yzwfyc.size()));
        resultMap.put("wtfkcz", Integer.valueOf(wtcz.size()));
        resultMap.put("xyxf", Integer.valueOf(xyxF.size()));
        resultMap.put("zjyth", Integer.valueOf(zjytH.size()));
        resultMap.put("yysq", Integer.valueOf(yysq.size()));
        resultMap.put("lhcjsD", Integer.valueOf(lhcjsD.size()));
        resultMap.put("lhcjjS", Integer.valueOf(lhcjjS.size()));
        resultMap.put("dbzs", dbzs);
        resultMap.put("mrxz", mrxz);
        resultMap.put("yb", yb);
        resultMap.put("mryb", mryb);
        resultMap.put("gtbj", Integer.valueOf(gtbj.size()));
        resultMap.put("yclr", Integer.valueOf(yclr.size()));
        resultMap.put("nzlr", Integer.valueOf(nzlr.size()));
        resultMap.put("ycyy", Integer.valueOf(ycyy.size()));
        resultMap.put("ycyc", Integer.valueOf(ycyc.size()));
        resultMap.put("nzyc", Integer.valueOf(nzyc.size()));
        resultMap.put("gthf", Integer.valueOf(gthf.size()));
        return RestResult.ok(resultMap);
    }

    @PostMapping("getAbnormal")
    public RestResult<?> getAbnormal(String aicUserId) {

        Map<String, Object> resultMap = new HashMap<>();
        //企业异常名录列入
        String yclrStr = "5";
        int yclr = taskListService.countByBUSTYPE(yclrStr, aicUserId);
        //企业异常名录异议
        String ycyyStr = "6";
        int ycyy = taskListService.countByBUSTYPE(ycyyStr, aicUserId);
        //企业异常名录移除
        String ycycStr = "7";
        int ycyc = taskListService.countByBUSTYPE(ycycStr, aicUserId);
        //个体工商户标记
        String gtbjStr = "11";
        int gtbj = taskListService.countByBUSTYPE(gtbjStr, aicUserId);
        //个体工商户恢复
        String gthfStr = "12";
        int gthf = taskListService.countByBUSTYPE(gthfStr, aicUserId);
        //农专列入
        String nzlrStr = "13";
        int nzlr = taskListService.countByBUSTYPE(nzlrStr, aicUserId);
        //农专移出
        String nzycStr = "14";
        int nzyc = taskListService.countByBUSTYPE(nzycStr, aicUserId);
        //严重违法拟列入
        String yzwfnlrStr = "55";
        int yzwfnlr = taskListService.countByBUSTYPE(yzwfnlrStr, aicUserId);
        //严重违法列入
        String yzwflrStr = "15";
        int yzwflr = taskListService.countByBUSTYPE(yzwflrStr, aicUserId);
        // 严重违法列入(列异满3年)
        int yzwflrthree = taskListService.countByBUSTYPEAndsourceType(yzwflrStr, aicUserId, "1");
        // 严重违法列入（行政处罚）
        int yzwflrxzcf = taskListService.countByBUSTYPEAndsourceType(yzwflrStr, aicUserId, "2");
        //严重违法异议
        String yzwfyyStr = "16";
        int yzwfyy = taskListService.countByBUSTYPE(yzwfyyStr, aicUserId);
        //严重违法移除
        String yzwfycStr = "17";
        int yzwfyc = taskListService.countByBUSTYPE(yzwfycStr, aicUserId);
        //冒用他人信息
        String myxxcStr = "31";
        int myxx = taskListService.countByBUSTYPE(myxxcStr, aicUserId);
        //批量吊销
        String pldxStr = "51";
        int pldx = taskListService.countPD(aicUserId);
        //问题处置反馈
        String wtczfk = "32";
        int wtcz = taskListService.countByBUSTYPE(wtczfk, aicUserId);
        //信用修复
        String xyxf = "33";
        int xyxF = taskListService.countByBUSTYPE(xyxf, aicUserId);
        //总局一体化
        String zjyth = "30";
        int zjytH = taskListService.countByBUSTYPE(zjyth, aicUserId);
        //异议申请

        //联合惩戒锁定
        String lhcjsd = "61";
        int lhcjsD = taskListService.countByBUSTYPE(lhcjsd, aicUserId);
        //联合惩戒解锁
        String lhcjjs = "62";
        int lhcjjS = taskListService.countByBUSTYPE(lhcjjs, aicUserId);

        //现场核查任务
        String xchcrwStr = "66";
        int xchcrw = taskListService.countByBUSTYPE(xchcrwStr, aicUserId);

        //投诉处理
        AICUser curUser = SSOUtil.getUser();

        //经营异常拟列入列表总数
        int nlrjyyc = 0;
        // 撤销登记实地核查
        Integer cxdjsdhc = 0;
        if (curUser.getAicPermissions().containsKey("fraudRegOneAssign")) {
            if (curUser.getRegionID().length() == 6) {
                cxdjsdhc = itFraudCheckService.lambdaQuery().ne(TFraudCheck::getStatus, "4").eq(TFraudCheck::getDomdistrict, curUser.getRegionID()).count();
            } else {
                cxdjsdhc = itFraudCheckService.lambdaQuery().eq(TFraudCheck::getStatus, "1").eq(TFraudCheck::getSendOrg, curUser.getRegionID()).count();
            }
            resultMap.put("cxdjsdhc", cxdjsdhc);
        }

        // 每日新增待办
        int mrxz = taskListService.searchUnionTaskToday(aicUserId).size();
        // 已办数量
        int yb = taskListService.countFinishAll(aicUserId);
        // 每日新增已办
        int mryb = taskListService.countFinishToday(aicUserId);
        //待办总数
        int dbzs = yclr + ycyy + ycyc
                + gtbj + gthf + nzlr + nzyc
                + yzwfnlr + yzwflr + yzwfyy + yzwfyc
                + pldx + myxx
                + wtcz
                + xyxF + zjytH
                + lhcjsD + lhcjjS + cxdjsdhc
                + xchcrw;

        resultMap.put("jyyc", yclr + ycyy + ycyc
                + gtbj + gthf + nzlr + nzyc);
        resultMap.put("yzwfsx", yzwflr + yzwfyy + yzwfyc);
        resultMap.put("pldx", pldx);
        resultMap.put("mytrxx", myxx);
        resultMap.put("qyjyycml", yclr + ycyy + ycyc);
        resultMap.put("gthjyyczt", gtbj + gthf);
        resultMap.put("nzsjyycml", nzlr + nzyc);
        resultMap.put("yzwfnlr", yzwfnlr);
        resultMap.put("yzwflrthree", yzwflrthree);
        resultMap.put("yzwflrxzcf", yzwflrxzcf);
        resultMap.put("yzwflr", yzwflr);
        resultMap.put("yzwfyy", yzwfyy);
        resultMap.put("yzwfyc", yzwfyc);
        resultMap.put("wtfkcz", wtcz);
        resultMap.put("xyxf", xyxF);
        resultMap.put("zjyth", zjytH);
        resultMap.put("lhcjsD", lhcjsD);
        resultMap.put("lhcjjS", lhcjjS);
        resultMap.put("dbzs", dbzs);

        resultMap.put("mrxz", mrxz);
        resultMap.put("yb", yb);
        resultMap.put("mryb", mryb);
        resultMap.put("gtbj", gtbj);
        resultMap.put("yclr", yclr);
        resultMap.put("nzlr", nzlr);
        resultMap.put("ycyy", ycyy);
        resultMap.put("ycyc", ycyc);
        resultMap.put("nzyc", nzyc);
        resultMap.put("gthf", gthf);
        resultMap.put("xchcrw", xchcrw);

        return RestResult.ok(resultMap);
    }

    /**
     * 综合查询
     * 经营异常名录查询
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @RequestMapping("/queryAbnList")
    public RestResult<?> queryAbnList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto);
        AICUser curUser = SSOUtil.getUser();
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        paramMap.put("curUser", curUser);
        Page<TSAbnList> page = new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize());
        IPage<TSAbnList> rs = taskListService.queryAbnList(page, paramMap);
        return RestResult.ok(rs);
    }

    /**
     * 综合查询
     * 经营异常名录查询
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("/exportAbnList")
    public void exportAbnList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AssertUtils.isNotNull(pageRequestDto);
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        //Page<AbnListExcel> page = new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize());
        List<AbnListExcel> rs = taskListService.exportAbnList(paramMap);

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("经营异常名单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ExcelWriter excelWriter = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            excelWriter = EasyExcel.write(bos, AbnListExcel.class).inMemory(true).build();
            excelWriter.write(rs, EasyExcel.writerSheet("列异信息").registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build());
            // 结束
            excelWriter.finish();
            response.getOutputStream().write(bos.toByteArray());
        } finally {
            // 结束
            if (excelWriter != null) excelWriter.finish();
        }
    }

    /**
     * 综合查询-业务查询 （不含批吊业务查询，已分离）
     *
     * @param pageRequestDto
     * @return
     */
    @RequestMapping("/businessQuery")
    public RestResult<?> businessQuery(@RequestBody PageRequestDto pageRequestDto) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        Page<TaskListUnionDto> page = new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize());
        IPage<TaskListUnionDto> rs = taskListService.comprehensiveOptimizeQuery(page, paramMap);
        return RestResult.ok(rs);
    }

    /**
     * 综合查询-旧业务查询
     *
     * @param pageRequestDto
     * @return
     */
    @RequestMapping("/queryOldeBusness")
    public RestResult<?> queryOldeBusness(@RequestBody PageRequestDto pageRequestDto) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        Page<TaskListUnionDto> page = new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize());
        IPage<TaskListUnionDto> rs = taskListService.queryOldeBusness(page, paramMap);
        return RestResult.ok(rs);
    }

    @ApiOperation("严重违法信用修复期限")
    @PostMapping("isDeadline")
    public Boolean isDeadline(String tasklistid) throws Exception {
        AssertUtils.isNotBlank(tasklistid);
        TSTaskList taskList = taskListService.getById(tasklistid);
        LocalDateTime createTime = taskList.getCreateTime();
        //总时长15天，超过10个工作日，在第11天预警
        String createDateStr = DateUtils.localDateFormat(createTime.toLocalDate(), DateUtils.DATE_DEFAULT_FORMAT);
        String workDayEnd = DateUtils.getWorkDayEnd(null, createDateStr, 11);
        LocalDate workEndDate = DateUtils.parseLocalDate(workDayEnd, DateUtils.DATE_DEFAULT_FORMAT);
        int leftDays = (int) LocalDate.now().toEpochDay() - (int) workEndDate.toEpochDay();
        if (leftDays >= 0) {
            return true;
        } else {//在各自环节剩余办理超过时限会预警 经办：4天 审核：3天 审批：3天
            String currentnode = workFlowService.findCurrentNode(taskList.getWorkflowid()).getCurrentnode();
            DeadlineStas deadlineStas = deadlinestasService.getByWorkflowId(taskList.getWorkflowid());

            boolean overTime = false;
            //在经办
            if (deadlineStas != null) {
                if (FlowUtil.SERILLEGALWORKFLOW_SERILLEGALENTER.equals(currentnode)) {
                    overTime = isOverTime(deadlineStas.getAcceptStartDate(), Integer.parseInt(deadlineStas.getAcceptLeftDays()), LocalDate.now());
                } else if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(currentnode)) {//在审核
                    overTime = isOverTime(deadlineStas.getHandleStartDate(), Integer.parseInt(deadlineStas.getHandleLeftDays()), LocalDate.now());
                } else if (FlowUtil.SERILLEGALWORKFLOW_APPORSERILLEGALENTER.equals(currentnode)) {//在审批
                    overTime = isOverTime(deadlineStas.getApproveStartDate(), Integer.parseInt(deadlineStas.getApproveLeftDays()), LocalDate.now());

                }
            }
            return overTime;
        }
    }

    private boolean isOverTime(LocalDate sDate, Integer days, LocalDate eDate) {
        int dutyDays = DateUtils.getDutyDays(sDate, eDate);
        if (dutyDays > days) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取未办结的件，当前环节信息
     *
     * @return
     */
    @GetMapping("/currentValidNode")
    public RestResult<TSTwfProcessNode> currentValidNode(@RequestParam String workflowId) {
        LambdaQueryWrapper<TSTwfProcessNode> lqw = Wrappers.lambdaQuery();
        lqw.eq(TSTwfProcessNode::getProcessid, workflowId)
                .eq(TSTwfProcessNode::getStatus, "0");
        TSTwfProcessNode tsTwfProcessNode = twfProcessNodeService.getOne(lqw);
        return RestResult.ok(tsTwfProcessNode);
    }

    @GetMapping("/queryAllOrg")
    public RestResult<?> queryAllOrg() {
        return RestResult.ok(taskListService.queryAllOrg());
    }

    /**
     * 信用修复预警待办分析
     *
     * @param pageRequestDto
     * @return
     * @author ymc
     * @since 2024年8月1日 11:53
     */
    @RequestMapping("/repairTaskQuery")
    public RestResult<?> repairTaskQuery(@RequestBody PageRequestDto pageRequestDto) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        IPage<RepairTaskListDto> rs = taskListService.repairTaskQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap);
        Map<Object, String> map = new HashMap<>();
        map.put("total", String.valueOf(rs.getTotal()));
        map.put("rows", String.valueOf(rs.getRecords()));
        map.put("page", String.valueOf(rs.getCurrent()));
        map.put("size", String.valueOf(rs.getSize()));
        map.put("sfsdf", "fsgdg");
        return RestResult.ok(rs);
    }

    /**
     * 导出信用修复待办
     *
     * @param pageRequestDto
     * @param request
     * @return
     * @author ymc
     * @since 2024年8月5日 15:41
     */
    @PostMapping("exportRepairTask")
    public void exportRepairTask(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        pageRequestDto.setCurPage(-1);
        pageRequestDto.setPageSize(-1);
        IPage<RepairTaskListDto> page = taskListService.repairTaskQuery(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap);
        List<RepairTaskListDto> pageRecords = page.getRecords();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("信用修复待办名单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<TaskListRepairData> taskListRepairDataList = BeanUtil.copyToList(pageRecords, TaskListRepairData.class);
        EasyExcel.write(response.getOutputStream(), TaskListRepairData.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自定义宽度
                .sheet("信用修复待办名单")
                .doWrite(taskListRepairDataList);
    }

    /**
     * 综合查询
     * 信用修复超期查询
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @RequestMapping("/queryxyxfCqList")
    public RestResult<?> queryxyxfCqList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto);
        AICUser curUser = SSOUtil.getUser();
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        if (curUser != null) {
            if ("440101".equals(curUser.getRegionID())) {
                paramMap.put("regorg", "4401" + "%");
            } else {
                paramMap.put("regorg", curUser.getRegionID().substring(0, 6) + "%");
            }
        }

        Page<XyxfCqDto> page = new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize());
        IPage<XyxfCqDto> rs = taskListService.queryxyxfCqList(page, paramMap);
        return RestResult.ok(rs);
    }

    /**
     * 综合查询
     * 经营异常名录查询
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("/exportxyxfCqList")
    public void exportxyxfCqList(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AssertUtils.isNotNull(pageRequestDto);
        AICUser curUser = SSOUtil.getUser();
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        if (curUser != null) {
            if ("440101".equals(curUser.getRegionID())) {
                paramMap.put("regorg", "4401" + "%");
            } else {
                paramMap.put("regorg", curUser.getRegionID().substring(0, 6) + "%");
            }
        }
//        List<XyxfCqDto> rs = taskListService.exportxyxfCqList(paramMap);
//
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode(
//                "信用修复超期名单_" + System.currentTimeMillis(),
//                "UTF-8"
//        );
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//
//        ExcelWriter excelWriter = null;
//        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
//            excelWriter = EasyExcel.write(bos, XyxfCqDto.class).inMemory(true).build();
//            excelWriter.write(rs, EasyExcel.writerSheet("信用修复超期名单").registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build());
//            // 结束
//            excelWriter.finish();
//            response.getOutputStream().write(bos.toByteArray());
//        }finally {
//            // 结束
//            if (excelWriter != null) excelWriter.finish();
//        }

        // 获取数据列表
        List<XyxfCqDto> rs = taskListService.exportxyxfCqList(paramMap);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(
                "信用修复超期名单_" + System.currentTimeMillis(),
                "UTF-8"
        );
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 使用更简洁的EasyExcel写入方式
        EasyExcel.write(response.getOutputStream(), XyxfCqDto.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("信用修复超期名单")
                .doWrite(rs);
    }

    /**
     * 信用修复预警统计
     */
    @RequestMapping("/repairTaskStatistic")
    public RestResult<?> repairTaskStatistic(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        AICUser aicUser = getLoginUser(request);
        //统计内外网的数量，只统计未完成的
        List<RepairTaskStatisticDto> repairTaskStatisticDto = taskListService.repairTaskStatistic(paramMap, aicUser);
        return RestResult.ok(repairTaskStatisticDto);
    }

    /**
     * 待办总览统计
     * type：1：统计各地区经营异常主体数量    2：统计经营异常主体类型分布
     *
     * @param pageRequestDto
     * @param request
     * @return
     */
    @PostMapping("indexPageStatistic")
    public RestResult<?> indexPageStatistic(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        Map<String, Object> map = taskListService.indexPageStatistic(customParamMap, curUser);
        return RestResult.ok(map);
    }
}
