package com.friday.tooldriver.service.rpa.driverimpl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.friday.tooldriver.dto.infodator.common.FilterEntity;
import com.friday.tooldriver.dto.infodator.common.MainFileDto;
import com.friday.tooldriver.dto.infodator.common.PageParam;
import com.friday.tooldriver.dto.infodator.common.TemplateAttachmentDto;
import com.friday.tooldriver.dto.infodator.request.AddVersionRequestDto;
import com.friday.tooldriver.dto.infodator.request.CreateProcessDto;
import com.friday.tooldriver.dto.infodator.request.GroupRequestDto;
import com.friday.tooldriver.dto.infodator.request.QueryRequestDto;
import com.friday.tooldriver.dto.infodator.response.*;
import com.friday.tooldriver.dto.infodator.response.Process;
import com.google.common.collect.Lists;
import com.friday.base.common.response.DubboResult;
import com.friday.operation.api.tooldriver.dto.common.DriverBase;
import com.friday.operation.api.tooldriver.dto.rpa.*;
import com.friday.tooldriver.constants.infodator.InfodatorRobotState;
import com.friday.tooldriver.dto.infodator.common.*;
import com.friday.tooldriver.dto.infodator.request.*;
import com.friday.tooldriver.dto.infodator.response.*;
import com.friday.tooldriver.service.strategy.ICapabilityDriverService;
import com.friday.tooldriver.service.rpa.supplier.INFODATORService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author YaoYao
 * @Date Created In 18:52 2022/12/1
 * @Description 容智驱动能力实现服务类
 * @Modified By
 */
@Service("INFODATORDriver")
public class INFODATORDriverServiceImpl implements ICapabilityDriverService {

    @Autowired
    private INFODATORService infodatorService;

    /**
     * 查询条件入参
     * @param classType 类型
     * @param fieldName 字段名
     * @param filterComparator 条件策略
     * @param params 参数
     * @param filters 入参对象
     */
    private void addFilters (String classType, String fieldName, String filterComparator, Object params, List<Map<String, Object>> filters) {
        Map<String,Object> filterMap = new HashMap<>();
        filterMap.put("@classType", classType);
        filterMap.put("fieldName", fieldName);
        filterMap.put("filterComparator", filterComparator);
        filterMap.put("params", params);
        filters.add(filterMap);
    }

    @Override
    public DubboResult<TenantDto> createTenant(DriverBase driverBase, TenantDto tenant) {
        return null;
    }

    @Override
    public DubboResult<ArrayList<TenantDto>> queryTenants(DriverBase driverBase, TenantSelectFilter filter) {
        return null;
    }

    @Override
    public DubboResult<TenantDto> queryTenantByKey(DriverBase driverBase, String key) {
        return null;
    }

    @Override
    public DubboResult deleteTenantByKey(DriverBase driverBase, String key) {
        return null;
    }

    @Override
    public DubboResult updateTenantByKey(DriverBase driverBase, String key) {
        return null;
    }

    @Override
    public DubboResult activateTenantByKey(DriverBase driverBase, String key) {
        return null;
    }

    @Override
    public DubboResult<GroupDto> createGroup(DriverBase driverBase, GroupDto group) {
        String groupName = group.getName();
        // 先查询组存不存在
        GroupFilter filter = GroupFilter.groupFilterBuilder().name(groupName).build();
        DubboResult<ArrayList<GroupDto>> queryGroupsResult = this.queryGroups(driverBase, filter);
        if (!queryGroupsResult.success()) {
            return DubboResult.newFailure(queryGroupsResult.getCode(), queryGroupsResult.getMessage());
        }
        ArrayList<GroupDto> groupDtoList = queryGroupsResult.getObject();
        if (CollectionUtils.isNotEmpty(groupDtoList)) {
            // 组存在直接返回
            return DubboResult.newSuccess(groupDtoList.get(0));
        }
        // 组不存在新建组
        GroupRequestDto groupRequestDto = GroupRequestDto.builder()
                .name(groupName)
                .description(group.getDescription())
                .build();
        DubboResult<GroupResponseDto> result = infodatorService.addGroup(driverBase, groupRequestDto);
        if (result.success()) {
            GroupResponseDto groupResponseDto = result.getObject();
            GroupDto groupResponse = groupResponseDto.createInfodatorGroupDto();
            return DubboResult.newSuccess(groupResponse);
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult<ArrayList<GroupDto>> queryGroups(DriverBase driverBase, GroupFilter filter) {
        List<Map<String,Object>> filters = Lists.newArrayList();
        addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
        if (StringUtils.isNotEmpty(filter.getName())) {
            addFilters("comparator", "name", "CONTAINS", new String[]{filter.getName()}, filters);
        }
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder()
                        .pageNo(0)
                        .pageSize(9999)
                        .build())
                .filter(FilterEntity.builder()
                        .classType("logic")
                        .logicOperator("AND")
                        .filters(filters.toArray())
                        .build())
                .sortFields(null)
                .build();
        UUID uuid = UUID.randomUUID();
        DubboResult<ArrayList<GroupResponseDto>> result = infodatorService.getAllGroupName(driverBase, queryRequestDto, uuid.toString());
        if (result.success()) {
            List<GroupResponseDto> groupList = result.getObject();
            List<GroupDto> list = groupList.stream().map(GroupResponseDto::createInfodatorGroupDto).collect(Collectors.toList());
            return DubboResult.newSuccess(Lists.newArrayList(list));
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult<GroupDto> queryGroupByKey(DriverBase driverBase, String key) {
        DubboResult<GroupResponseDto> result = infodatorService.getGroupByKey(driverBase, Integer.parseInt(key));
        if (result.success()) {
            GroupDto groupDto = result.getObject().createInfodatorGroupDto();
            return DubboResult.newSuccess(groupDto);
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult deleteGroupByKey(DriverBase driverBase, String key) {
        return infodatorService.deleteGroup(driverBase, key);
    }

    @Override
    public DubboResult<CodePackageDto> uploadPackage(DriverBase driverBase, CodePackageDto pkg) {
        File file = new File(pkg.getFilePath());
        // 先按照代码包名查询组
        String groupName = pkg.getName();
        Integer groupId = null;
        GroupFilter filter = GroupFilter.groupFilterBuilder().name(groupName).build();
        DubboResult<ArrayList<GroupDto>> queryGroupsResult = this.queryGroups(driverBase, filter);
        if (!queryGroupsResult.success()) {
            return DubboResult.newFailure(queryGroupsResult.getCode(), queryGroupsResult.getMessage());
        }
        ArrayList<GroupDto> groupDtoList = queryGroupsResult.getObject();
        if (CollectionUtils.isNotEmpty(groupDtoList)) {
            groupId = Integer.parseInt(groupDtoList.get(0).getKey());
        }
        if (groupId == null) {
            // 组不存在则新建组
            GroupRequestDto groupRequestDto = GroupRequestDto.builder()
                    .name(groupName)
                    .build();
            DubboResult<GroupResponseDto> groupResult = infodatorService.addGroup(driverBase, groupRequestDto);
            if (!groupResult.success()) {
                return DubboResult.newFailure(groupResult.getCode(), groupResult.getMessage());
            }
            GroupResponseDto groupResponseDto = groupResult.getObject();
            groupId = groupResponseDto.getId();
        }
        DubboResult<UploadFileResponseDto> uploadResult = infodatorService.uploadPackage(driverBase, file);
        if (uploadResult.success()) {
            UploadFileResponseDto fileResponseDto = uploadResult.getObject();
            pkg.setKey(String.valueOf(fileResponseDto.getId()));
            if (StringUtils.isEmpty(pkg.getProcessKey())) {
                // 流程不存在则添加新的流程
                CreateProcessDto createProcessDto = CreateProcessDto.builder()
                        .description(fileResponseDto.getFileName())
                        .groupId(groupId)
                        .mainFileName(fileResponseDto.getFileName())
                        .mainLogicFileId(fileResponseDto.getId())
                        .templateName(pkg.getName())
                        .build();
                DubboResult<Process> addProcessResult = infodatorService.addProcess(driverBase, createProcessDto);
                if (!addProcessResult.success()) {
                    return DubboResult.newFailure(addProcessResult.getCode(), addProcessResult.getMessage());
                }
                Process processResponseDto = addProcessResult.getObject();
                // 通过流程详情获取版本信息
                DubboResult<Process> processResult = infodatorService.getProcessByKey(driverBase, processResponseDto.getId());
                if (processResult.success()) {
                    Process process = processResult.getObject();
                    TemplateVersionDto templateVersion = process.getTemplateVersion();
                    pkg.setVersion(templateVersion.getCode());
                }
            } else {
                // 添加新流程版本
                AddVersionRequestDto addVersionRequestDto = AddVersionRequestDto.builder()
                        .description(fileResponseDto.getFileName())
                        .templateAttachments(TemplateAttachmentDto.builder()
                                .mainFile(MainFileDto.builder()
                                        .fileName(pkg.getName())
                                        .logicFileId(fileResponseDto.getId())
                                        .build())
                                .build())
                        .templateId(Integer.parseInt(pkg.getProcessKey()))
                        .build();
                DubboResult versionResult = infodatorService.addProcessVersion(driverBase, addVersionRequestDto);
                if (!versionResult.success()) {
                    return versionResult;
                }
            }
            return DubboResult.newSuccess(pkg);
        }
        return DubboResult.newFailure(uploadResult.getCode(), uploadResult.getMessage());
    }

    @Override
    public DubboResult deletePackageByKey(DriverBase driverBase, String key) {
        return infodatorService.deletePackageByKey(driverBase, key);
    }

    @Override
    public DubboResult<ArrayList<CodePackageDto>> queryPackages(DriverBase driverBase, CodePackageFilter filter) {
        //根据name查版本
        if (StringUtils.isNotEmpty(filter.getName())) {
            List<Map<String,Object>> filters = Lists.newArrayList();
            addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
            addFilters("comparator", "name", "CONTAINS", new String[]{filter.getName()}, filters);
            QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                    .pageParam(PageParam.builder()
                            .pageNo(0)
                            .pageSize(9999)
                            .build())
                    .filter(FilterEntity.builder()
                            .classType("logic")
                            .logicOperator("AND")
                            .filters(filters.toArray())
                            .build())
                    .sortFields(null)
                    .build();
            // 通过流程信息获取对应代码包
            DubboResult<ArrayList<Process>> processResult = infodatorService.getProcesses(driverBase, queryRequestDto);
            if (processResult.success()) {
                ArrayList<Process> processList = processResult.getObject();
                List<CodePackageDto> list = processList.stream().map(Process::createInfodatorCodePackageDto).collect(Collectors.toList());
                return DubboResult.newSuccess(Lists.newArrayList(list));
            }
            return DubboResult.newFailure(processResult.getCode(), processResult.getMessage());
        }
        return DubboResult.newSuccess(Lists.newArrayList());
    }

    @Override
    public DubboResult<CodePackageDto> queryPackageByKey(DriverBase driverBase, String key) {
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder()
                        .pageNo(0)
                        .pageSize(9999)
                        .build())
                .filter(null)
                .sortFields(null)
                .build();
        // 通过流程信息获取对应代码包
        DubboResult<ArrayList<Process>> processResult = infodatorService.getProcesses(driverBase, queryRequestDto);
        if (processResult.success()) {
            ArrayList<Process> processList = processResult.getObject();
            List<CodePackageDto> list = processList.stream().map(Process::createInfodatorCodePackageDto).collect(Collectors.toList());
            // 通过key筛选代码包
            Optional<CodePackageDto> pckOptional = list.stream().filter(pck -> key.equals(pck.getKey())).findFirst();
            if (pckOptional.isPresent()) {
                CodePackageDto codePackageDto = pckOptional.get();
                return DubboResult.newSuccess(codePackageDto);
            }
        }
        return DubboResult.newFailure(processResult.getCode(), processResult.getMessage());
    }

    @Override
    public DubboResult<FileInfoDto> downloadPackageByKey(DriverBase driverBase, String key, String fileName) {
            return infodatorService.downloadPackageByKey(driverBase, key, fileName);
    }

    @Override
    public DubboResult<ReleaseDto> releaseProcess(DriverBase driverBase, ReleaseDto release) {
        List<Map<String,Object>> filters = Lists.newArrayList();
        if (StringUtils.isNotEmpty(release.getCodePackageName())) {
            addFilters("comparator", "templateId", "EQ", new Integer[]{Integer.parseInt(release.getCodePackageName())}, filters);
        }
        addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder()
                        .pageNo(0)
                        .pageSize(9999)
                        .build())
                .filter(FilterEntity.builder()
                        .classType("logic")
                        .logicOperator("AND")
                        .filters(filters.toArray())
                        .build())
                .sortFields(null)
                .build();
        // 根据流程id查询流程版本
        DubboResult<ArrayList<HistoryVersionDto>> versionResult = infodatorService.getProcessVersions(driverBase, queryRequestDto);
        if (versionResult.success()) {
            ArrayList<HistoryVersionDto> historyVersionList = versionResult.getObject();
            // 根据版本号查询版本id
            Optional<HistoryVersionDto> historyVersionOptional = historyVersionList.stream()
                    .filter(version -> release.getProcessVersion().equals(version.getCode())).findFirst();
            if (historyVersionOptional.isPresent()) {
                HistoryVersionDto historyVersionDto = historyVersionOptional.get();
                return infodatorService.releaseProcess(driverBase, release.getCodePackageName(), String.valueOf(historyVersionDto.getId()));
            }
        }
        return DubboResult.newFailure(versionResult.getCode(), versionResult.getMessage());
    }

    @Override
    public DubboResult deleteProcessReleaseByKey(DriverBase driverBase, String key) {
        return infodatorService.deleteProcessReleaseByKey(driverBase, key);
    }

    @Override
    public DubboResult<ArrayList<ReleaseDto>> queryProcessReleases(DriverBase driverBase, ReleaseFilter filter) {
        List<Map<String, Object>> filters = Lists.newArrayList();
        if (StringUtils.isNotEmpty(filter.getName())) {
            addFilters("comparator", "name", "CONTAINS", new String[]{filter.getName()}, filters);
        }
        addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder().pageNo(0).pageSize(9999).build())
                .filter(FilterEntity.builder()
                        .classType("logic")
                        .logicOperator("AND")
                        .filters(filters.toArray())
                        .build())
                .sortFields(null)
                .build();
        DubboResult<ArrayList<Process>> result = infodatorService.getProcesses(driverBase, queryRequestDto);
        if (result.success()) {
            ArrayList<Process> processList = result.getObject();
            List<ReleaseDto> list = processList.stream().map(Process::createInfodatorReleaseDto).collect(Collectors.toList());
            return DubboResult.newSuccess(Lists.newArrayList(list));
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult<ReleaseDto> queryProcessReleaseByKey(DriverBase driverBase, String key) {
        DubboResult<Process> result = infodatorService.getProcessByKey(driverBase, Integer.parseInt(key));
        if (result.success()) {
            ReleaseDto releaseDto = result.getObject().createInfodatorReleaseDto();
            return DubboResult.newSuccess(releaseDto);
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult<RobotDto> createRobot(DriverBase driverBase, RobotDto robot) {
        AddRobotRequestDto robotRequestDto = AddRobotRequestDto.builder()
                .agentName(robot.getName())
                .agentDesc(robot.getName())
                .machineCode(robot.getMachineCode())
                .ip(robot.getIp())
                .osInfo("Microsoft Windows 10 企业版 LTSC;10.0.17763;64 位")
                .clientVersion("1.0.0")
                .build();
        DubboResult<RpaRobot> robotResult = infodatorService.addRobot(driverBase, robotRequestDto);
        if (robotResult.success()) {
            RpaRobot rpaRobot = robotResult.getObject();
            RobotDto robotDto = rpaRobot.createRobotDto();
            return DubboResult.newSuccess(robotDto);
        }
        return DubboResult.newFailure(robotResult.getCode(), robotResult.getMessage());
    }

    @Override
    public DubboResult deleteRobotByKey(DriverBase driverBase, String key) {
        return infodatorService.deleteRobotByKey(driverBase, key);
    }

    @Override
    public DubboResult<ArrayList<RobotDto>> queryRobots(DriverBase driverBase, RobotFilter filter) {
        List<Map<String,Object>> filters = Lists.newArrayList();
        addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
        if (StringUtils.isNotEmpty(filter.getName())) {
            addFilters("comparator", "robotName", "CONTAINS", new String[]{filter.getName()}, filters);
        }
        if (StringUtils.isNotEmpty(filter.getState())) {
            addFilters("comparator", "approveStatus", "IN", Lists.newArrayList(filter.getState()), filters);
        }
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder()
                        .pageNo(0)
                        .pageSize(9999)
                        .build())
                .filter(FilterEntity.builder()
                        .classType("logic")
                        .logicOperator("AND")
                        .filters(filters.toArray())
                        .build())
                .sortFields(null)
                .build();
        DubboResult<ArrayList<Robot>> result = infodatorService.queryRobots(driverBase, queryRequestDto);
        if (result.success()) {
            ArrayList<Robot> robotList = result.getObject();
            List<RobotDto> robotDtoList = robotList.stream().map(Robot::createInfodatorRobotDto).collect(Collectors.toList());
            return DubboResult.newSuccess(Lists.newArrayList(robotDtoList));
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult<RobotDto> queryRobotByKey(DriverBase driverBase, String key) {
        DubboResult<Robot> result = infodatorService.queryLiveRobotByKey(driverBase, key);
        if (result.success()) {
            RobotDto robotDto = result.getObject().createInfodatorRobotDto();
            return DubboResult.newSuccess(robotDto);
        }
        return DubboResult.newFailure(result.getCode(), result.getMessage());
    }

    @Override
    public DubboResult assignRobotToGroup(DriverBase driverBase, String robotKey, String groupKey) {
        // 查询已有robot信息
        DubboResult<Robot> result = infodatorService.queryLiveRobotByKey(driverBase, robotKey);
        if (result.success()) {
            Robot robot = result.getObject();
            RpaRobot rpaRobot = robot.getRpaRobot();
            rpaRobot.setGroupId(Integer.parseInt(groupKey));
            // 更新robot分组
            DubboResult<RpaRobot> robotResult = infodatorService.updateRobot(driverBase, rpaRobot);
            return robotResult;
        }
        return result;
    }

    @Override
    public DubboResult removeRobotFromGroup(DriverBase driverBase, String robotKey, String groupKey) {
        return infodatorService.removeRobotFromGroup();
    }

    @Override
    public DubboResult enableLicense(DriverBase driverBase, LicenseDto license) {
        return infodatorService.changeRobotStatus(driverBase, license.getRobotKey(), InfodatorRobotState.OnlineStateEnum.AVAILABLE.getState());
    }

    @Override
    public DubboResult disableLicense(DriverBase driverBase, LicenseDto license) {
        return infodatorService.changeRobotStatus(driverBase, license.getRobotKey(), InfodatorRobotState.OnlineStateEnum.UNAVAILABLE.getState());
    }

    @Override
    public DubboResult<Integer> availableLicenseNum(DriverBase driverBase, String licenseType) {
        return DubboResult.newSuccess(Integer.MAX_VALUE);
    }

    @Override
    public DubboResult<JobDto> startJob(DriverBase driverBase, StartJobDto start) {
        // 查询 robot 信息
        DubboResult<Robot> robotResult = infodatorService.queryLiveRobotByKey(driverBase, start.getRobotKey());
        if (!robotResult.success()) {
            return DubboResult.newFailure(robotResult.getCode(), robotResult.getMessage());
        }
        Robot robot = robotResult.getObject();
        RpaRobot rpaRobot = robot.getRpaRobot();
        // 待确认是否需要实时查询 查询流程信息
        DubboResult<Process> processResult = infodatorService.getProcessByKey(driverBase, Integer.parseInt(start.getProcessReleaseKey()));
        if (!processResult.success()) {
            return DubboResult.newFailure(processResult.getCode(), processResult.getMessage());
        }
        Process process = processResult.getObject();
        String taskName = process.getName() + "_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Task taskReq = Task.builder()
                .agentGroupIds(rpaRobot.getGroupId())
                .agentRobotIds(String.valueOf(rpaRobot.getId()))
                .templateId(process.getId())
                .processMode(1)
                .groupId(process.getGroupId())
                .dutyMode("SHARE")
                .enabled(true)
                .launchMode("RIGHT_NOW")
                .name(taskName)
                .waitIfRobotBusy(true)
                .build();
        if (StringUtils.isNotEmpty(start.getInputArguments())) {
            taskReq.setInputArguments(JSON.toJSONString(start.getInputArguments()));
        }
        // 新建任务
        DubboResult<Task> taskResult = infodatorService.addTask(driverBase, taskReq);
        if (!taskResult.success()) {
            return DubboResult.newFailure(taskResult.getCode(), taskResult.getMessage());
        }
        Task taskRes = taskResult.getObject();
        // 启动任务
        DubboResult<Integer> startResult = infodatorService.startTask(driverBase, taskRes.getId());
        if (!startResult.success()) {
            return DubboResult.newFailure(startResult.getCode(), startResult.getMessage());
        }
        Integer taskExecutionQueueId = startResult.getObject();
        JobDto jobDto = taskReq.createInfodatorJobDto();
        jobDto.setJobId(String.valueOf(taskExecutionQueueId));
        jobDto.setRobot(robot.createInfodatorRobotDto());
        jobDto.setRelease(process.createInfodatorReleaseDto());
        return DubboResult.newSuccess(jobDto);
    }

    @Override
    public DubboResult<JobDto> restartJob(DriverBase driverBase, String jobId) {
        // 根据jobId查询任务id
        List<Map<String,Object>> filters = Lists.newArrayList();
        addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
        // 任务id
        addFilters("comparator", "taskExecutionQueueId", "EQ", new Integer[]{Integer.parseInt(jobId)}, filters);
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder()
                        .pageNo(0)
                        .pageSize(9999)
                        .build())
                .filter(FilterEntity.builder()
                        .classType("logic")
                        .logicOperator("AND")
                        .filters(filters.toArray())
                        .build())
                .sortFields(null)
                .build();
        DubboResult<ArrayList<Task>> taskHistoryResult = infodatorService.getTaskHistoryList(driverBase, queryRequestDto);
        if (taskHistoryResult.success()) {
            ArrayList<Task> taskHistoryList = taskHistoryResult.getObject();
            if (CollectionUtils.isNotEmpty(taskHistoryList)) {
                String taskId = taskHistoryList.get(0).getTaskId();
                // 启动任务
                DubboResult<Integer> startResult = infodatorService.startTask(driverBase, Integer.parseInt(taskId));
                if (!startResult.success()) {
                    return DubboResult.newFailure(startResult.getCode(), startResult.getMessage());
                }
                Integer taskExecutionQueueId = startResult.getObject();
                JobDto jobDto = JobDto.builder()
                        .jobId(String.valueOf(taskExecutionQueueId))
                        .build();
                return DubboResult.newSuccess(jobDto);
            }
        }
        return DubboResult.newFailure(taskHistoryResult.getCode(), taskHistoryResult.getMessage());
    }

    @Override
    public DubboResult pauseJob(DriverBase driverBase, String jobId) {
        return infodatorService.pauseJob(driverBase, jobId);
    }

    @Override
    public DubboResult resumeJob(DriverBase driverBase, String jobId) {
        return infodatorService.resumeJob(driverBase, jobId);
    }

    @Override
    public DubboResult stopJob(DriverBase driverBase, String jobId) {
        return infodatorService.cancelTask(driverBase, jobId);
    }

    @Override
    public DubboResult stopJobs(DriverBase driverBase, List<String> jobIdList) {
        ArrayList<String> errorList = Lists.newArrayList();
        jobIdList.forEach(jobId -> {
            DubboResult result = infodatorService.cancelTask(driverBase, jobId);
            if (!result.success()) {
                errorList.add(jobId);
            }
        });
        return DubboResult.newSuccess(errorList);
    }

    @Override
    public DubboResult<ArrayList<JobDto>> queryJobs(DriverBase driverBase, JobFilter filter) {
        List<Map<String,Object>> filters = Lists.newArrayList();
        addFilters("comparator", "deleted", "EQ", new boolean[]{false}, filters);
        if (StringUtils.isNotEmpty(filter.getState())) {
            // 任务状态
            addFilters("comparator", "taskRunStatus", "EQ", RpaRobot.createFromJobState(filter.getState()), filters);
        }
        FilterEntity filterEntity = FilterEntity.builder()
                .classType("logic")
                .logicOperator("AND")
                .filters(filters.toArray())
                .build();
        QueryRequestDto queryRequestDto = QueryRequestDto.builder()
                .pageParam(PageParam.builder()
                        .pageNo(0)
                        .pageSize(50)
                        .build())
                .filter(CollectionUtils.isEmpty(filters) ? null : filterEntity)
                .sortFields(null)
                .build();
        DubboResult<ArrayList<TaskStatus>> taskStatusResult = infodatorService.getJobListStatus(driverBase, queryRequestDto);
        if (taskStatusResult.success()) {
            ArrayList<TaskStatus> taskStatusList = taskStatusResult.getObject();
            List<JobDto> list = taskStatusList.stream().map(TaskStatus::createJobDto).collect(Collectors.toList());
            return DubboResult.newSuccess(Lists.newArrayList(list));
        }
        return DubboResult.newFailure(taskStatusResult.getCode(), taskStatusResult.getMessage());
    }

    @Override
    public DubboResult<JobDto> queryJobByKey(DriverBase driverBase, String jobId) {
        DubboResult<TaskStatus> taskStatusResult = infodatorService.getJobStatus(driverBase, jobId);
        if (taskStatusResult.success()) {
            JobDto jobDto = taskStatusResult.getObject().createJobDto();
            return DubboResult.newSuccess(jobDto);
        }
        return DubboResult.newFailure(taskStatusResult.getCode(), taskStatusResult.getMessage());
    }

}
