// oms/scripts/migrate-total-done-rates.ts

import mongoose, { Schema, Document, Connection } from "mongoose";
import TotalDoneRate, { ITotalDoneRate } from "../models/totalDoneRateModel"; // 导入新的 TotalDoneRate 模型

// --- 数据库配置 ---
// 本地 OMS 数据库的连接字符串
const LOCAL_MONGO_URI = "mongodb://oms:oms123.@localhost:27717/omsdb?authSource=admin";
// 远程旧 CLOGS 数据库的连接字符串
const REMOTE_CLOGS_MONGO_URI = "mongodb://clogs:clogs123.%23%23@localhost:27017/clogs";

// --- 旧数据库 total_done_rate 表的 Schema 和 Model ---
// 接口与新模型的 ITotalDoneRate 相同，因为数据结构是同构的
interface IOldTotalDoneRate extends Document {
  _id: mongoose.Types.ObjectId;
  totalStartCount: number;
  totalDoneCount: number;
  completionRate: number;
}

const oldTotalDoneRateSchema: Schema<IOldTotalDoneRate> = new Schema(
  {
    _id: { type: Schema.Types.ObjectId, required: true },
    totalStartCount: { type: Number, required: true },
    totalDoneCount: { type: Number, required: true },
    completionRate: { type: Number, required: true },
  },
  {
    collection: "total_done_rate", // 指定旧的表名
    versionKey: false,
  }
);

let localConn: Connection | null = null;
let remoteConn: Connection | null = null;

// 定义每次处理的数据量
const BATCH_SIZE = 5000;

/**
 * 迁移函数，执行 total_done_rate 数据割接
 */
async function migrateTotalDoneRates() {
  console.log("[Migration] Starting data migration from clogs.total_done_rate to oms.totaldonerates...");

  try {
    // 1. 建立本地和远程数据库连接
    localConn = await mongoose.createConnection(LOCAL_MONGO_URI);
    console.log("[Migration] Connected to local OMS database.");

    remoteConn = await mongoose.createConnection(REMOTE_CLOGS_MONGO_URI);
    const OldTotalDoneRate = remoteConn.model<IOldTotalDoneRate>("OldTotalDoneRate", oldTotalDoneRateSchema);
    console.log("[Migration] Connected to remote CLOGS database.");

    // 2. 使用游标分批处理数据
    console.log(`[Migration] Processing records in batches of ${BATCH_SIZE}...`);

    let processedCount = 0;
    let successfulInserts = 0;
    let batch: any[] = [];

    // 使用游标查询，不会一次性加载所有数据到内存
    const cursor = OldTotalDoneRate.find({}).lean().cursor();

    // 逐条处理游标中的数据
    for await (const doc of cursor) {
      // 数据结构同构，可以直接推入批次
      batch.push(doc);

      // 如果达到批次大小，则执行批量插入
      if (batch.length >= BATCH_SIZE) {
        try {
          const result = await localConn.model("TotalDoneRate", TotalDoneRate.schema).insertMany(batch, { ordered: false });
          successfulInserts += result.length;
        } catch (error: any) {
          if (error.code === 11000) {
            console.warn("[Migration] Duplicate key error in batch. Attempting individual inserts...");
            // 如果存在重复项，则尝试逐条插入以找出成功的记录
            for (const item of batch) {
              try {
                await localConn.model("TotalDoneRate", TotalDoneRate.schema).create(item);
                successfulInserts++;
              } catch (e: any) {
                if (e.code !== 11000) {
                  console.error(`[Migration] Failed to insert record with _id ${item._id}:`, e.message);
                }
              }
            }
          } else {
            console.error("[Migration] An error occurred during a batch insertion:", error.message);
          }
        }

        processedCount += batch.length;
        console.log(`[Migration] Processed ${processedCount} records. Total successfully inserted: ${successfulInserts}`);

        // 清空批次，准备下一轮
        batch = [];
      }
    }

    // 处理最后一个未满的批次
    if (batch.length > 0) {
      try {
        const result = await localConn.model("TotalDoneRate", TotalDoneRate.schema).insertMany(batch, { ordered: false });
        successfulInserts += result.length;
      } catch (error: any) {
        if (error.code === 11000) {
          console.warn("[Migration] Duplicate key error in final batch. Attempting individual inserts...");
          for (const item of batch) {
            try {
              await localConn.model("TotalDoneRate", TotalDoneRate.schema).create(item);
              successfulInserts++;
            } catch (e: any) {
              if (e.code !== 11000) {
                console.error(`[Migration] Failed to insert record with _id ${item._id}:`, e.message);
              }
            }
          }
        } else {
          console.error("[Migration] An error occurred during the final batch insertion:", error.message);
        }
      }
      processedCount += batch.length;
    }

    console.log(`[Migration] All records processed. Total processed: ${processedCount}. Total successfully inserted: ${successfulInserts}`);
    console.log("[Migration] Data migration completed successfully!");
  } catch (error: any) {
    console.error("[Migration] A critical error occurred. Script will exit:", error);
    throw error;
  } finally {
    // 确保关闭所有连接
    if (localConn) {
      await localConn.close();
      console.log("[Migration] Local connection closed.");
    }
    if (remoteConn) {
      await remoteConn.close();
      console.log("[Migration] Remote connection closed.");
    }
  }
}

// 运行迁移脚本
migrateTotalDoneRates().catch((err) => {
  console.error("[Migration] Script failed to run:", err);
  process.exit(1); // 退出并返回错误码
});
