/**
 * ============================================================
 * AirScript: 部署状态切换为"部署中"时自动创建子表记录
 * ============================================================
 *
 * 触发方式:
 *   方式一: 自动化流程触发 (推荐)
 *   方式二: 手动在 AirScript 编辑器中运行
 *
 * 核心逻辑:
 *   1. 读取「项目本地化部署状态表」中状态为「部署中」的记录
 *   2. 使用 Application.Field.GetFields() 检测各子表的实际字段类型
 *   3. 自动跳过 Link(关联)等不兼容字段，避免 E_INVALIDARG 错误
 *   4. 通过 Application.Record.CreateRecords() 批量创建新记录
 *
 * ============================================================
 */

// ============================
// 配置区域
// ============================

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

// 7 种标准中间件
const MIDDLEWARE_LIST = [
  { type: "MySQL",          version: "",  deployMethod: "容器化", defaultPort: "3306" },
  { type: "Redis",          version: "",  deployMethod: "容器化", defaultPort: "6379" },
  { type: "RabbitMQ",       version: "",  deployMethod: "容器化", defaultPort: "5672" },
  { type: "EMQX",           version: "",  deployMethod: "容器化", defaultPort: "1883" },
  { type: "NACOS",          version: "",  deployMethod: "容器化", defaultPort: "8848" },
  { type: "K8S Dashboard",  version: "",  deployMethod: "容器化", defaultPort: "443"  },
  { type: "MINIO",          version: "",  deployMethod: "容器化", defaultPort: "9000" },
];

// 默认初始业务微服务列表
const DEFAULT_SERVICES = [
  { name: "网关服务 (Gateway)",  branch: "", image: "", version: "" },
  { name: "认证服务 (Auth)",     branch: "", image: "", version: "" },
  { name: "用户服务 (User)",     branch: "", image: "", version: "" },
  { name: "飞服平台核心服务",     branch: "", image: "", version: "" },
  { name: "监管平台核心服务",     branch: "", image: "", version: "" },
];

// 需要跳过的字段类型 (这些类型需要特殊值格式，不能直接传文本)
const SKIP_FIELD_TYPES = ["Link", "Lookup", "Formula", "CreatedTime", "ModifiedTime", "CreatedBy", "ModifiedBy", "AutoNumber"];

// ============================
// 工具函数: 读取已有记录的字段值
// ============================
function readCell(view, row, fieldName) {
  try {
    return view.RecordRange(row + ":" + row, ["@" + fieldName]).Value;
  } catch (e) {
    console.warn("⚠️ 读取 [" + fieldName + "] 行" + row + " 失败: " + e.message);
    return null;
  }
}

// ============================
// 工具函数: 获取表的字段类型映射
// ============================
function getFieldTypeMap(sheetId) {
  let typeMap = {};
  try {
    let fieldsResult = Application.Field.GetFields({ SheetId: sheetId });
    // fieldsResult 可能是 {fields: [...]} 或直接是数组
    let 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;
        console.log("     字段: " + f.name + " → 类型: " + f.type);
      }
    }
  } catch (e) {
    console.warn("⚠️ 获取字段信息失败: " + e.message);
  }
  return typeMap;
}

// ============================
// 核心工具: 安全创建记录 (自动检测字段类型，跳过不兼容字段)
// ============================
function createRecordsSafely(tableName, recordsData) {
  const sheet = Application.Sheets.Item(tableName);
  const sheetId = sheet.Id;

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

  // 构建过滤后的记录，跳过不兼容字段
  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) {
        // 字段不存在于表中, 尝试仍然传入 (可能是 GetFields 没返回)
        // 但如果值为空就跳过
        if (value === "" || value === null || value === undefined) continue;
        cleanFields[fieldName] = value;
        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;
    }

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

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

  // 打印将要创建的第一条记录的字段信息 (调试用)
  console.log("   📋 将创建 " + cleanRecords.length + " 条记录，首条字段:");
  let firstFields = cleanRecords[0].fields;
  for (let fn in firstFields) {
    console.log("      " + fn + " = " + firstFields[fn]);
  }

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

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

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

  return true;
}

// ============================
// 主函数
// ============================
function main() {
  console.log("====================================");
  console.log("开始执行: 自动创建部署子表记录");
  console.log("====================================");

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

  console.log("\n✅ 触发记录信息:");
  console.log("   部署编号: " + triggerInfo.deployId);
  console.log("   关联项目: " + triggerInfo.projectName);
  console.log("   部署负责人: " + triggerInfo.deployer);
  console.log("   部署状态: " + triggerInfo.status);
  console.log("   命名空间: " + triggerInfo.namespace);

  // 校验部署状态
  if (triggerInfo.status !== "部署中") {
    console.warn("⚠️ 当前部署状态不是「部署中」，跳过");
    return;
  }

  // 校验部署负责人
  if (!triggerInfo.deployer || String(triggerInfo.deployer).trim() === "") {
    console.warn("⚠️ 部署负责人为空，跳过");
    return;
  }

  // Step 2: 防重复检查
  if (checkExistingRecords(triggerInfo)) {
    console.warn("⚠️ 已存在关联记录，跳过创建以防重复");
    return;
  }

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

  // Step 4: 创建业务信息记录
  createBusinessRecords(triggerInfo);

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

  console.log("\n====================================");
  console.log("✅ 所有子表记录创建完成！");
  console.log("====================================");
  console.log("📌 提示: 如果「所属部署」是关联字段(Link)，请手动在各子表中设置关联。");
}

// ============================
// 获取触发记录信息
// ============================
function getTriggerRecordInfo() {
  try {
    const sheet = Application.Sheets.Item(TABLE_NAMES.deployStatus);
    const view = sheet.Views(1);
    const totalRows = view.RecordRange.Count;
    console.log("📋 部署状态表共 " + totalRows + " 行记录");

    let targetRow = null;

    // 优先从自动化入参获取
    if (typeof Context !== "undefined" && Context.argv) {
      console.log("📥 自动化入参: " + JSON.stringify(Context.argv));
      if (Context.argv.p1) {
        targetRow = parseInt(Context.argv.p1);
      }
    }

    // 没有入参则从最后一行往前查找「部署中」
    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 projectName = readCell(view, targetRow, "关联项目");
    let deployer    = readCell(view, targetRow, "部署负责人");
    let status      = readCell(view, targetRow, "部署状态");
    let namespace   = readCell(view, targetRow, "命名空间");

    return {
      row:         targetRow,
      deployId:    deployId    ? String(deployId)    : "未编号",
      projectName: projectName ? String(projectName) : "未关联项目",
      deployer:    deployer    ? String(deployer)    : "",
      status:      status      ? String(status)      : "",
      namespace:   namespace   ? String(namespace)   : "",
    };
  } 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;

    // 尝试用「中间件类型」列 + 行数来判断
    // 如果已有 >= 7 条中间件记录且最近的标识匹配，认为已创建
    // 这里简单检查行数，后续可优化
    console.log("   中间件表当前共 " + count + " 条记录");

    return false; // 暂时不做防重检查，确保首次能创建成功
  } catch (e) {
    console.warn("⚠️ 检查已有记录时出错: " + e.message);
    return false;
  }
}

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

  try {
    let records = [];
    for (let i = 0; i < MIDDLEWARE_LIST.length; i++) {
      let mw = MIDDLEWARE_LIST[i];
      records.push({
        "所属部署":     triggerInfo.deployId,
        "中间件类型":   mw.type,
        "中间件版本":   mw.version,
        "部署方式":     mw.deployMethod,
        "是否暴露公网": false,
        "内网端口":     mw.defaultPort,
      });
    }

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

// ============================
// 创建业务信息记录
// ============================
function createBusinessRecords(triggerInfo) {
  console.log("\n🔧 创建业务信息记录...");

  try {
    let records = [];
    for (let i = 0; i < DEFAULT_SERVICES.length; i++) {
      let svc = DEFAULT_SERVICES[i];
      records.push({
        "所属部署":   triggerInfo.deployId,
        "微服务名称": svc.name,
        "微服务分支": svc.branch,
        "微服务镜像": svc.image,
        "微服务版本": svc.version,
        "部署状态":   "待部署",
      });
    }

    let success = createRecordsSafely(TABLE_NAMES.business, records);
    if (success) {
      console.log("🔧 业务信息创建完成，共 " + DEFAULT_SERVICES.length + " 条");
    }
  } catch (e) {
    console.error("❌ 创建业务记录失败: " + e.message);
  }
}

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

  try {
    let records = [{
      "所属部署":     triggerInfo.deployId,
      "是否开启SSL":  false,
      "端口信息说明": "待填写",
      "备注":         "自动创建 - 部署编号: " + triggerInfo.deployId + " 项目: " + triggerInfo.projectName,
    }];

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

// ============================
// 执行入口
// ============================
main();
