package com.friday.distributor.common;

import com.alibaba.fastjson.JSON;
import com.friday.base.common.response.DubboResult;
import com.friday.blank.api.constants.MachineStateEnum;
import com.friday.blank.api.dto.taskType.TaskTypeDetailDto;
import com.friday.blank.api.service.external.IExternalCommonService;
import com.friday.distributor.exception.DistributorRuntimeException;
import com.friday.distributor.mapper.BizConfigMapper;
import com.friday.distributor.po.BizConfigPo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

import static com.friday.operation.api.distributor.constant.RobotExecType.Unattended;
import static org.apache.commons.lang3.StringUtils.EMPTY;

/**
 * @Author YaoYao
 * @Date Created In 14:34 2023/3/7
 * @Description 运行配置相关服务
 * @Modified By
 */
@Service
@Slf4j
public class PlatformInteractionService {
    @Autowired(required = false)
    private IExternalCommonService platformService;
    @Autowired
    private BizConfigMapper bizConfigMapper;
    @Autowired
    private TaskExecConfigService taskExecConfigService;
//    @Autowired
//    private ExecDataService execDataService;
//    @Autowired
//    private ExecutorMethodInvokeHelper executorInvoker;

    public DubboResult syncRobotState(String platformTenant, String platformRobotName, String state) {
        try {
            if (MachineStateEnum.ILLEGAL_OCCUPY.getKey().equals(state)) {
                log.error("平台工位{}-{}非法占用中", platformTenant, platformRobotName);
            }
            return platformService.syncRobotState(platformTenant, platformRobotName, state);
        } catch (Exception e) {
            log.error("更新平台工位{}-{}状态:{}失败", platformTenant, platformRobotName, state, e);
            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, e.getMessage());
        }
    }

//    public DubboResult syncPlatformTaskState(String taskId){
//        try {
//            TaskResultStateDto state = execDataService.getTaskState(taskId);
//            TaskResultFilter filter = new TaskResultFilter();
//            filter.setTaskId(taskId);
//            DubboResult<TaskResultDto> result = executorInvoker.getTaskResult(filter);
//            if(Objects.nonNull(result) && !result.success()){
//                return result;
//            }
//            List<TaskResultFile> files;
//            if(Objects.isNull(result) || Objects.isNull(result.getObject()) || CollectionUtils.isEmpty(result.getObject().getFiles())){
//                files = Lists.newArrayList();
//            } else {
//                files = result.getObject().getFiles();
//            }
//            return platformService.syncTaskState(taskId, state.getExecState(), state.getFailMag(), files);
//        } catch (Exception e) {
//            log.error("更新平台任务{}状态失败", taskId, e);
//            return DubboResult.newFailure(DubboResult.SERVER_EXCEPTION, e.getMessage());
//        }
//        return DubboResult.newSuccess();
//    }

    public TaskTypeDetailDto getTaskExecConfig(String platformTenant, String taskType) {
        //TODO 对接数字员工管理平台，如果未从管理端查询到配置数据，则从数据表中查询
        DubboResult<TaskTypeDetailDto> result = platformService.getTaskDetail(platformTenant, taskType);
        log.error("打印入参：{}", platformTenant + "----" + taskType);
        log.error("查询执行任务配置信息：{}", result);
        if (result.success()) {
            return result.getObject();
        }
//        if(!result.success() || Objects.isNull(result.getObject())){
//            throw new DistributorRuntimeException("查询管理端运行配置信息失败", result.getMessage());
//        }
//        TaskTypeDetailDto detail = result.getObject();
        BizConfigPo configPo = bizConfigMapper.selectConfig(platformTenant, taskType);
        log.error("查询BizConfigPo：", configPo);
        if (configPo == null || StringUtils.isEmpty(configPo.getDefaultConfig())) {
            throw new DistributorRuntimeException("运行配置信息缺失，请检查配置表");
        }
        String config = configPo.getDefaultConfig();
        TaskTypeDetailDto detail = JSON.parseObject(config, TaskTypeDetailDto.class);
        if (Objects.isNull(detail.getProcess()) || Objects.isNull(detail.getSchedule())) {
            throw new DistributorRuntimeException("运行配置信息缺失");
        }
        if (Unattended.getType().equals(detail.getSchedule().getExecuteMethod()) && CollectionUtils.isEmpty(detail.getMachines())) {
            throw new DistributorRuntimeException("后台运行工位信息缺失");
        }
        if (Objects.isNull(detail.getSchedule().getIsRetry())) {
            detail.getSchedule().setIsRetry(false);
        }
        if (Objects.isNull(detail.getSchedule().getIsSync())) {
            detail.getSchedule().setIsSync(false);
        }
        // 配置存缓存
        taskExecConfigService.setGeneralConfig(detail);
        return detail;
    }

    public String queryPlatformRobotState(String platformTenant, String platformRobotName) {
        try {
            DubboResult<String> stateResult = platformService.getRobotState(platformTenant, platformRobotName);
            if (stateResult.success()) {
                return stateResult.getObject();
            }
            //TODO 对接数字员工管理平台，如果未从管理端查询到配置数据，先返回可用状态
            return MachineStateEnum.AVAILABLE.getKey();
        } catch (Exception e) {
            log.error("查询平台工位{}-{}状态失败", platformTenant, platformRobotName, e);
            return EMPTY;
        }
    }

    public List<String> queryPlatformRobotsByState(String platformTenant, String machineState) {
        return Lists.newArrayList();
        //TODO 对接数字员工管理平台，如果未从管理端查询到配置数据，先返回可用状态
//        DubboResult<ArrayList<String>> result = platformService.getRobot(platformTenant, machineState);
//        if(!result.success() || Objects.isNull(result.getObject())){
//            throw new DistributorRuntimeException("根据状态查询平台工位失败：", platformTenant, machineState, result.getMessage());
//        }
//        return result.getObject();
    }
}
