const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { UserProfileList, UserInputList,AIRecommendationList, PerferList } = require("./data");
importData()

DataMap = {
    UserProfile:{},
    UserInput:{},
    AIRecommendation:{},
    PerferList:{}
}

async function importData(){
    // 导入用户数据
     //let userProfileList = UserProfileList
     //for (let index = 0; index < userProfileList.length; index++) {
         //let userProfile = userProfileList[index];
        // userProfile = await importObject("UserProfile",userProfile)
     //}
     //导入用户输入数据
    //  let userInputList = UserInputList
    //  for (let index = 0; index < userInputList.length; index++) {
    //      let userInput = userInputList[index];
    //      userInput = await importObject("UserInput",userInput)
    //  }
     //导入AI生成数据
    //  let aiRecommendationList = AIRecommendationList
    //  for (let index = 0; index < aiRecommendationList.length; index++) {
    //      let aiRecommendation = aiRecommendationList[index];
    //      aiRecommendation = await importObject("AIRecommendation",aiRecommendation)
    //  }
    //导入偏好数据
      let perferList = PerferList
     for (let index = 0; index < perferList.length; index++) {
          let perfer = perferList[index];
          perfer = await importObject("Perfer",perfer)
      }


     console.log(DataMap)
}

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()
    

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

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

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

    //DataMap[className][srcId] = importObj
}