import {mongoConfig} from '../config/dbConfig'
import * as mongodb from 'mongodb';
const {Db, MongoClient, ObjectId} = mongodb;

let db: mongodb.Db | null = null;
let client: mongodb.MongoClient | null = null;

async function connectToMongo() {
    if (db) {
        return db;
    }
    try {
        console.log('开始初始化MongoDB');
        const url = `mongodb://${mongoConfig.url}:${mongoConfig.port}`;
        console.log('MongoDB连接URL:', url);
        
        // MongoDB 2.x 使用旧式连接方式
        client = await MongoClient.connect(url);
        
        db = client.db('sdk');
        console.log('MongoDB连接成功');
        return db;
    } catch (error) {
        console.error('连接到MongoDB失败:', error);
        throw error;
    }
}

// 获取某一个数据库连接
async function getDb(): Promise<mongodb.Db> {
    if (!db) {
        db = await connectToMongo();
    }
    return db;
}

// 查询某一个db的集合
async function getCollection(collectionName: string) {
    const database = await getDb();
    return database.collection(collectionName);
}

//关闭连接
async function closeConnection() {
    if (client) {
        await client.close();
        db = null;
        client = null;
        console.log("MongoDB连接已关闭");
    }
}

//通过id和db查询某一个角色信息
async function getRoleInfoById(dbName: string, roleId: string) {
    try {
        if (!client) {
            await connectToMongo();
        }
        const database = client!.db(dbName);
        const collection = database.collection('char');
        const roleInfo = await collection.findOne({roleId: roleId});
        return roleInfo;
    } catch (error) {
        console.error('查询角色信息失败:', error);
        return null;
    }
}

//查询工会信息
async function getGuildInfoById(dbName: string, uuid: string) {
    try {
        if (!client) {
            await connectToMongo();
        }
        const database = client!.db(dbName);
        const collection = database.collection('guild');
        const guildInfo = await collection.findOne({_id: new ObjectId(uuid)});
        return guildInfo;
    } catch (error) {
        console.error('查询工会信息失败:', error);
        return null;
    }
}

//根据用户ID和服务器ID查询角色信息
async function getRoleInfoByUidAndServerId(newUniqueTag: string, dbName: string) {
    try {
        if (!client) {
            await connectToMongo();
        }
        const database = client!.db(dbName);
        const collection = database.collection('char');
        
        // 查询该用户在该服务器上的角色信息
        const roleInfo = await collection.findOne({newUniqueTag: newUniqueTag});
        
        if (roleInfo) {
            return {
                roleName: roleInfo.name || "未知角色",
                roleLevel: roleInfo.lv || 1,
                roleId: roleInfo.roleId || "",
                head: roleInfo.head || "",
            };
        }
        
        return null;
    } catch (error) {
        console.error('查询角色信息失败:', error);
        return null;
    }
}

/**
 * 向玩家发送系统邮件（直接写入 MongoDB）
 * @param dbName    游戏服数据库名，如 "ckwy_fy_S001"
 * @param newUniqueTag  玩家唯一标识，格式 "channelId|serverId|account"
 * @param title     邮件标题
 * @param content   邮件内容
 * @param items     道具列表，格式 [[itemId, count], ...]
 * @returns 发送是否成功
 */
async function insertMailToPlayer(
    dbName: string,
    newUniqueTag: string,
    title: string,
    content: string,
    items: Array<[number, number]>
): Promise<boolean> {
    try {
        if (!client) {
            await connectToMongo();
        }
        const database = client!.db(dbName);

        // 通过 newUniqueTag 找到角色，取出 _id
        const charCol = database.collection('char');
        const charDoc = await charCol.findOne({ newUniqueTag });
        if (!charDoc) {
            console.warn(`[insertMailToPlayer] 找不到角色 newUniqueTag=${newUniqueTag} dbName=${dbName}`);
            return false;
        }

        const receiverUuid = charDoc._id.toString();

        const mailDoc: any = {
            type: 1,                    // SYSTEM
            receiverUuid,
            title,
            senderName: title,
            head: 0,
            content,
            time: Math.floor(Date.now() / 1000),
        };

        if (items && items.length > 0) {
            mailDoc.items = items;
            mailDoc.flag = 1;           // 有道具未领取
        } else {
            mailDoc.get = 1;            // 无道具，直接已读
        }

        const mailCol = database.collection('mail');
        await mailCol.insertOne(mailDoc);
        console.log(`[insertMailToPlayer] 邮件发送成功 receiverUuid=${receiverUuid} itemCnt=${items.length}`);
        return true;
    } catch (error) {
        console.error('[insertMailToPlayer] 发送邮件失败:', error);
        return false;
    }
}

/**
 * 批量查询某用户在多个区服的角色信息
 * @param serverList  已加入区服列表，每项包含 { server_id, db_name, name (区服名) }
 * @param tag         渠道标识（用于拼 newUniqueTag）
 * @param uid         用户账号
 */
async function getRoleListByUserId(
    serverList: Array<{ server_id: string; db_name: string; name: string }>,
    tag: number | string,
    uid: string
): Promise<Array<{
    roleId: string;
    roleName: string;
    roleLevel: number;
    zhandouli: number;
    serverName: string;
    serverId: string;
    createTime: number;
}>> {
    const results: Array<{
        roleId: string;
        roleName: string;
        roleLevel: number;
        zhandouli: number;
        serverName: string;
        serverId: string;
        createTime: number;
    }> = [];

    if (!client) {
        await connectToMongo();
    }

    for (const server of serverList) {
        console.log(`[getRoleListByUserId] server:`, JSON.stringify(server));
        if (!server.db_name) {
            console.log(`[getRoleListByUserId] 跳过 server_id=${server.server_id}，db_name 为空`);
            continue;
        }
        try {
            const database = client!.db(server.db_name);
            const collection = database.collection('char');
            const newUniqueTag = `${tag}|${server.server_id}|${uid}`;
            console.log(`[getRoleListByUserId] 查询 db=${server.db_name} newUniqueTag=${newUniqueTag}`);
            // MongoDB v2.x 使用 fields 而非 projection
            const doc = await collection.findOne({ newUniqueTag });
            console.log(`[getRoleListByUserId] 查询结果:`, doc ? `找到 name=${doc.name}` : 'null');
            if (doc) {
                results.push({
                    roleId: doc._id.toString(),
                    roleName: doc.name || '',
                    roleLevel: doc.lv || 0,
                    zhandouli: doc.zhandouli || 0,
                    serverName: server.name || '',
                    serverId: server.server_id,
                    createTime: doc.createTime || 0,
                });
            }
        } catch (error) {
            console.error(`[getRoleListByUserId] 查询区服 ${server.server_id} 异常:`, error);
        }
    }

    return results;
}

export { getDb, getCollection, closeConnection, getRoleInfoById, connectToMongo, getGuildInfoById, getRoleInfoByUidAndServerId, insertMailToPlayer, getRoleListByUserId };