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.target.TargetVersion;
import cd.casic.ci.process.process.dataObject.task.PipTask;
import cd.casic.ci.process.process.service.target.TargetVersionService;
import cd.casic.ci.process.util.SftpUploadUtil;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import cd.casic.module.machine.utils.CryptogramUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.Map;
import java.util.Objects;

/**
 * 自定义编译
 * */
@Slf4j
@WorkAtom(taskType = "CUSTOM_COMPILE")
public class CustomCompilerWorker extends SshWorker {
    @Resource
    private TargetVersionService targetVersionService;

    @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;
            try {
                //将节点的配置信息反编译成对象
                log.info("构建脚本" + commandScript);

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

                PipPipeline pipeline = (PipPipeline) getContextManager().getContext(taskDef.getPipelineId()).getContextDef();
                //获取机器
                String resourceType = taskProperties.get("resourceType").toString();
                String resourceId = taskProperties.get("resourceId").toString();
                if (StringUtils.isEmpty(resourceId) || StringUtils.isEmpty(resourceType)) {
                    append(context,"缺少参数");
//                缺少参数
                    toBadEnding();
                }
                ResourceQueryReq req = new ResourceQueryReq();
                req.setId(resourceId);
                req.setType(resourceType);
                ResourceDetailResp resource = getResourceManagerService().findResourceDetailById(resourceId);
                if (Objects.isNull(resource.getMachineInfo())) {
                    append(context,"当前机器不支持machine");
                    return;
                }
                MachineInfoDO resourceMachine = resource.getMachineInfo();

                //根据目标id查询目标信息
                if (StringUtils.isEmpty(pipeline.getTargetVersionId())){
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"目标文件不存在");
                }

                TargetVersion targetVersion = targetVersionService.getById(pipeline.getTargetVersionId());
                String filePath = targetVersion.getFilePath();
                File file = new File(filePath);
                if (!file.exists() || !file.canRead()) {
                    log.error("目标文件不存在或不可读");
                    localVariables.put("statusCode", "-1");
                    append(context,"目标文件不存在或不可读");
                    toBadEnding();
                }
                append(context,"上传文件"+targetVersion.getFileName()+"到目标服务器IP:"+resourceMachine.getHostIp());
                append(context,"上传路径："+"/home/casic/706/ai_test_527");
                // 上传目标 到目标服务器
                //通过taskProperties获取制品路径
//                String remoteDir = taskProperties.get("remoteDir").toString();
                String remoteDir = null;
                if (StringUtils.isEmpty(remoteDir)){
                    //则默认路径写死
                    remoteDir = "/home/casic/706/ai_test_527";
                }
                SftpUploadUtil.uploadFileViaSftp(resourceMachine.getHostIp(), resourceMachine.getSshPort(),resourceMachine.getUsername(), CryptogramUtil.doDecrypt(resourceMachine.getPassword()),null,file.getAbsolutePath(),remoteDir,file.getName());

                //TODO 得改一下
                statusCode = shell(resourceMachine, null,context,
                        "echo \"编译命令执行\"",
                        "cd /home/casic/706/ai_test_527",
                        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);
        }
    }
}
