// import-data.js

const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { DepartList, DoctorList, HotDotList, DrugList, RealDoctorList, IllnessList } = require("./data"); // 确保正确导入所有集合

// 添加所有集合到 DataMap
const DataMap = {
    Doctor: {},
    Department: {},
    HotDot: {},
    Drug: {},
    RealDoctor: {},
    Illness: {},
};

// 开始导入数据
inportDapartAndDoctor();

async function inportDapartAndDoctor() {
    try {
        // 导入药品数据
        // let drugList = DrugList;
        // console.log(`开始导入 Drug 数据，共 ${drugList.length} 条`);
        // for (let index = 0; index < drugList.length; index++) {
        //     let drug = drugList[index];
        //     drug = await importObject("Drug", drug);
        // }

        // 导入疾病数据
        // let illnessList = IllnessList;
        // console.log(`开始导入 Illness 数据，共 ${illnessList.length} 条`);
        // for (let index = 0; index < illnessList.length; index++) {
        //     let illness = illnessList[index];
        //     illness = await importObject("Illness", illness);
        // }

        // 如果需要导入其他数据（科室、医生、热点），可以取消注释以下代码

        // 导入科室数据
        // let departList = DepartList;
        // console.log(`开始导入 Department 数据，共 ${departList.length} 条`);
        // for (let index = 0; index < departList.length; index++) {
        //     let depart = departList[index];
        //     depart = await importObject("Department", depart);
        // }

        // 导入医生数据
        // let doctorList = DoctorList;
        // console.log(`开始导入 Doctor 数据，共 ${doctorList.length} 条`);
        // for (let index = 0; index < doctorList.length; index++) {
        //     let doctor = doctorList[index];
        //     doctor = await importObject("Doctor", doctor);
        // }

        // 导入热点数据
        let hotDotList = HotDotList;
        console.log(`开始导入 HotDot 数据，共 ${hotDotList.length} 条`);
        for (let index = 0; index < hotDotList.length; index++) {
            let hotDot = hotDotList[index];
            hotDot = await importObject("HotDot", hotDot);
        }

        console.log("数据导入完成");
    } catch (error) {
        console.error("导入过程中发生错误:", error);
    }
}

async function importObject(className, data) {
    try {
        // 查重 srcId 数据源中的 objectId 并非数据库生成的唯一ID，因此需要有一个 srcId 字段进行记录，并查重
        let query = new CloudQuery(className);
        let srcId = data.objectId;
        query.equalTo("srcId", srcId);
        let importObj = await query.first();
        console.log(`查重结果 [${className}]:`, importObj ? `已存在 objectId: ${importObj.id}` : "不存在，准备导入");

        // 导入前批量处理 Pointer 类型数据，进行重定向
        Object.keys(data)?.forEach(key => {
            let field = data[key];
            let fieldObjId = field?.objectId;
            if (fieldObjId && typeof field === 'object' && field.__type === 'Pointer') { // 是 Pointer 类型字段
                if (key === "depart") {
                    data[key] = DataMap["Department"]?.[fieldObjId]?.toPointer();
                }
                // 如果有其他 Pointer 类型的字段，可以在这里处理
                if (key === "doctor") {
                    data[key] = DataMap["Doctor"]?.[fieldObjId]?.toPointer();
                }
            }

            // 处理 treats 字段
            if (key === "treats" && Array.isArray(field)) {
                data[key] = field.map(item => ({
                    "__type": "Pointer",
                    "className": "Illness",
                    "objectId": item.objectId
                }));
            }
        });

        // 若未添加，则创建新对象并保存
        if (!importObj?.id) {
            importObj = new CloudObject(className);
        }

        // 保存或更新数据
        data.srcId = srcId;
        importObj.set(data);
        importObj = await importObj.save();

        DataMap[className][srcId] = importObj;
        console.log(`成功导入 ${className} 对象，objectId: ${importObj.id}`);
        return importObj;
    } catch (error) {
        console.error(`导入 ${className} 类别的对象时发生错误:`, error);
    }
}