const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { TravelUserList, TravelPostList } = require("./data.js");
importTravelPostAndTravelUser()

DataMap = {
    TravelUser:{},
    TravelPost:{}
}

async function importTravelPostAndTravelUser(){
    // 导入用户数据
    let traveluserList = TravelUserList
    for (let index = 0; index < traveluserList.length; index++) {
        let traveluser = traveluserList[index];
        traveluser = await importObject("TravelUser",traveluser)
    }
    console.log(DataMap["TravelUser"])
    // 导入帖子数据
    let travelpostList = TravelPostList
    for (let index = 0; index < travelpostList.length; index++) {
        let travelpost = travelpostList[index];
        travelpost = await importObject("TravelPost",travelpost)
    }
    console.log(DataMap["TravelPost"])
}

async function importObject(className,data){

    // 查重 srcId 数据源列表中的objectId并非数据库生成的唯一ID，因此需要有一个srcId字段进行记录，并查重
    let query = new CloudQuery(className)
    let srcId = data.objectId
    query.equalTo("srcId",srcId)
    let importObj = await query.first()
    console.log(importObj)

    // 导入
    // 导入前批量处理Pointer类型数据，进行重定向
    Object.keys(data)?.forEach(key=>{
        let field = data[key]
        let srcId = field?.objectId
        if(srcId){ // 是数组字段
            if(key=="user"){
                data[key] = DataMap?.["TravelUser"]?.[srcId]?.toPointer();
            }
        }
    })

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

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

    DataMap[className][srcId] = importObj
}