const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { DepartList, DoctorList } = require("./data");
inportDapartAndDoctor()

DataMap = {
    Doctor:{},
    Department:{}
}

async function inportDapartAndDoctor(){
    // 导入科室数据
    let departList = DepartList
    for (let index = 0; index < departList.length; index++) {
        let depart = departList[index];
        depart = await importObject("Department",depart)
    }
    // 导入医生数据
    let doctorList = DoctorList
    for (let index = 0; index < doctorList.length; index++) {
        let doctor = doctorList[index];
        doctor = await importObject("Doctor",doctor)
    }
    // console.log(DataMap["Doctor"])
}

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=="depart"){
                data[key] = DataMap?.["Department"]?.[srcId]?.toPointer();
            }
        }
    })

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

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

    DataMap[className][srcId] = importObj
}