package cd.casic.ci.process.engine.worker;


import cd.casic.ci.process.common.WorkAtom;
import cd.casic.ci.process.dto.req.resource.ResourceQueryReq;
import cd.casic.ci.process.dto.resp.resource.ResourceDetailResp;
import cd.casic.ci.process.engine.constant.DIYImageExecuteCommandConstant;
import cd.casic.ci.process.engine.runContext.TaskRunContext;
import cd.casic.ci.process.engine.worker.base.SshWorker;
import cd.casic.ci.process.process.dataObject.pipeline.PipPipeline;

import cd.casic.ci.process.process.dataObject.task.PipTask;
import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Objects;

/**
 * 自定义镜像执行命令
 *
 * @author herenbin
 * @date 2022-11-08 9:59
 */
@Slf4j
@WorkAtom(taskType = "CUSTOM_IMAGE_EXECUTION_COMMAND")
public class DIYImageExecuteCommandWorker extends SshWorker {

    @Override
    public void execute(TaskRunContext context) {
        int statusCode = -1;
        Map<String, Object> localVariables = context.getLocalVariables();
        if (context.getContextDef() instanceof PipTask taskDef) {
            log.info(taskDef.getTaskName());
            Map<String, Object> taskProperties = taskDef.getTaskProperties();
            Object commandScriptObj = taskProperties.get(DIYImageExecuteCommandConstant.COMMAND_SCRIPT);
            String commandScript = commandScriptObj instanceof String ? ((String) commandScriptObj) : null;
            if (StringUtils.isEmpty(commandScript)) {
//                缺少参数
                toBadEnding();
            }

            try {
                //将节点的配置信息反编译成对象
                log.info("构建脚本" + commandScript);

                //如果machineId为0，则说明该节点没有配置机器，则使用开始节点的机器

                PipPipeline pipeline = (PipPipeline) getContextManager().getContext(taskDef.getPipelineId()).getContextDef();
//                String resourceId = pipeline.getResourceId();
//                ResourceFindResp resourceById = getResourceManagerService().findResourceById(resourceId);
//                PipResourceMachine resourceMachine = resourceById.getResourceMachine();

                //获取机器
                String resourceType = taskProperties.get("resourceType").toString();
                String resourceId = taskProperties.get("resourceId").toString();
                if (StringUtils.isEmpty(resourceId) || StringUtils.isEmpty(resourceType)) {
//                缺少参数
                    toBadEnding();
                }
                ResourceQueryReq req = new ResourceQueryReq();
                req.setId(resourceId);
                req.setType(resourceType);
                ResourceDetailResp resource = getResourceManagerService().findResourceDetailById(resourceId);
                if (Objects.isNull(resource)||Objects.isNull(resource.getMachineInfo())) {
                    append(context,"当前机器不支持machine");
                    return;
                }
                MachineInfoDO resourceMachine = resource.getMachineInfo();
                //TODO 得改一下
                statusCode = shell(resourceMachine, null,context,
                        "echo \"自定义镜像执行命令\"",
                        commandScript
                );
            } catch (Exception e) {
                String errorMessage = "该节点配置信息为空，请先配置该节点信息" + "\r\n";
                log.error("执行ssh失败:",e);
                append(context,errorMessage);
                toBadEnding();
            }
            if (statusCode == 0) {
                log.info("节点执行完成");
            } else {
                log.error("节点执行失败");
            }
            localVariables.put(DIYImageExecuteCommandConstant.STATUS_CODE,statusCode);
        }
    }
}
