const { CloudQuery, CloudObject } = require("../lib/ncloud");
const { QuestionnaireResultList, QuestionnaireList, QuestionList, OptionList, UserInterestProfileList } = require("./data");

importData();

let DataMap = {
    QuestionnaireResult: {},
    Questionnaire: {},
    Question: {},
    Option: {},
    UserInterestProfile: {}
}

async function importData() {
    // 导入问卷结果数据
    let questionnaireResultList = QuestionnaireResultList;
    for (let index = 0; index < questionnaireResultList.length; index++) {
        let result = questionnaireResultList[index];
        result = await importObject("QuestionnaireResult", result);
    }

    // 导入问卷数据
    let questionnaireList = QuestionnaireList;
    for (let index = 0; index < questionnaireList.length; index++) {
        let questionnaire = questionnaireList[index];
        questionnaire = await importObject("Questionnaire", questionnaire);
    }

    // 导入问题数据
    let questionList = QuestionList;
    for (let index = 0; index < questionList.length; index++) {
        let question = questionList[index];
        question = await importObject("Question", question);
    }

    // 导入选项数据
    let optionList = OptionList;
    for (let index = 0; index < optionList.length; index++) {
        let option = optionList[index];
        option = await importObject("Option", option);
    }

    // 导入用户兴趣画像数据
    let userInterestProfileList = UserInterestProfileList;
    for (let index = 0; index < userInterestProfileList.length; index++) {
        let profile = userInterestProfileList[index];
        profile = await importObject("UserInterestProfile", profile);
    }

    // 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();
    console.log(importObj);

    // 导入前批量处理 Pointer 类型数据，进行重定向
    Object.keys(data)?.forEach(key => {
        let field = data[key];
        let srcId = field?.objectId;
        if (srcId) { // 是 Pointer 类型
            if (key === "userId" || key === "questionnaireId" || key === "questionId") {
                data[key] = DataMap?.[key.replace("Id", "")]?.[srcId]?.toPointer();
            } else if (Array.isArray(field)) {
                data[key] = field.map(item => {
                    return DataMap?.[item.className]?.[item.objectId]?.toPointer();
                });
            }
        }
    });
    // 若未添加，则创建新对象并保存
    if (!importObj?.id) {
        importObj = new CloudObject(className);
    }

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

    DataMap[className][srcId] = importObj;
}


/// 展示当前问卷内的问题及其选项
async function displayQuestionnaireDetails(questionnaireId) {
    // 查询问卷
    let questionnaireQuery = new CloudQuery("Questionnaire");
    questionnaireQuery.equalTo("objectId", questionnaireId);
    let questionnaire = await questionnaireQuery.first();

    // 检查问卷是否存在
    if (!questionnaire) {
        console.log("问卷未找到，无法展示问题和选项。");
        return;
    }

    console.log(`问卷标题: ${questionnaire.title}`);
    console.log(`问卷状态: ${questionnaire.status}`);
    console.log("问题列表:");

    // 查询问题
    let questionQuery = new CloudQuery("Question");
    questionQuery.equalTo("questionnaireId", {
        "__type": "Pointer",
        "className": "Questionnaire",
        "objectId": questionnaireId
    });
    let questions = await questionQuery.find();

    // 检查是否有问题
    if (questions.length === 0) {
        console.log("当前问卷没有问题。");
        return;
    }

    // 遍历问题并查询选项
    for (let question of questions) {
        // 检查问题是否存在
        if (!question) {
            console.log("问题未找到，无法展示选项。");
            continue; // 跳过当前循环，继续下一个问题
        }

        console.log(`  问题: ${question.questionText}`);

        // 查询选项
        let optionQuery = new CloudQuery("Option");
        optionQuery.equalTo("questionId", {
            "__type": "Pointer",
            "className": "Question",
            "objectId": question.objectId
        });
        let options = await optionQuery.find();

        // 输出选项
        console.log("  选项:");
        if (options.length === 0) {
            console.log("    - 此问题没有选项。");
        } else {
            for (let option of options) {
                console.log(`    - ${option.optionText} (已选: ${option.isSelected})`);
            }
        }
        console.log(""); // 添加空行以便于阅读
    }
}

// 示例调用
displayQuestionnaireDetails("jbg6EYXk3G");