const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { UserInfoList, ItemInfoList, UserPreferList } = require("./data");
// 测试CRUD
//testQuery();
async function testQuery() {
    let query = new CloudQuery("UserInfo");
    query.equalTo("name", "湖南渣渣辉2");
    let userInfoList = await query.find();
    console.log("userInfoList", userInfoList);
}

async function main() {
    // 基本的增删改查
    let query = new CloudQuery("UserInfo");
    let userInfoList = await query.find();
    console.log("userInfoList count", userInfoList?.length)

    let newUserInfo = new CloudObject("UserInfo");
    newUserInfo.set({ "name": "Squirral" });
    newUserInfo = await newUserInfo.save(newUserInfo);
    console.log("newUserInfo added", newUserInfo);

    newUserInfo.set({ "name": "Squirral2" });
    newUserInfo = await newUserInfo.save(newUserInfo);
    console.log("newUserInfo updated", newUserInfo);

    await newUserInfo.destory();
    console.log("newUserInfo deleted", newUserInfo);
}
//main()

DataMap = {
    UserInfo: {},
    UserPrefer: {},
    ItemInfo: {}
}

importUserAndPrefer();

async function importUserAndPrefer() {
    //导入用户数据
    let userInfoList = UserInfoList
    for (let index = 0; index < userInfoList.length; index++) {
        let userInfo = userInfoList[index];
        userInfo = await importObject("UserInfo", userInfo, "UserID");
    }
    //导入物品数据
    let itemInfoList = ItemInfoList
    for (let index = 0; index < itemInfoList.length; index++) {
        let itemInfo = itemInfoList[index];
        itemInfo = await importObject("ItemInfo", itemInfo,"ItemID");
    }
    //导入偏好数据
    let userPreferList = UserPreferList
    for (let index = 0; index < userPreferList.length; index++) {
        let userPrefer = userPreferList[index];
        userPrefer = await importObject("UserPrefer", userPrefer,"PreferID");
    }
    console.log(DataMap);
}

async function importObject(className, data, keyID) {
    // 查重：判断导入的数据的data.keyID字段值是否能在数据库对应的keyID字段中查到对应的记录
    // srcId为导入的表的主键字段值
    let query = new CloudQuery(className);
    let keyValue = data[keyID];
    let srcId = keyValue;
    query.equalTo(keyID,srcId)
    let importObj = await query.first()
    console.log(importObj)

    // 导入
    // 导入前批量处理Pointer类型数据，进行重定向
    Object.keys(data).forEach(key => {
        let field = data[key];
        if (field && typeof field === 'object' && field.__type === 'Pointer') {
            // 如果字段是Pointer类型，则进行重定向处理
            if (DataMap && DataMap[field.className] && DataMap[field.className][field.objectId]) {
                data[key] = DataMap[field.className][field.objectId].toPointer();
            }
        }
    });

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

    // 保存或更新data数据，让data中的keyID字段等于srcId的值
    data[keyID] = srcId;
    importObj.set(data);
    importObj = await importObj.save();

    DataMap[className][srcId] = importObj
}