/**
 * ============================================================
 * AirScript: 按钮触发 — 自动创建部署子表记录 (v2)
 * ============================================================
 *
 * 触发方式: 按钮字段触发 (项目本地化部署状态表中的按钮列)
 *
 * 核心逻辑:
 *   1. 通过按钮获取当前行数据 (部署编号、项目名称、部署平台等)
 *   2. 获取当前行的 recordId，用于 Link 关联字段回写
 *   3. 根据「部署平台」字段严格区分: 飞服平台只建飞服微服务，监管平台只建监管微服务
 *   4. 所有新建记录自动填写「项目名称」字段
 *   5. 所有新建记录自动通过 Link 关联回「项目本地化部署状态表」当前行
 *
 * 变更日志:
 *   v2 - 2026-03-09
 *     - 新增: 项目名称字段自动填入子表记录
 *     - 新增: 所属部署 Link 关联字段自动回写 (通过 recordId)
 *     - 修复: 平台判定逻辑，飞服平台不再同时生成监管服务
 *
 * ============================================================
 */

// ========================================================================
// 第一部分: 配置定义区域 (所有可配置项集中在此)
// ========================================================================

// --- 表名配置 ---
const TABLE_NAMES = {
  deployStatus: "项目本地化部署状态表",
  middleware:   "项目部署中间件信息表",
  business:     "项目部署业务信息表",
  network:      "项目部署网络信息表",
};

// --- 中间件配置 ---
// 所有中间件信息在此处定义，每新增/删除中间件只需修改此数组
const MIDDLEWARE_LIST = [
  { type: "MySQL",          version: "",  deployMethod: "容器化", defaultPublicPort: "",     defaultPrivatePort: "3306",  defaultPrivateIP: "" },
  { type: "Redis",          version: "",  deployMethod: "容器化", defaultPublicPort: "",     defaultPrivatePort: "6379",  defaultPrivateIP: "" },
  { type: "RabbitMQ",       version: "",  deployMethod: "容器化", defaultPublicPort: "",     defaultPrivatePort: "5672",  defaultPrivateIP: "" },
  { type: "EMQX",           version: "",  deployMethod: "容器化", defaultPublicPort: "",     defaultPrivatePort: "1883",  defaultPrivateIP: "" },
  { type: "NACOS",          version: "",  deployMethod: "容器化", defaultPublicPort: "",     defaultPrivatePort: "8848",  defaultPrivateIP: "" },
  { type: "K8S Dashboard",  version: "",  deployMethod: "容器化", defaultPublicPort: "",     defaultPrivatePort: "443",   defaultPrivateIP: "" },
  { type: "MINIO",          version: "",  deployMethod: "容器化", defaultPublicPort: "9000", defaultPrivatePort: "9000",  defaultPrivateIP: "" },
];

// --- 业务微服务配置 ---
// 使用 Map 格式: key 为部署平台标识，value 为该平台对应的微服务列表
// 「飞服平台」和「监管平台」的微服务名称不同

const BUSINESS_SERVICES_MAP = {
  // 公共服务 (两个平台都需要部署的)
  "common": [
    { name: "网关服务 (fly-gateway)",       branch: "", image: "", version: "" },
    { name: "认证服务 (fly-auth)",           branch: "", image: "", version: "" },
    { name: "用户服务 (fly-system)",         branch: "", image: "", version: "" },
    { name: "文件服务 (fly-file)",           branch: "", image: "", version: "" },
  ],

  // 飞行服务平台专属微服务
  "fly": [
    { name: "飞服-飞行管理 (fly-flight)",        branch: "", image: "", version: "" },
    { name: "飞服-设备管理 (fly-device)",         branch: "", image: "", version: "" },
    { name: "飞服-空域管理 (fly-airspace)",       branch: "", image: "", version: "" },
    { name: "飞服-任务调度 (fly-task)",           branch: "", image: "", version: "" },
    { name: "飞服-数据中心 (fly-datacenter)",     branch: "", image: "", version: "" },
    { name: "飞服-消息服务 (fly-message)",        branch: "", image: "", version: "" },
  ],

  // 监管平台专属微服务
  "supervisor": [
    { name: "监管-飞行监管 (sup-flight)",        branch: "", image: "", version: "" },
    { name: "监管-无人机管理 (sup-uav)",          branch: "", image: "", version: "" },
    { name: "监管-空域管理 (sup-airspace)",       branch: "", image: "", version: "" },
    { name: "监管-预警处置 (sup-warning)",        branch: "", image: "", version: "" },
    { name: "监管-数据中心 (sup-datacenter)",     branch: "", image: "", version: "" },
    { name: "监管-消息服务 (sup-message)",        branch: "", image: "", version: "" },
  ],
};

// 需要跳过的字段类型 (这些类型不能直接传文本值)
// 注意: Link 已移除，由脚本通过 recordId 自动处理
const SKIP_FIELD_TYPES = [
  "Lookup", "Formula",
  "CreatedTime", "ModifiedTime", "CreatedBy", "ModifiedBy",
  "AutoNumber",
];


// ========================================================================
// 第二部分: 通用工具函数
// ========================================================================

/**
 * 读取指定视图中某行某字段的原始值 (.Value)
 * 适用于普通文本、数字等字段
 */
function readCell(view, row, fieldName) {
  try {
    return view.RecordRange(row + ":" + row, ["@" + fieldName]).Value;
  } catch (e) {
    console.warn("⚠️ 读取 [" + fieldName + "] 行" + row + " 失败: " + e.message);
    return null;
  }
}

/**
 * 读取指定视图中某行某字段的显示文本 (.Text)
 * ★ 适用于 Link/引用/Lookup 等复杂字段，返回用户可见的文本而非原始对象
 * 例如: 项目名称 是引用字段时，.Value 返回 {"Value":"[]"}，.Text 返回 "项目A"
 */
function readCellText(view, row, fieldName) {
  try {
    return view.RecordRange(row + ":" + row, ["@" + fieldName]).Text;
  } catch (e) {
    console.warn("⚠️ 读取Text [" + fieldName + "] 行" + row + " 失败: " + e.message);
    return null;
  }
}

/**
 * 获取表的字段信息 (含类型和额外属性)
 * @returns {{ typeMap: Object, fieldsList: Array }}
 */
function getFieldInfo(sheetId) {
  let typeMap = {};
  let fieldsList = [];
  try {
    let fieldsResult = Application.Field.GetFields({ SheetId: sheetId });
    fieldsList = fieldsResult.fields || fieldsResult;
    if (Array.isArray(fieldsList)) {
      for (let i = 0; i < fieldsList.length; i++) {
        let f = fieldsList[i];
        typeMap[f.name] = f.type;
      }
    }
  } catch (e) {
    console.warn("⚠️ 获取字段信息失败: " + e.message);
  }
  return { typeMap: typeMap, fieldsList: fieldsList };
}

/**
 * ★ 通过字段值匹配获取 recordId (不再依赖行索引)
 *
 * GetRecords 返回顺序可能与视图行号不一致，
 * 所以用「部署编号」等唯一字段值来精确匹配正确的记录。
 *
 * @param {number} sheetId - 表 ID
 * @param {string} matchFieldName - 用于匹配的字段名 (如 "部署编号")
 * @param {string} matchFieldValue - 要匹配的字段值
 * @returns {string|null} recordId
 */
function getRecordIdByMatch(sheetId, matchFieldName, matchFieldValue) {
  try {
    let result = Application.Record.GetRecords({ SheetId: sheetId });
    let records = result.records || result;

    if (!Array.isArray(records)) {
      console.warn("   📎 GetRecords 返回非数组: " + typeof records);
      return null;
    }

    console.log("   📎 总记录数: " + records.length + "，查找字段 [" + matchFieldName + "] = [" + matchFieldValue + "]");

    // 打印第一条记录结构用于调试
    if (records.length > 0) {
      let first = records[0];
      let firstId = first.id || first.Id || first.recordId;
      console.log("   📎 记录结构示例 — id: " + firstId + ", keys: " + Object.keys(first).join(", "));
      if (first.fields) {
        console.log("   📎 fields keys: " + Object.keys(first.fields).join(", "));
      }
    }

    // 遍历所有记录，按字段值匹配
    for (let i = 0; i < records.length; i++) {
      let record = records[i];
      let recordId = record.id || record.Id || record.recordId;
      let fields = record.fields || record;

      // 获取匹配字段的值
      let fieldValue = null;
      if (fields[matchFieldName] !== undefined) {
        fieldValue = fields[matchFieldName];
      } else if (record.fields && record.fields[matchFieldName] !== undefined) {
        fieldValue = record.fields[matchFieldName];
      }

      // 比较字段值 (转为字符串比较，处理各种类型)
      let fieldValueStr = (fieldValue !== null && fieldValue !== undefined) ? String(fieldValue).trim() : "";

      if (fieldValueStr === String(matchFieldValue).trim()) {
        console.log("   📎 ✅ 匹配成功！记录[" + i + "] recordId: " + recordId);
        return String(recordId);
      }
    }

    console.warn("   📎 ❌ 未找到匹配的记录");
    return null;
  } catch (e) {
    console.warn("⚠️ 获取 recordId 失败: " + e.message);
    return null;
  }
}

/**
 * 安全创建记录: 自动检测字段类型，正确处理 Link 关联字段
 *
 * @param {string} tableName - 目标表名
 * @param {Array} recordsData - 记录数据数组，每条为 { fieldName: value }
 * @param {Object} linkFieldValues - Link 字段值映射 { fieldName: [recordId] }
 * @returns {boolean} 是否成功
 */
function createRecordsSafely(tableName, recordsData, linkFieldValues) {
  const sheet = Application.Sheets.Item(tableName);
  const sheetId = sheet.Id;

  console.log("   📊 检测表 [" + tableName + "] 的字段类型...");
  let fieldInfo = getFieldInfo(sheetId);
  let fieldTypeMap = fieldInfo.typeMap;

  let cleanRecords = [];
  let skippedFields = [];

  for (let r = 0; r < recordsData.length; r++) {
    let originalFields = recordsData[r];
    let cleanFields = {};

    for (let fieldName in originalFields) {
      let value = originalFields[fieldName];
      let fieldType = fieldTypeMap[fieldName];

      // 字段不存在于表中，如果值非空仍传入
      if (!fieldType) {
        if (value === "" || value === null || value === undefined) continue;
        cleanFields[fieldName] = value;
        continue;
      }

      // === Link 字段特殊处理 ===
      // Link 字段需要传入 recordId 数组格式: [recordId]
      if (fieldType === "Link") {
        if (linkFieldValues && linkFieldValues[fieldName]) {
          cleanFields[fieldName] = linkFieldValues[fieldName];
          console.log("   🔗 Link 字段 [" + fieldName + "] → " + JSON.stringify(linkFieldValues[fieldName]));
        } else {
          if (skippedFields.indexOf(fieldName) < 0) {
            skippedFields.push(fieldName);
            console.log("   ⏭️ 跳过 Link 字段 [" + fieldName + "] (无 recordId 可关联)");
          }
        }
        continue;
      }

      // 跳过不兼容字段类型
      if (SKIP_FIELD_TYPES.indexOf(fieldType) >= 0) {
        if (skippedFields.indexOf(fieldName) < 0) {
          skippedFields.push(fieldName);
          console.log("   ⏭️ 跳过字段 [" + fieldName + "] (类型: " + fieldType + ")");
        }
        continue;
      }

      // 跳过非文本字段的空值
      if ((value === "" || value === null || value === undefined) &&
          fieldType !== "MultiLineText" && fieldType !== "Text") {
        continue;
      }

      cleanFields[fieldName] = value;
    }

    // 追加 Link 字段 (如果记录数据中没有显式包含，但 linkFieldValues 中有)
    if (linkFieldValues) {
      for (let linkFieldName in linkFieldValues) {
        if (!cleanFields[linkFieldName] && fieldTypeMap[linkFieldName] === "Link") {
          cleanFields[linkFieldName] = linkFieldValues[linkFieldName];
        }
      }
    }

    cleanRecords.push({ fields: cleanFields });
  }

  if (cleanRecords.length === 0) {
    console.warn("⚠️ 没有有效记录需要创建");
    return false;
  }

  console.log("   📋 将创建 " + cleanRecords.length + " 条记录");

  // 打印首条记录内容 (用于调试)
  if (cleanRecords.length > 0) {
    let firstFields = cleanRecords[0].fields;
    console.log("   📋 首条记录字段:");
    for (let fn in firstFields) {
      let v = firstFields[fn];
      let display = (typeof v === "object") ? JSON.stringify(v) : String(v);
      console.log("      " + fn + " = " + display);
    }
  }

  // 批量创建记录
  Application.Record.CreateRecords({
    SheetId: sheetId,
    Records: cleanRecords,
  });

  console.log("   ✅ 成功创建 " + cleanRecords.length + " 条记录");

  if (skippedFields.length > 0) {
    console.log("   ⚠️ 以下字段需要手动设置: " + skippedFields.join(", "));
  }

  return true;
}


// ========================================================================
// 第三部分: 获取按钮触发行的数据
// ========================================================================

/**
 * 获取当前按钮所在行的部署信息
 * ★ Context.argv.p1 是记录ID (recordId)，不是行号
 */
function getTriggerRecordInfo() {
  try {
    const sheet = Application.Sheets.Item(TABLE_NAMES.deployStatus);
    const sheetId = sheet.Id;
    const view = sheet.Views(1);
    const totalRows = view.RecordRange.Count;
    console.log("📋 部署状态表共 " + totalRows + " 行记录");

    // ★ 核心: Context.argv.p1 是记录ID (recordId)
    let recordId = null;
    if (typeof Context !== "undefined" && Context.argv) {
      console.log("📥 按钮入参: " + JSON.stringify(Context.argv));
      if (Context.argv.p1) {
        recordId = String(Context.argv.p1).trim();
        console.log("   📎 按钮传入的记录ID: " + recordId);
      }
    }

    // ★ 通过 recordId 定位视图中的行号 (用于 readCell/readCellText 读取字段)
    let targetRow = null;

    if (recordId) {
      // 用 GetRecords 找到 recordId 对应的索引，再映射到行号
      try {
        let result = Application.Record.GetRecords({ SheetId: sheetId });
        let records = result.records || result;
        if (Array.isArray(records)) {
          for (let i = 0; i < records.length; i++) {
            let rid = records[i].id || records[i].Id || records[i].recordId;
            if (String(rid) === recordId) {
              targetRow = i + 1;  // 视图行号从1开始
              console.log("   📎 recordId 匹配到记录索引 " + i + "，映射行号: " + targetRow);
              break;
            }
          }
        }
      } catch (e) {
        console.warn("   ⚠️ GetRecords 定位行号失败: " + e.message);
      }
    }

    // 如果通过 recordId 找不到行号，fallback 到选区
    if (!targetRow) {
      try {
        let selection = Application.Selection;
        let range = selection.Range;
        if (range && range.Rows && range.Rows.Count > 0) {
          targetRow = range.Rows(1).Row;
          console.log("   使用当前选区行: " + targetRow);
        }
      } catch (e) {
        console.warn("   ⚠️ 无法获取选区: " + e.message);
      }
    }

    // 最后 fallback: 扫描查找「部署中」记录
    if (!targetRow) {
      console.log("📋 扫描全表查找「部署中」记录...");
      for (let i = totalRows; i >= 1; i--) {
        let status = readCell(view, i, "部署状态");
        if (status && String(status) === "部署中") {
          targetRow = i;
          console.log("   找到第 " + i + " 行状态为「部署中」");
          break;
        }
      }
    }

    if (!targetRow || targetRow < 1 || targetRow > totalRows) {
      console.error("❌ 未找到有效的目标记录行");
      return null;
    }

    // 读取本行关键字段
    let deployId       = readCell(view, targetRow, "部署编号");
    let deployer       = readCell(view, targetRow, "部署负责人");
    let status         = readCell(view, targetRow, "部署状态");
    let namespace      = readCell(view, targetRow, "命名空间");
    let deployPlatform = readCell(view, targetRow, "部署平台");

    // 使用 .Text 读取项目名称 (Link/引用类型字段)
    let rawProjectName = readCellText(view, targetRow, "项目名称");
    let rawRelProject  = readCellText(view, targetRow, "关联项目");

    console.log("   📝 项目名称(.Text): [" + rawProjectName + "]");
    console.log("   📝 关联项目(.Text): [" + rawRelProject + "]");

    let finalProjectName = "";
    if (rawProjectName && String(rawProjectName).trim() !== "" && String(rawProjectName).trim() !== "[]") {
      finalProjectName = String(rawProjectName).trim();
    } else if (rawRelProject && String(rawRelProject).trim() !== "" && String(rawRelProject).trim() !== "[]") {
      finalProjectName = String(rawRelProject).trim();
    } else {
      finalProjectName = "未关联项目";
    }
    console.log("   📝 最终项目名称: [" + finalProjectName + "]");

    // ★ recordId 来源优先级:
    //   1. Context.argv.p1 (按钮直接传入，最可靠)
    //   2. 无 fallback，没有 recordId 则 Link 无法自动关联
    if (!recordId) {
      console.warn("⚠️ 按钮未传入 recordId (p1)，所属部署 Link 关联将无法自动设置");
    }

    let deployIdStr = deployId ? String(deployId).trim() : "未编号";

    return {
      row:             targetRow,
      recordId:        recordId,          // ★ 直接来自按钮 p1 参数
      sheetId:         sheetId,
      deployId:        deployIdStr,
      projectName:     finalProjectName,
      deployer:        deployer        ? String(deployer).trim()        : "",
      status:          status          ? String(status).trim()          : "",
      namespace:       namespace       ? String(namespace).trim()       : "",
      deployPlatform:  deployPlatform  ? String(deployPlatform).trim()  : "",
    };
  } catch (e) {
    console.error("❌ 获取触发记录信息失败: " + e.message);
    return null;
  }
}


// ========================================================================
// 第四部分: 防重复检查
// ========================================================================

function checkExistingRecords(triggerInfo) {
  try {
    const sheet = Application.Sheets.Item(TABLE_NAMES.middleware);
    const view = sheet.Views(1);
    const count = view.RecordRange.Count;

    if (count === 0) return false;

    for (let i = 1; i <= count; i++) {
      let existingDeployId = readCell(view, i, "所属部署");
      if (existingDeployId && String(existingDeployId).trim() === triggerInfo.deployId) {
        console.warn("⚠️ 中间件表第 " + i + " 行已存在部署编号 [" + triggerInfo.deployId + "] 的记录");
        return true;
      }
    }

    return false;
  } catch (e) {
    console.warn("⚠️ 检查已有记录时出错: " + e.message);
    return false;
  }
}


// ========================================================================
// 第五部分: 创建记录逻辑
// ========================================================================

/**
 * 判定部署平台类型 — 仅依据「部署平台」字段
 * @returns {string} "fly" | "supervisor" | "both" | "error"
 */
function detectPlatformType(triggerInfo) {
  let platform = triggerInfo.deployPlatform;
  console.log("   🔍 部署平台原始值: [" + platform + "]");

  if (platform) {
    // 同时包含飞服和监管 → both
    if (platform.indexOf("飞服") >= 0 && platform.indexOf("监管") >= 0) {
      console.log("   🔍 匹配结果: both (同时包含飞服和监管)");
      return "both";
    }
    // 仅包含飞服 → fly
    if (platform.indexOf("飞服") >= 0 || platform.indexOf("飞行服务") >= 0) {
      console.log("   🔍 匹配结果: fly (飞行服务平台)");
      return "fly";
    }
    // 仅包含监管 → supervisor
    if (platform.indexOf("监管") >= 0) {
      console.log("   🔍 匹配结果: supervisor (监管平台)");
      return "supervisor";
    }
    // 部署平台有值但不包含已知关键词
    console.error("❌ 部署平台值 [" + platform + "] 无法识别");
    console.error('   已知值: 包含"飞服"→飞服平台, 包含"监管"→监管平台');
    return "error";
  }

  // 部署平台字段为空
  console.error("❌ 「部署平台」字段为空！请先填写部署平台");
  console.error("   飞服平台 → 只创建飞服微服务");
  console.error("   监管平台 → 只创建监管微服务");
  return "error";
}

/**
 * 构建 Link 关联字段值
 * 所有子表的「所属部署」字段都应关联回部署状态表的当前行
 */
function buildLinkFieldValues(triggerInfo) {
  if (!triggerInfo.recordId) {
    console.warn("   ⚠️ 无法获取 recordId，Link 关联字段将无法自动设置");
    return {};
  }
  // Link 字段值格式: [recordId] (数组)
  return {
    "所属部署": [triggerInfo.recordId],
  };
}

/**
 * 创建中间件信息记录
 */
function createMiddlewareRecords(triggerInfo) {
  console.log("\n📦 创建中间件信息记录...");

  try {
    let linkValues = buildLinkFieldValues(triggerInfo);
    let records = [];

    for (let i = 0; i < MIDDLEWARE_LIST.length; i++) {
      let mw = MIDDLEWARE_LIST[i];
      records.push({
        "项目名称":     triggerInfo.projectName,   // ★ 新增: 填写项目名称
        "所属部署":     triggerInfo.deployId,       // 文本备份 (如果 Link 不生效则有文本)
        "中间件类型":   mw.type,
        "中间件版本":   mw.version,
        "部署方式":     mw.deployMethod,
        "是否暴露公网": false,
        "公网端口":     mw.defaultPublicPort,
        "内网端口":     mw.defaultPrivatePort,
        "内网IP":       mw.defaultPrivateIP,
      });
    }

    let success = createRecordsSafely(TABLE_NAMES.middleware, records, linkValues);
    if (success) {
      console.log("📦 中间件信息创建完成，共 " + MIDDLEWARE_LIST.length + " 条");
    }
  } catch (e) {
    console.error("❌ 创建中间件记录失败: " + e.message);
  }
}

/**
 * 创建业务信息记录 — 严格按部署平台区分
 */
function createBusinessRecords(triggerInfo) {
  console.log("\n🔧 创建业务信息记录...");

  try {
    let platformType = detectPlatformType(triggerInfo);
    console.log("   📌 最终部署平台类型: " + platformType);

    // ★ 修复: 无法判定时终止，不再默认创建全部
    if (platformType === "error") {
      console.error("❌ 部署平台类型无法判定，跳过业务信息创建");
      console.error("   请确保「部署平台」字段已正确填写（飞服平台/监管平台）");
      return;
    }

    let linkValues = buildLinkFieldValues(triggerInfo);

    // 构建微服务列表: 公共服务 + 对应平台服务
    let serviceList = [];

    // 始终包含公共服务
    let commonServices = BUSINESS_SERVICES_MAP["common"] || [];
    for (let i = 0; i < commonServices.length; i++) {
      serviceList.push(commonServices[i]);
    }

    // ★ 修复: 严格按平台添加专属服务
    if (platformType === "fly" || platformType === "both") {
      let flyServices = BUSINESS_SERVICES_MAP["fly"] || [];
      for (let i = 0; i < flyServices.length; i++) {
        serviceList.push(flyServices[i]);
      }
      console.log("   ✅ 添加飞服平台微服务: " + (BUSINESS_SERVICES_MAP["fly"] || []).length + " 条");
    }

    if (platformType === "supervisor" || platformType === "both") {
      let supServices = BUSINESS_SERVICES_MAP["supervisor"] || [];
      for (let i = 0; i < supServices.length; i++) {
        serviceList.push(supServices[i]);
      }
      console.log("   ✅ 添加监管平台微服务: " + (BUSINESS_SERVICES_MAP["supervisor"] || []).length + " 条");
    }

    if (serviceList.length === 0) {
      console.warn("⚠️ 没有匹配的微服务，跳过业务信息创建");
      return;
    }

    // 构建记录
    let records = [];
    for (let i = 0; i < serviceList.length; i++) {
      let svc = serviceList[i];
      records.push({
        "项目名称":   triggerInfo.projectName,   // ★ 新增: 填写项目名称
        "所属部署":   triggerInfo.deployId,       // 文本备份
        "微服务名称": svc.name,
        "微服务分支": svc.branch,
        "微服务镜像": svc.image,
        "微服务版本": svc.version,
        "部署状态":   "待部署",
      });
    }

    let success = createRecordsSafely(TABLE_NAMES.business, records, linkValues);
    if (success) {
      console.log("🔧 业务信息创建完成，共 " + serviceList.length + " 条");
      console.log("   → 公共服务: " + commonServices.length + " 条");
      if (platformType === "fly") {
        console.log("   → 飞服平台: " + (BUSINESS_SERVICES_MAP["fly"] || []).length + " 条");
        console.log("   → 监管平台: 不创建 (当前为飞服平台部署)");
      } else if (platformType === "supervisor") {
        console.log("   → 飞服平台: 不创建 (当前为监管平台部署)");
        console.log("   → 监管平台: " + (BUSINESS_SERVICES_MAP["supervisor"] || []).length + " 条");
      } else {
        console.log("   → 飞服平台: " + (BUSINESS_SERVICES_MAP["fly"] || []).length + " 条");
        console.log("   → 监管平台: " + (BUSINESS_SERVICES_MAP["supervisor"] || []).length + " 条");
      }
    }
  } catch (e) {
    console.error("❌ 创建业务记录失败: " + e.message);
  }
}

/**
 * 创建网络信息记录
 */
function createNetworkRecords(triggerInfo) {
  console.log("\n🌐 创建网络信息记录...");

  try {
    let linkValues = buildLinkFieldValues(triggerInfo);
    let records = [{
      "项目名称":     triggerInfo.projectName,   // ★ 新增: 填写项目名称
      "所属部署":     triggerInfo.deployId,       // 文本备份
      "是否开启SSL":  false,
      "端口信息说明": "待填写",
      "备注":         "自动创建 — 部署编号: " + triggerInfo.deployId + " | 项目: " + triggerInfo.projectName,
    }];

    let success = createRecordsSafely(TABLE_NAMES.network, records, linkValues);
    if (success) {
      console.log("🌐 网络信息创建完成，共 1 条");
    }
  } catch (e) {
    console.error("❌ 创建网络记录失败: " + e.message);
  }
}


// ========================================================================
// 第六部分: 主函数 — 入口
// ========================================================================

function main() {
  console.log("====================================");
  console.log("🚀 按钮触发: 自动创建部署子表记录 v3");
  console.log("====================================");

  // Step 1: 获取触发记录信息 (recordId 来自按钮 p1 参数)
  let triggerInfo = getTriggerRecordInfo();
  if (!triggerInfo) {
    console.error("❌ 无法获取触发记录信息，脚本终止");
    return;
  }

  console.log("\n✅ 触发记录信息:");
  console.log("   行号:       " + triggerInfo.row);
  console.log("   recordId:   " + (triggerInfo.recordId || "未获取到"));
  console.log("   部署编号:   " + triggerInfo.deployId);
  console.log("   项目名称:   " + triggerInfo.projectName);
  console.log("   部署负责人: " + triggerInfo.deployer);
  console.log("   部署状态:   " + triggerInfo.status);
  console.log("   命名空间:   " + triggerInfo.namespace);
  console.log("   部署平台:   " + triggerInfo.deployPlatform);

  // Link 关联提示
  if (triggerInfo.recordId) {
    console.log("\n🔗 Link 关联: 已获取到 recordId，将自动设置所属部署关联");
  } else {
    console.warn("\n⚠️ Link 关联: 未获取到 recordId，所属部署关联需要手动设置");
  }

  // Step 2: 防重复检查
  if (checkExistingRecords(triggerInfo)) {
    console.warn("\n⚠️ 中间件表中已存在部署编号 [" + triggerInfo.deployId + "] 的记录！");
    console.warn("   为防止重复创建，脚本终止。");
    console.warn("   如需重新创建，请先手动删除已有记录。");
    return;
  }

  // Step 3: 创建中间件信息记录
  createMiddlewareRecords(triggerInfo);

  // Step 4: 创建业务信息记录 (严格按部署平台区分)
  createBusinessRecords(triggerInfo);

  // Step 5: 创建网络信息记录
  createNetworkRecords(triggerInfo);

  console.log("\n====================================");
  console.log("✅ 所有子表记录创建完成！");
  console.log("====================================");
  console.log("📌 提示:");
  if (triggerInfo.recordId) {
    console.log("   ✅ 所属部署 Link 关联已自动设置");
  } else {
    console.log("   ⚠️ 所属部署 Link 关联需要手动设置 (recordId 未获取)");
  }
  console.log("   ✅ 项目名称已自动填写: " + triggerInfo.projectName);
  console.log("   📝 请检查中间件的内网IP和公网端口是否需要修改");
  console.log("   📝 业务微服务的分支和镜像信息需要后续补充");
}

// 执行入口
main();
