/**
 * ============================================================
 *  金山多维表格 AirScript — 导出表结构到数据表 (v3)
 * ============================================================
 *
 *  📌 使用方法:
 *     1. 打开你的金山多维表格文档
 *     2. 点击「脚本」→「JS脚本」→「新建脚本」
 *     3. 将本文件的全部内容粘贴进去
 *     4. 点击「运行」按钮
 *     5. 查看新生成的「数据导出-tmp」表，表结构数据全部在里面
 *
 *  📌 功能说明:
 *     - 遍历指定的 7 张表，获取所有字段信息
 *     - 自动创建「数据导出-tmp」表（如已存在会先删除再重建）
 *     - 将每个字段作为一行写入导出表，包含:
 *       表名、SheetId、字段序号、字段名称、字段类型、字段ID
 *     - 在控制台输出进度信息
 *
 *  📌 v3 修复:
 *     - 使用 FieldDescriptors.Count 和 .Item(i) 替代 .length 和 [i]
 *     - 增加 Application.Field.GetFields() 作为备选
 *     - 结果写入数据表而非仅输出到控制台
 */

// ============================================================
//  配置区
// ============================================================
var TARGET_TABLES = [
  '项目基本信息表',
  '项目本地化部署升级信息表',
  '项目本地化部署状态表',
  '项目部署环境信息表',
  '项目部署网络信息表',
  '项目部署中间件信息表',
  '项目部署业务信息表'
];

var FILTER_BY_NAME = true;
var EXPORT_TABLE_NAME = '数据导出-tmp';

// ============================================================
//  Step 1: 收集所有表的字段信息
// ============================================================

console.log("╔══════════════════════════════════════════════════════╗");
console.log("║   金山多维表格 — 表结构导出到数据表  (v3)           ║");
console.log("╚══════════════════════════════════════════════════════╝\n");

var sheets = Application.Sheets;
var totalCount = sheets.Count;
console.log("📊 当前文档共有 " + totalCount + " 张数据表\n");

// 收集所有字段行数据: [{tableName, sheetId, fieldIndex, fieldName, fieldType, fieldId}]
var allRows = [];

for (var i = 1; i <= totalCount; i++) {
  var sheet = sheets.Item(i);
  var sheetName = sheet.Name;
  var sheetId = sheet.Id;

  // 跳过导出表本身
  if (sheetName === EXPORT_TABLE_NAME) {
    console.log("⏭️  跳过导出表: " + sheetName);
    continue;
  }

  // 按名称过滤
  if (FILTER_BY_NAME && TARGET_TABLES.length > 0) {
    var found = false;
    for (var t = 0; t < TARGET_TABLES.length; t++) {
      if (TARGET_TABLES[t] === sheetName) {
        found = true;
        break;
      }
    }
    if (!found) {
      continue;
    }
  }

  console.log("📋 正在读取: " + sheetName + " (SheetId: " + sheetId + ")");

  var fields = [];

  // --- 方案 A: Application.Field.GetFields() ---
  try {
    var getFieldsResult = Application.Field.GetFields({ SheetId: sheetId });
    if (getFieldsResult) {
      // 可能是数组，也可能是 {fields: [...]} 结构
      var fieldArr = null;
      if (Array.isArray(getFieldsResult) && getFieldsResult.length > 0) {
        fieldArr = getFieldsResult;
      } else if (getFieldsResult.fields && Array.isArray(getFieldsResult.fields)) {
        fieldArr = getFieldsResult.fields;
      } else if (getFieldsResult.Fields && Array.isArray(getFieldsResult.Fields)) {
        fieldArr = getFieldsResult.Fields;
      }

      if (fieldArr && fieldArr.length > 0) {
        for (var g = 0; g < fieldArr.length; g++) {
          var gf = fieldArr[g];
          fields.push({
            name: gf.name || gf.Name || "未知",
            type: gf.type || gf.Type || "未知",
            id: gf.id || gf.Id || ""
          });
        }
        console.log("   ✅ GetFields 获取到 " + fields.length + " 个字段");
      }
    }
  } catch (e) {
    console.log("   ⚠️ GetFields 异常: " + e.message);
  }

  // --- 方案 B: FieldDescriptors ---
  if (fields.length === 0) {
    try {
      var descriptors = sheet.FieldDescriptors;
      var fdCount = descriptors.Count;
      if (fdCount && fdCount > 0) {
        for (var j = 1; j <= fdCount; j++) {
          var fd = descriptors.Item(j);
          fields.push({
            name: fd.name || "未知",
            type: fd.type || "未知",
            id: ""
          });
        }
        console.log("   ✅ FieldDescriptors 获取到 " + fields.length + " 个字段");
      }
    } catch (e2) {
      console.log("   ⚠️ FieldDescriptors 异常: " + e2.message);
    }
  }

  // --- 方案 C: Views.Fields 兜底 ---
  if (fields.length === 0) {
    try {
      var view = sheet.Views(1);
      if (view && view.Fields) {
        var vfObj = view.Fields;
        var vfCount = vfObj.Count || vfObj.length || 0;
        if (vfCount > 0) {
          for (var v = 1; v <= vfCount; v++) {
            try {
              var vf = vfObj.Item ? vfObj.Item(v) : vfObj[v - 1];
              if (vf) {
                fields.push({
                  name: vf.Name || vf.name || "未知",
                  type: vf.Type || vf.type || "未知",
                  id: vf.Id || vf.id || ""
                });
              }
            } catch (e3) {
              // skip
            }
          }
          console.log("   ✅ Views.Fields 获取到 " + fields.length + " 个字段");
        }
      }
    } catch (e4) {
      console.log("   ⚠️ Views 异常: " + e4.message);
    }
  }

  if (fields.length === 0) {
    console.log("   ❌ 未获取到字段");
    // 仍然写一行标记
    allRows.push({
      tableName: sheetName,
      sheetId: String(sheetId),
      fieldIndex: "0",
      fieldName: "(无法获取字段)",
      fieldType: "-",
      fieldId: ""
    });
  } else {
    for (var fi = 0; fi < fields.length; fi++) {
      allRows.push({
        tableName: sheetName,
        sheetId: String(sheetId),
        fieldIndex: String(fi + 1),
        fieldName: fields[fi].name,
        fieldType: fields[fi].type,
        fieldId: String(fields[fi].id || "")
      });
    }
  }
}

console.log("\n📊 共收集到 " + allRows.length + " 条字段记录\n");

// ============================================================
//  Step 2: 删除已有的导出表（如果存在）
// ============================================================

try {
  var existingExportSheet = null;
  for (var d = 1; d <= Application.Sheets.Count; d++) {
    if (Application.Sheets.Item(d).Name === EXPORT_TABLE_NAME) {
      existingExportSheet = Application.Sheets.Item(d);
      break;
    }
  }
  if (existingExportSheet) {
    console.log("🗑️  删除已存在的「" + EXPORT_TABLE_NAME + "」表...");
    existingExportSheet.Delete();
    console.log("   ✅ 已删除");
  }
} catch (e5) {
  console.log("⚠️ 删除旧表异常（可忽略）: " + e5.message);
}

// ============================================================
//  Step 3: 创建新的导出表
// ============================================================

console.log("📝 创建「" + EXPORT_TABLE_NAME + "」表...");

// 使用 CreateSheet 创建表（返回 {id}）
var createResult = Application.Sheet.CreateSheet({
  Name: EXPORT_TABLE_NAME,
  Views: [{ name: '默认视图', type: 'Grid' }],
  Fields: [
    { name: '所属表名', type: 'MultiLineText' },
    { name: 'SheetId', type: 'MultiLineText' },
    { name: '字段序号', type: 'MultiLineText' },
    { name: '字段名称', type: 'MultiLineText' },
    { name: '字段类型', type: 'MultiLineText' },
    { name: '字段ID', type: 'MultiLineText' }
  ]
});

var newSheetId = createResult.id;
console.log("   ✅ 创建成功, SheetId: " + newSheetId);

// 等待一下让表注册完成
Time.sleep(500);

// 通过遍历 Sheets 集合找到新创建的表对象
var newSheet = null;
var refreshedSheets = Application.Sheets;
var refreshedCount = refreshedSheets.Count;
console.log("   🔍 当前共 " + refreshedCount + " 张表，正在查找新建表...");

for (var si = 1; si <= refreshedCount; si++) {
  var tmpSheet = refreshedSheets.Item(si);
  if (tmpSheet.Name === EXPORT_TABLE_NAME) {
    newSheet = tmpSheet;
    console.log("   ✅ 找到「" + EXPORT_TABLE_NAME + "」(索引: " + si + ")\n");
    break;
  }
}

if (!newSheet) {
  // 尝试直接用名称获取
  try {
    newSheet = Application.Sheets.Item(EXPORT_TABLE_NAME);
    console.log("   ✅ 通过名称获取到表\n");
  } catch (eFindSheet) {
    console.log("   ❌ 无法找到新建的导出表: " + eFindSheet.message);
    console.log("   💡 请手动创建「" + EXPORT_TABLE_NAME + "」表后重试");
    throw new Error("无法获取导出表对象");
  }
}

// ============================================================
//  Step 4: 将数据写入导出表
// ============================================================

console.log("📥 正在写入 " + allRows.length + " 条记录...");

var newView = newSheet.Views(1);

// 逐行写入数据
for (var r = 0; r < allRows.length; r++) {
  var row = allRows[r];

  // RecordRange(行号, 列号), 行号从1开始, 列号从1开始
  // 第1行是已有的空行，从第1行开始写
  // 列顺序: 所属表名(1), SheetId(2), 字段序号(3), 字段名称(4), 字段类型(5), 字段ID(6)

  var rowNum = r + 1;

  try {
    newView.RecordRange(rowNum, 1).Value = row.tableName;
    newView.RecordRange(rowNum, 2).Value = row.sheetId;
    newView.RecordRange(rowNum, 3).Value = row.fieldIndex;
    newView.RecordRange(rowNum, 4).Value = row.fieldName;
    newView.RecordRange(rowNum, 5).Value = row.fieldType;
    newView.RecordRange(rowNum, 6).Value = row.fieldId;
  } catch (writeErr) {
    console.log("   ⚠️ 写入第 " + rowNum + " 行异常: " + writeErr.message);
  }

  // 每 10 条打印一次进度
  if ((r + 1) % 10 === 0 || r === allRows.length - 1) {
    console.log("   📝 已写入 " + (r + 1) + " / " + allRows.length + " 条");
  }
}

// ============================================================
//  Step 5: 输出摘要
// ============================================================

console.log("\n");
console.log("╔══════════════════════════════════════════════════════╗");
console.log("║              📊 导出摘要                            ║");
console.log("╚══════════════════════════════════════════════════════╝");
console.log("  导出表名: " + EXPORT_TABLE_NAME);
console.log("  总记录数: " + allRows.length + " 条");

// 按表名统计
var tableStats = {};
for (var s = 0; s < allRows.length; s++) {
  var tn = allRows[s].tableName;
  if (!tableStats[tn]) tableStats[tn] = 0;
  tableStats[tn]++;
}

console.log("\n  各表字段数:");
var tableNames = Object.keys(tableStats);
for (var sn = 0; sn < tableNames.length; sn++) {
  console.log("    " + (sn + 1) + ". " + tableNames[sn] + " → " + tableStats[tableNames[sn]] + " 个字段");
}

console.log("\n🎉 表结构已导出到「" + EXPORT_TABLE_NAME + "」表中!");
console.log("💡 请切换到该表查看完整数据，可直接复制或筛选使用。");
