import {sendChromeAPIMessage} from '@/api/chromeApi'

export async function createFolderApi(folderArr, mallId) {
    let res1 = await queryAllFolders(mallId)
    return await createFolder(res1, folderArr, 0, mallId)
}

async function createFolder(folders, folderArr, index, mallId) {
    for (let i = 0; i < folders.childFolderList.length; i++) {
        if (folders.childFolderList[i].folderName == folderArr[index]) {
            if (folders.childFolderList[i].childFolderList.length == 0) {
                if (index == (folderArr.length - 1)) {
                    return folders.childFolderList[i].folderId
                } else {
                    return await createFolderFunc(folders.childFolderList[i].folderId, folderArr, ++index, mallId)
                }
            } else {
                return createFolder(folders.childFolderList[i], folderArr, ++index, mallId)
            }
        }
    }
    return await createFolderFunc(folders.folderId, folderArr, index, mallId)
}

async function createFolderFunc(folderId, folderArr, index, mallId) {
    let tempFolderId = folderId
    await sendChromeAPIMessage({
        url: 'marvel-mms/cn/api/kiana/gmp/bg/phoenix/api/material/create-folder',
        needMallId: true,
        mallId: mallId,
        data: {
            parentId: tempFolderId,
            folderName: folderArr[index]
        }})
    let res1 = await queryAllFolders(mallId)

    return await createFolder(res1, folderArr, 0, mallId)
}

async function queryAllFolders(mallId) {
    let folders = await sendChromeAPIMessage({
        url: 'marvel-mms/cn/api/kiana/gmp/bg/phoenix/api/material/query-folders',
        needMallId: true,
        mallId: mallId,
        data: {}})
    
    return folders.result.rootFolder
}