"use strict";

var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AgvService = void 0;
const agv_constant_1 = require("../entity/agv.constant");
const aubo_logger_1 = require("@aubo/aubo_logger");
const aubo_sdk_1 = require("@aubo/aubo_sdk");
const axios_1 = __importDefault(require("axios"));
const webscope_service_1 = require("../webscope-service");
const robot_proxy_constants_1 = require("../enum/robot-proxy.constants");
class AgvService {
  constructor() {
    var _a, _b, _c, _d, _e;
    this.robotStatus = null;
    this.lastCancelNavigationAt = 0;
    this.cancelNavigationDebounceMs = 1200;
    this.monitorInterval = null;
    this.logger = (_c = (_b = (_a = (0, webscope_service_1.getWebscopeService)()) === null || _a === void 0 ? void 0 : _a.getLogger) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : new aubo_logger_1.AsLogger("AgvService");
    this.robotProxy = (_d = (0, webscope_service_1.getWebscopeService)()) === null || _d === void 0 ? void 0 : _d.getRobotProxy();
    (_e = (0, webscope_service_1.getWebscopeService)()) === null || _e === void 0 ? void 0 : _e.getRobotProxy();
    this.monitorRobotStatus();
  }
  async refreshStations(ip, count = 1) {
    var _a, _b, _c;
    try {
      if (count > 3) return false;
      axios_1.default.defaults.timeout = 5000;
      const data = await axios_1.default.post(`http://${ip !== null && ip !== void 0 ? ip : agv_constant_1.AGV_DEFAULT_HOST}:${agv_constant_1.AGV_STEERING_SERVER_PORT}/api/map/stations`);
      const stations = (_a = data.data) === null || _a === void 0 ? void 0 : _a.data;
      (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log(`获取站点信息: ${JSON.stringify(stations)}`);
      agv_constant_1.SingleInstance.getInstance().set(agv_constant_1.ConstantEnum.AGV_STATIONS, stations);
      return true;
    } catch (e) {
      (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error("connect error: ", e);
      return this.refreshStations(ip, ++count);
    }
  }
  normalizeRuntimeState(status) {
    if (status === null || typeof status === "undefined") {
      return "UNKNOWN";
    }
    let stateValue = status;
    if (typeof stateValue === "number") {
      const enumName = aubo_sdk_1.RuntimeState[stateValue];
      if (typeof enumName === "string") {
        stateValue = enumName;
      }
    }
    const normalized = String(stateValue).trim().toLowerCase();
    if (normalized === "running") return "RUNNING";
    if (normalized === "paused" || normalized === "pausing") return "PAUSED";
    if (normalized === "stopped" || normalized === "idle") return "STOPPED";
    if (normalized.includes("abort") || normalized.includes("stop")) {
      return "ABORTING_OR_STOPPING";
    }
    return normalized.toUpperCase();
  }
  shouldCancelNavigation(normalizedStatus) {
    return normalizedStatus === "STOPPED" || normalizedStatus === "ABORTING_OR_STOPPING";
  }
  async cancelNavigationWithDebounce(url, cancelNavigation, currentStatus, from) {
    var _a;
    const now = Date.now();
    if (now - this.lastCancelNavigationAt < this.cancelNavigationDebounceMs) {
      (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`接收指令为：${currentStatus}, ${from} 命中去重窗口(${this.cancelNavigationDebounceMs}ms)，跳过重复取消导航`);
      return "SKIPPED_DEBOUNCE";
    }
    const result = await this.remoteCall(url, cancelNavigation);
    this.lastCancelNavigationAt = now;
    return result;
  }
  async monitorRobotStatus() {
    var _a, _b, _c;
    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log("Monitoring AGV robot status");
    const pauseAgvSpeed = {
      moduleName: "Agvc",
      functionNam: "pauseAgvSpeed",
      params: []
    };
    const resumeAgvSpeed = {
      moduleName: "Agvc",
      functionNam: "resumeAgvSpeed",
      params: []
    };
    const cancelNavigation = {
      moduleName: "Agvc",
      functionNam: "cancelNavigation",
      params: []
    };
    const url = `http://${agv_constant_1.AGV_DEFAULT_HOST}:${agv_constant_1.AGV_STEERING_WORKER_SERVER_PORT}/api/sdk/remote-call`;
    (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log("Setting up robot mode callback");
    const accordingRobotRunStatusChangeAgvStatus = async status => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _j;
      try {
        const previousStatus = this.normalizeRuntimeState(this.robotStatus);
        const currentStatus = this.normalizeRuntimeState(status);
        if (previousStatus !== currentStatus) {
          (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`Runtime state changed: ${previousStatus} -> ${currentStatus} (raw: ${status})`);
          if (previousStatus === "RUNNING") {
            let result;
            switch (currentStatus) {
              case "PAUSED":
                result = await this.remoteCall(url, pauseAgvSpeed);
                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log(`接收指令为：Paused,下发暂停指令，反馈结果为：${result}`);
                break;
              case "STOPPED":
              case "ABORTING_OR_STOPPING":
                result = await this.cancelNavigationWithDebounce(url, cancelNavigation, currentStatus, "Running");
                (_c = this.logger) === null || _c === void 0 ? void 0 : _c.log(`接收指令为：${currentStatus},下发取消导航指令，反馈结果为：${result}`);
                break;
              default:
                (_d = this.logger) === null || _d === void 0 ? void 0 : _d.log(`Running-状态变化为：${currentStatus},未下发任何指令`);
            }
          } else if (previousStatus === "PAUSED") {
            let result;
            switch (currentStatus) {
              case "RUNNING":
                result = await this.remoteCall(url, resumeAgvSpeed);
                (_e = this.logger) === null || _e === void 0 ? void 0 : _e.log(`接收指令为：RUNNING,下发恢复运行指令，反馈结果为：${result}`);
                break;
              case "STOPPED":
              case "ABORTING_OR_STOPPING":
                result = await this.cancelNavigationWithDebounce(url, cancelNavigation, currentStatus, "Paused");
                (_f = this.logger) === null || _f === void 0 ? void 0 : _f.log(`接收指令为：${currentStatus},下发取消导航指令，反馈结果为：${result}`);
                break;
              default:
                (_g = this.logger) === null || _g === void 0 ? void 0 : _g.log(`Paused-状态变化为：${currentStatus},未下发任何指令`);
            }
          } else if (this.shouldCancelNavigation(currentStatus)) {
            const result = await this.cancelNavigationWithDebounce(url, cancelNavigation, currentStatus, "Compensation");
            (_h = this.logger) === null || _h === void 0 ? void 0 : _h.log(`接收指令为：${currentStatus},补偿下发取消导航指令，反馈结果为：${result}`);
          }
          this.robotStatus = currentStatus;
        }
        return true;
      } catch (e) {
        (_j = this.logger) === null || _j === void 0 ? void 0 : _j.error(`Failed to register robot mode callback: ${e}`);
        return false;
      }
    };
    if (!this.monitorInterval) {
      this.monitorInterval = setInterval(async () => {
        var _a, _b;
        try {
          accordingRobotRunStatusChangeAgvStatus((_b = (_a = this.robotProxy) === null || _a === void 0 ? void 0 : _a.getRealtimeRobotState()) === null || _b === void 0 ? void 0 : _b.getRuntimeState());
        } catch (e) {} finally {}
      }, 300);
      (_c = this.logger) === null || _c === void 0 ? void 0 : _c.log("Started persistent monitor interval to maintain RTDE callback");
    }
  }
  async remoteCall(url, parm) {
    var _a, _b;
    try {
      const result = await axios_1.default.post(url, parm);
      return (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.data;
    } catch (error) {
      (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(`Remote call failed: ${error}`);
      return -1;
    }
  }
  getControlConnectionAndStatus() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    if (((_b = (_a = this.robotProxy) === null || _a === void 0 ? void 0 : _a.getRpcClient()) === null || _b === void 0 ? void 0 : _b.getWsClient().getWsClient()) !== null && ((_d = (_c = this.robotProxy) === null || _c === void 0 ? void 0 : _c.getRpcClient()) === null || _d === void 0 ? void 0 : _d.getWsClient().getWsClient()) !== undefined && ((_f = (_e = this.robotProxy) === null || _e === void 0 ? void 0 : _e.getRpcClient()) === null || _f === void 0 ? void 0 : _f.getWsClient().getWsClient().readyState) === aubo_sdk_1.WS_CLIENT_STATUS.OPEN && ((_h = (_g = this.robotProxy) === null || _g === void 0 ? void 0 : _g.getRtdeClient()) === null || _h === void 0 ? void 0 : _h.getCurrentWsClientStatus()) === aubo_sdk_1.WS_CLIENT_STATUS.OPEN && ((_k = (_j = this.robotProxy) === null || _j === void 0 ? void 0 : _j.getScriptClient()) === null || _k === void 0 ? void 0 : _k.getCurrentWsClientStatus()) === aubo_sdk_1.WS_CLIENT_STATUS.OPEN) {
      return robot_proxy_constants_1.ControlConnectStatus.IN_SERVICE;
    }
    return robot_proxy_constants_1.ControlConnectStatus.CONTROL_ERROR;
  }
}
exports.AgvService = AgvService;
//# sourceMappingURL=agv.service.js.map