const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { ChatPartnerList, ChatRecordList } = require("./data");

DataMap = {
    ChatPartner:{},
    ChatRecord:{},
};

// 查询
//async function testQuery(){
    //let query = new CloudQuery("ChatPartner")
    //query.greaterThanAndEqualTo("",)查询条件
    //query.lessThan("",)查询条件
    //let list = await query.find();
    //console.log(list)
//}
//testCRUD()// 测试ChatPartner表的查询

// 增删改查
//async function testCRUD(){
    //let query = new CloudQuery("ChatPartner")
    //let chatpartnerList = await query.find();
    //console.log("chatpartnerList count",chatpartnerList?.length)

    //let newChatPartner = new CloudObject("ChatPartner")
    //newChatPartner.set({"name":"123"})
    
    //newChatPartner = await newChatPartner.save(newChatPartner)
    //console.log("newChatPartner",newChatPartner)

    //await newChatPartner.destory()
    //console.log("newChatPartner 已删除",newChatPartner)
//}
//testQuery()// ChatPartner表基本的增删查改测试

async function inportDapartAndChatPartner(){
    // 导入陪聊师数据
    let chatpartnerList = ChatPartnerList
    for(let index = 0;index < chatpartnerList.length;index++){
        let chatpartner = chatpartnerList[index];
        chatpartner = await importObject("ChatPartner",chatpartner)
    }
    // 导入聊天记录数据
    let chatrecordList = ChatRecordList
    for(let index = 0;index < chatrecordList.length;index++){
        let chatrecord = chatrecordList[index];
        chatrecord = await importObject("ChatRecord",chatrecord)
    }
    console.log(DataMap)
}
inportDapartAndChatPartner()

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=="chatpartner"){
                data[key] = DataMap["ChatPartner"]?.[srcId]?.toPointer();
            }
        }
    });
    // 新对象需要添加
    if(!importObj?.id){
        importObj = new CloudObject(className)
    }
    //保存或更新数据
    data.srcId = srcId;
    importObj.set(data);
    importObj = await importObj.save();

    DataMap[className][srcId] = importObj
}