"use strict";

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = {
      enumerable: true,
      get: function () {
        return m[k];
      }
    };
  }
  Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});
var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});
var __importStar = void 0 && (void 0).__importStar || function () {
  var ownKeys = function (o) {
    ownKeys = Object.getOwnPropertyNames || function (o) {
      var ar = [];
      for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
      return ar;
    };
    return ownKeys(o);
  };
  return function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
    __setModuleDefault(result, mod);
    return result;
  };
}();
var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.VisionInspectionNode = exports.VISION_INSPECTION_RESULT_SUFFIX = void 0;
const tree_model_1 = __importDefault(require("tree-model"));
const domain_1 = require("../../domain");
const agv_constant_1 = require("../../entity/agv.constant");
const translation_util_1 = __importStar(require("../../utils/translation.util"));
const waypoint_rpc_util_1 = require("../../utils/waypoint-rpc.util");
const scope_setting_1 = require("../../scope-setting");
const webscope_service_1 = require("../../webscope-service");
const TranslationUtil = translation_util_1.default;
exports.VISION_INSPECTION_RESULT_SUFFIX = 'Vision_Inspection_Result_';
class VisionInspectionNode {
  setResultVariable(v) {
    this.resultVariable = v;
    this.pendingResultVariableName = this.extractVariableName(v);
    return this;
  }
  getResultVariable() {
    return this.resultVariable;
  }
  setInspectionWaypoint(v) {
    this.inspectionWaypoint = v;
    this.pendingInspectionWaypointName = this.extractWaypointName(v);
    return this;
  }
  getInspectionWaypoint() {
    return this.inspectionWaypoint;
  }
  setDataModel(dataModel) {
    this.dataModel = dataModel;
    const resultVariable = dataModel.get(this.VisionInspectionResultVariableKey, null);
    if (this.isVariable(resultVariable)) {
      this.resultVariable = resultVariable;
      this.pendingResultVariableName = this.extractVariableName(resultVariable);
    } else if (typeof resultVariable === 'string' && resultVariable) {
      this.pendingResultVariableName = resultVariable;
    }
    const inspectionWaypoint = dataModel.get(this.VisionInspectionWaypointKey, null);
    if (this.isWaypoint(inspectionWaypoint)) {
      this.inspectionWaypoint = inspectionWaypoint;
      this.pendingInspectionWaypointName = this.extractWaypointName(inspectionWaypoint);
    } else if (typeof inspectionWaypoint === 'string' && inspectionWaypoint) {
      this.pendingInspectionWaypointName = inspectionWaypoint;
    }
  }
  getDataModel() {
    this.dataModel.set(this.VisionInspectionResultVariableKey, this.resultVariable, domain_1.XmlLabelType.VARIABLE);
    this.dataModel.set(this.VisionInspectionWaypointKey, this.inspectionWaypoint, domain_1.XmlLabelType.WAYPOINT);
    return this.dataModel;
  }
  isVariable(value) {
    return typeof value === 'object' && value !== null && typeof value.getDisplayName === 'function' && typeof value.getType === 'function';
  }
  isWaypoint(value) {
    return typeof value === 'object' && value !== null && typeof value.getPose === 'function';
  }
  extractVariableName(value) {
    if (typeof value === 'string' && value) {
      return value;
    }
    if (!value || typeof value !== 'object') {
      return null;
    }
    const variable = value;
    if (typeof variable.name === 'string' && variable.name) {
      return variable.name;
    }
    if (typeof variable.getDisplayName === 'function') {
      const displayName = variable.getDisplayName();
      if (typeof displayName === 'string' && displayName) {
        return displayName;
      }
    }
    if (typeof variable.getName === 'function') {
      const name = variable.getName();
      if (typeof name === 'string' && name) {
        return name;
      }
    }
    return null;
  }
  extractWaypointName(value) {
    if (typeof value === 'string' && value) {
      return value;
    }
    if (!value || typeof value !== 'object') {
      return null;
    }
    const waypoint = value;
    if (typeof waypoint.name === 'string' && waypoint.name) {
      return waypoint.name;
    }
    if (typeof waypoint.getName === 'function') {
      const name = waypoint.getName();
      if (typeof name === 'string' && name) {
        return name;
      }
    }
    if (typeof waypoint.value === 'string' && waypoint.value) {
      return waypoint.value;
    }
    if (typeof waypoint.getDisplayName === 'function') {
      const displayName = waypoint.getDisplayName();
      if (typeof displayName === 'string' && displayName) {
        return displayName;
      }
    }
    return null;
  }
  toSerializableValue(key, value) {
    if (key === this.VisionInspectionResultVariableKey) {
      return this.extractVariableName(value) || this.pendingResultVariableName;
    }
    if (key === this.VisionInspectionWaypointKey) {
      return this.extractWaypointName(value) || this.pendingInspectionWaypointName;
    }
    return value;
  }
  hasWaypointPoseDefined(value) {
    var _a, _b, _c;
    if (!this.isWaypoint(value)) {
      return false;
    }
    const waypoint = value;
    const pose = Array.isArray((_a = waypoint.getPose) === null || _a === void 0 ? void 0 : _a.call(waypoint)) ? waypoint.getPose() : [];
    const joint = Array.isArray((_b = waypoint.getJointPositions) === null || _b === void 0 ? void 0 : _b.call(waypoint)) ? waypoint.getJointPositions() : [];
    const offset = Array.isArray((_c = waypoint.getTcpOffset) === null || _c === void 0 ? void 0 : _c.call(waypoint)) ? waypoint.getTcpOffset() : [];
    const hasNonZero = arr => arr.some(item => Math.abs(Number(item !== null && item !== void 0 ? item : 0)) > 1e-9);
    return hasNonZero(pose) || hasNonZero(joint) || hasNonZero(offset);
  }
  resolveVariableByName(name) {
    if (!name) {
      return null;
    }
    const webscopeService = (0, webscope_service_1.getWebscopeService)();
    if (!webscopeService) {
      return null;
    }
    const variableModel = webscopeService.getVariableModel();
    try {
      const byName = typeof (variableModel === null || variableModel === void 0 ? void 0 : variableModel.getByName) === 'function' ? variableModel.getByName(name) : null;
      if (this.isVariable(byName)) {
        return byName;
      }
    } catch (error) {}
    try {
      const byGet = typeof (variableModel === null || variableModel === void 0 ? void 0 : variableModel.get) === 'function' ? variableModel.get(name) : null;
      if (this.isVariable(byGet)) {
        return byGet;
      }
    } catch (error) {}
    return null;
  }
  resolveWaypointByName(name) {
    if (!name) {
      return null;
    }
    const webscopeService = (0, webscope_service_1.getWebscopeService)();
    if (!webscopeService) {
      return null;
    }
    try {
      const waypoint = webscopeService.getWaypointModel().getByName(name);
      return this.isWaypoint(waypoint) ? waypoint : null;
    } catch (error) {
      return null;
    }
  }
  setId(id) {
    this.id = id;
  }
  update(config) {
    let updated = false;
    for (const key in config) {
      const raw = config[key];
      const value = raw && typeof raw === 'object' && 'value' in raw ? raw.value : raw;
      if (key === this.VisionInspectionResultVariableKey) {
        if (value === null) {
          const hasPending = !!this.pendingResultVariableName;
          if (this.getResultVariable() !== null || hasPending) {
            this.setResultVariable(null);
            this.pendingResultVariableName = null;
            updated = true;
          }
        } else {
          const incomingVariableName = this.extractVariableName(value);
          const currentVariableName = this.extractVariableName(this.getResultVariable());
          const lockedVariableName = currentVariableName || this.pendingResultVariableName;
          const variableName = lockedVariableName || incomingVariableName;
          if (variableName === null && value !== null && value !== undefined) {
            continue;
          }
          const hasPendingNameChanged = !lockedVariableName && variableName !== this.pendingResultVariableName;
          if (hasPendingNameChanged) {
            this.pendingResultVariableName = variableName;
          }
          const variable = this.resolveVariableByName(variableName);
          if (!variable && this.getResultVariable() !== null && !!lockedVariableName) {
            continue;
          }
          if (variable !== this.getResultVariable()) {
            this.setResultVariable(variable);
            updated = true;
          }
          if (hasPendingNameChanged) {
            updated = true;
          }
        }
      } else if (key === this.VisionInspectionWaypointKey) {
        const incomingHasDefined = !!(raw && typeof raw === 'object' && 'hasDefined' in raw && raw.hasDefined === true);
        if (value === null) {
          const hasPending = !!this.pendingInspectionWaypointName;
          if (this.getInspectionWaypoint() !== null || hasPending) {
            this.setInspectionWaypoint(null);
            this.pendingInspectionWaypointName = null;
            this.inspectionWaypointForcedDefined = false;
            updated = true;
          }
        } else {
          const incomingWaypointName = this.extractWaypointName(value);
          const currentWaypointName = this.extractWaypointName(this.getInspectionWaypoint());
          const lockedWaypointName = currentWaypointName || this.pendingInspectionWaypointName;
          const waypointName = lockedWaypointName || incomingWaypointName;
          const hasPendingNameChanged = !lockedWaypointName && waypointName !== this.pendingInspectionWaypointName;
          if (hasPendingNameChanged) {
            this.pendingInspectionWaypointName = waypointName;
          }
          const waypoint = this.resolveWaypointByName(waypointName);
          if (!waypoint && this.getInspectionWaypoint() !== null && !!lockedWaypointName) {
            continue;
          }
          if (waypoint !== this.getInspectionWaypoint()) {
            this.setInspectionWaypoint(waypoint);
            updated = true;
          }
          if ((incomingHasDefined || !!waypointName) && !this.inspectionWaypointForcedDefined) {
            this.inspectionWaypointForcedDefined = true;
            updated = true;
          }
          if (hasPendingNameChanged) {
            updated = true;
          }
        }
      }
    }
    return updated;
  }
  dropNode() {}
  toJSON() {
    const result = {};
    const model = this.getDataModel();
    if (!model || typeof model.getKeys !== 'function') {
      return result;
    }
    model.getKeys().forEach(key => {
      const serializedValue = this.toSerializableValue(key, model.get(key, null));
      let hasDefined = !!serializedValue;
      if (key === this.VisionInspectionWaypointKey) {
        const waypointName = this.extractWaypointName(serializedValue);
        const hasUpdatedByRpc = (0, waypoint_rpc_util_1.hasWaypointBeenUpdated)(waypointName);
        if (hasUpdatedByRpc && !this.inspectionWaypointForcedDefined) {
          this.inspectionWaypointForcedDefined = true;
        }
        const latestWaypoint = this.resolveWaypointByName(waypointName);
        hasDefined = this.inspectionWaypointForcedDefined || hasUpdatedByRpc || this.hasWaypointPoseDefined(latestWaypoint || model.get(key, null));
      }
      result[key] = {
        value: serializedValue,
        hasDefined
      };
    });
    return result;
  }
  cloneNode(node) {
    const treeModelInstance = new tree_model_1.default();
    const parseTree = treeModelInstance.parse({});
    const {
      children,
      programNode
    } = node;
    if (programNode) {
      const nodeData = programNode.getDataModel();
      this.setDataModel(nodeData);
    }
    const currentNode = this.programModel.getProgramTree().addChild(parseTree, node.nodeId, this, 0);
    currentNode.model.disabled = node.disabled;
    currentNode.model.isBreakpoint = node.isBreakpoint;
    currentNode.model.suppressedComment = node.suppressedComment;
    return currentNode;
  }
  constructor(programModel) {
    this.VisionInspectionResultVariableKey = 'result_variable';
    this.VisionInspectionWaypointKey = 'inspection_waypoint';
    this.id = '';
    this.DEFAULT_VISION_TARGET_TYPE = 10010100;
    this.resultVariable = null;
    this.inspectionWaypoint = null;
    this.pendingResultVariableName = null;
    this.pendingInspectionWaypointName = null;
    this.inspectionWaypointForcedDefined = false;
    this.programModel = programModel;
    this.node = this;
  }
  toLuaPose() {
    var _a, _b, _c, _d, _e, _f;
    const waypoint = this.getInspectionWaypoint();
    if (!waypoint || typeof waypoint.getPose !== 'function') {
      return `{0, 0, 0, 0, 0, 0}`;
    }
    const pose = waypoint.getPose() || [];
    return `{${Number((_a = pose[0]) !== null && _a !== void 0 ? _a : 0)}, ${Number((_b = pose[1]) !== null && _b !== void 0 ? _b : 0)}, ${Number((_c = pose[2]) !== null && _c !== void 0 ? _c : 0)}, ${Number((_d = pose[3]) !== null && _d !== void 0 ? _d : 0)}, ${Number((_e = pose[4]) !== null && _e !== void 0 ? _e : 0)}, ${Number((_f = pose[5]) !== null && _f !== void 0 ? _f : 0)}}`;
  }
  generateScript(scriptWriter) {
    var _a, _b;
    const tree_node = (_b = (_a = this.programModel) === null || _a === void 0 ? void 0 : _a.getProgramTree().getTreeNodeById(this.id)) === null || _b === void 0 ? void 0 : _b.model;
    if (!tree_node) {
      return;
    }
    const row = tree_node.lineNumber;
    const resultVarName = this.extractVariableName(this.getResultVariable());
    const inspectionPose = this.toLuaPose();
    const defaultTargetType = this.DEFAULT_VISION_TARGET_TYPE;
    scriptWriter.appendLine(`function _vision_inspection_status_msg_${row}(status)`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`if status == -1 then return "目标类型错误，无法找到对应type识别目标" end`);
    scriptWriter.appendLine(`if status == -2 then return "rgb图像为空" end`);
    scriptWriter.appendLine(`if status == -3 then return "点云为空" end`);
    scriptWriter.appendLine(`if status == -4 then return "机械臂位姿数据错误（不是6位）" end`);
    scriptWriter.appendLine(`if status == -5 then return "http通信请求失败" end`);
    scriptWriter.appendLine(`if status == -6 then return "通信结果解析失败" end`);
    scriptWriter.appendLine(`if status == -7 then return "识别结果中的位姿数据错误" end`);
    scriptWriter.appendLine(`return "未知错误 status=" .. tostring(status)`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function _vision_inspection_popup_error_${row}(msg)`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`sched.sync_program_point()`);
    scriptWriter.appendLine(`clearNamedVariable("_popup_continue_or_stop")`);
    scriptWriter.appendLine(`do`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local _popup_t = getControlSystemTime()`);
    scriptWriter.appendLine(`popup(TraceLevel.ERROR, "Error", msg, 1)`);
    scriptWriter.appendLine(`halt()`);
    scriptWriter.appendLine(`while not variableUpdated("_popup_continue_or_stop", _popup_t) do sync() end`);
    scriptWriter.appendLine(`if not getBool("_popup_continue_or_stop", true) then halt() end`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function _vision_inspection_normalize_pose_${row}(robot_pose)`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`if robot_pose == nil then return nil end`);
    scriptWriter.appendLine(`if robot_pose.x ~= nil then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`return {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`tonumber(robot_pose.x) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose.y) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose.z) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose.rx) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose.ry) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose.rz) or 0,`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`if robot_pose[1] ~= nil or robot_pose[6] ~= nil then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`return {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`tonumber(robot_pose[1]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[2]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[3]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[4]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[5]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[6]) or 0,`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`if robot_pose[0] ~= nil or robot_pose[5] ~= nil then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`return {`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`tonumber(robot_pose[0]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[1]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[2]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[3]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[4]) or 0,`);
    scriptWriter.appendLine(`tonumber(robot_pose[5]) or 0,`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`}`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`return nil`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function _vision_inspection_extract_rsp_${row}(raw)`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`if raw == nil then return nil end`);
    scriptWriter.appendLine(`if type(raw) ~= "table" then return nil end`);
    scriptWriter.appendLine(`if raw.status ~= nil then return raw end`);
    scriptWriter.appendLine(`if raw.pose ~= nil then return { status = 0, pose = raw.pose } end`);
    scriptWriter.appendLine(`if type(raw.data) == "table" and raw.data.status ~= nil then return raw.data end`);
    scriptWriter.appendLine(`if type(raw.data) == "table" and raw.data.pose ~= nil then return { status = 0, pose = raw.data.pose } end`);
    scriptWriter.appendLine(`if type(raw.result) == "table" and raw.result.status ~= nil then return raw.result end`);
    scriptWriter.appendLine(`if type(raw.result) == "table" and raw.result.pose ~= nil then return { status = 0, pose = raw.result.pose } end`);
    scriptWriter.appendLine(`if type(raw.result) == "table" and type(raw.result.data) == "table" and raw.result.data.status ~= nil then return raw.result.data end`);
    scriptWriter.appendLine(`if type(raw.result) == "table" and type(raw.result.data) == "table" and raw.result.data.pose ~= nil then return { status = 0, pose = raw.result.data.pose } end`);
    scriptWriter.appendLine(`if type(raw[1]) == "table" then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`if raw[1].status ~= nil then return raw[1] end`);
    scriptWriter.appendLine(`if raw[1].pose ~= nil then return { status = 0, pose = raw[1].pose } end`);
    scriptWriter.appendLine(`if type(raw[1].data) == "table" and raw[1].data.status ~= nil then return raw[1].data end`);
    scriptWriter.appendLine(`if type(raw[1].data) == "table" and raw[1].data.pose ~= nil then return { status = 0, pose = raw[1].data.pose } end`);
    scriptWriter.appendLine(`if type(raw[1].result) == "table" and raw[1].result.status ~= nil then return raw[1].result end`);
    scriptWriter.appendLine(`if type(raw[1].result) == "table" and raw[1].result.pose ~= nil then return { status = 0, pose = raw[1].result.pose } end`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`return nil`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function _vision_inspection_get_target_pose_${row}(target_type, robot_pose)`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`textmsg("vision inspection call getVisionTargetPose, type=" .. tostring(target_type) .. ", host=127.0.0.1, port=30210")`);
    scriptWriter.appendLine(`local normalized_pose = _vision_inspection_normalize_pose_${row}(robot_pose)`);
    scriptWriter.appendLine(`if not normalized_pose then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`textmsg("vision inspection invalid robot_pose, expected 6-axis pose")`);
    scriptWriter.appendLine(`return { status = -4 }`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`local visionc = sched.jsonrpc.proxy('http://127.0.0.1:30210/jsonrpc')`);
    scriptWriter.appendLine(`local ok, rsp = pcall(function() return getVisionTargetPose(target_type, normalized_pose) end)`);
    scriptWriter.appendLine(`local rpcOkCount = 0`);
    scriptWriter.appendLine(`if ok then rpcOkCount = rpcOkCount + 1 end`);
    scriptWriter.appendLine(`if ok then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local parsed = _vision_inspection_extract_rsp_${row}(rsp)`);
    scriptWriter.appendLine(`if parsed then return parsed end`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`if not ok then textmsg("vision inspection rpc failed: getVisionTargetPose") end`);
    scriptWriter.appendLine(`if ok and rsp == nil then textmsg("vision inspection rpc invalid: getVisionTargetPose -> nil") end`);
    scriptWriter.appendLine(`if ok and type(rsp) ~= "table" then textmsg("vision inspection rpc invalid: getVisionTargetPose type=" .. tostring(type(rsp))) end`);
    scriptWriter.appendLine(`if ok and type(rsp) == "table" then textmsg("vision inspection rpc invalid: getVisionTargetPose shape=" .. tostring(json.encode(rsp))) end`);
    scriptWriter.appendLine(`ok, rsp = pcall(function() return visionc.getVisionTargetPose(target_type, normalized_pose) end)`);
    scriptWriter.appendLine(`if ok then rpcOkCount = rpcOkCount + 1 end`);
    scriptWriter.appendLine(`if ok then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local parsed = _vision_inspection_extract_rsp_${row}(rsp)`);
    scriptWriter.appendLine(`if parsed then return parsed end`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`if not ok then textmsg("vision inspection rpc failed: visionc.getVisionTargetPose") end`);
    scriptWriter.appendLine(`if ok and rsp == nil then textmsg("vision inspection rpc invalid: visionc.getVisionTargetPose -> nil") end`);
    scriptWriter.appendLine(`if ok and type(rsp) ~= "table" then textmsg("vision inspection rpc invalid: visionc.getVisionTargetPose type=" .. tostring(type(rsp))) end`);
    scriptWriter.appendLine(`if ok and type(rsp) == "table" then textmsg("vision inspection rpc invalid: visionc.getVisionTargetPose shape=" .. tostring(json.encode(rsp))) end`);
    scriptWriter.appendLine(`ok, rsp = pcall(function() return visionc.VisionInterface.getVisionTargetPose(target_type, normalized_pose) end)`);
    scriptWriter.appendLine(`if ok then rpcOkCount = rpcOkCount + 1 end`);
    scriptWriter.appendLine(`if ok then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local parsed = _vision_inspection_extract_rsp_${row}(rsp)`);
    scriptWriter.appendLine(`if parsed then return parsed end`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`if not ok then textmsg("vision inspection rpc failed: visionc.VisionInterface.getVisionTargetPose") end`);
    scriptWriter.appendLine(`if ok and rsp == nil then textmsg("vision inspection rpc invalid: visionc.VisionInterface.getVisionTargetPose -> nil") end`);
    scriptWriter.appendLine(`if ok and type(rsp) ~= "table" then textmsg("vision inspection rpc invalid: visionc.VisionInterface.getVisionTargetPose type=" .. tostring(type(rsp))) end`);
    scriptWriter.appendLine(`if ok and type(rsp) == "table" then textmsg("vision inspection rpc invalid: visionc.VisionInterface.getVisionTargetPose shape=" .. tostring(json.encode(rsp))) end`);
    scriptWriter.appendLine(`if rpcOkCount == 0 then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`textmsg("vision inspection rpc call failed on all providers")`);
    scriptWriter.appendLine(`return { status = -5 }`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`textmsg("vision inspection rpc returned empty/invalid response, treat as no target")`);
    scriptWriter.appendLine(`return { status = 1 }`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function _vision_inspection_move_line_until_reached_${row}(pose, a, v, blend, duration)`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local handler = thread(function()`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`sched.INST([[_vision_inspection_flag_thread_move_${row} = 1]], _ENV)`);
    scriptWriter.appendLine(`moveJoint(inverseKinematics(getJointPositions(), pose), a, v, blend, duration)`);
    scriptWriter.appendLine(`sched.INST([[_vision_inspection_flag_thread_move_${row} = 2]], _ENV)`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end, "thread_move_vision_inspection_${row}")`);
    scriptWriter.appendLine(`_vision_inspection_flag_thread_move_${row} = 0`);
    scriptWriter.appendLine(`run(handler)`);
    scriptWriter.appendLine(`while true do`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`if (_vision_inspection_flag_thread_move_${row} > 1) then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`kill(handler)`);
    scriptWriter.appendLine(`break`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`sync()`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`sched.cancel_point()`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`function _vision_inspection_call_${row}()`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local inspect_pose = ${inspectionPose}`);
    scriptWriter.appendLine(`local vision_target_type = ${defaultTargetType}`);
    scriptWriter.appendLine(`textmsg("vision inspection start, target_type=" .. tostring(vision_target_type))`);
    scriptWriter.appendLine(`_vision_inspection_move_line_until_reached_${row}(inspect_pose, 1.3962634015954636, 1.0471975511965976, 0, 0)`);
    scriptWriter.appendLine(`local retry = 0`);
    scriptWriter.appendLine(`local rsp = nil`);
    scriptWriter.appendLine(`while retry < 3 do`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`rsp = _vision_inspection_get_target_pose_${row}(vision_target_type, getTcpPose())`);
    scriptWriter.appendLine(`local status = tonumber(rsp and rsp.status) or -5`);
    scriptWriter.appendLine(`textmsg("vision inspection attempt=" .. tostring(retry + 1) .. ", status=" .. tostring(status))`);
    scriptWriter.appendLine(`if status >= 0 then break end`);
    scriptWriter.appendLine(`retry = retry + 1`);
    scriptWriter.appendLine(`if retry < 3 then sleep(0.1) end`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`local status = tonumber(rsp and rsp.status) or -5`);
    scriptWriter.appendLine(`if status < 0 then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`local err_msg = "视觉巡检失败: " .. _vision_inspection_status_msg_${row}(status)`);
    scriptWriter.appendLine(`textmsg("vision inspection fatal error after retries, status=" .. tostring(status))`);
    scriptWriter.appendLine(`_vision_inspection_popup_error_${row}(err_msg)`);
    scriptWriter.appendLine(`return { ok = false, status = status, confidence = 0 }`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`if status == 1 then`);
    scriptWriter.increaseIndent();
    scriptWriter.appendLine(`textmsg("vision inspection no target detected")`);
    scriptWriter.appendLine(`return { ok = false, status = 1, confidence = 0 }`);
    scriptWriter.decreaseIndent();
    scriptWriter.appendLine(`end`);
    scriptWriter.appendLine(`textmsg("vision inspection target detected")`);
    scriptWriter.appendLine(`return { ok = true, status = 0, pose = rsp and rsp.pose, confidence = 1 }`);
    scriptWriter.end();
    scriptWriter.lineFeed();
    scriptWriter.appendLine(`local inspection_rsp = _vision_inspection_call_${row}()`);
    scriptWriter.appendLine(`local inspection_ok = inspection_rsp and inspection_rsp.ok`);
    if (resultVarName) {
      scriptWriter.appendLine(`${resultVarName} = inspection_ok`);
    }
    scriptWriter.appendLine(`textmsg("vision inspection result=" .. tostring(inspection_ok) .. ", status=" .. tostring(inspection_rsp and inspection_rsp.status))`);
    scriptWriter.appendLine(`sync()`);
    scriptWriter.appendLine(`sleep(0.05)`);
    scriptWriter.appendLine(`textmsg("vision inspection finished")`);
  }
  hasDefined() {
    return true;
  }
  getTitle() {
    const language = (0, scope_setting_1.getCurrentLanguage)();
    return translation_util_1.default.toAimLanguage(language, 'Visual Inspection', translation_util_1.TranslationNamespace.AGV);
  }
  getIcon(hasDefined) {
    return hasDefined ? `icon${agv_constant_1.PluginsProgramNodeId.AUBO_VISION_INSPECTION}Complete` : `icon${agv_constant_1.PluginsProgramNodeId.AUBO_VISION_INSPECTION}`;
  }
}
exports.VisionInspectionNode = VisionInspectionNode;
//# sourceMappingURL=visioninspection-node.js.map