import { sleep, xpath, createZip, fmt0 } from "./util.js";
import { addLog } from "./timezone.js";
import { createTasks } from "./base.js";
import { Task } from "./task.js";
import { uploadFile } from "./upload.js";
import { TABLE } from "./conf.js";

// fetch("https://advertising.walmart.com/extend-sso")
async function webJump() {
    if (location.hostname === 'login.account.wal-mart.com') {
        document.querySelector("button").click();
    } else if (location.hostname === 'seller.walmart.com') {
        await sleep(5000);
        xpath(
            '//*[@id="header"]/div[1]/div[1]/div/div[3]/a'
        ).click();
    }
};
async function run(options = {}) {
    const { uri, plan, sn } = options;
    plan.period ||= [fmt0(new Date(), -10), fmt0(new Date(), -1)];
    const [fromDate, toDate] = plan.period;
    const [key, { name }] = Object.entries(TABLE).find((item) => item[1].uri === uri);
    let tasks = await createTasks(uri, fromDate, toDate);
    tasks = sn ? [tasks.at(sn)] : tasks;
    // 在季度周期过滤掉月度任务
    // tasks = tasks.filter((x)=>!x.isMonthly);
    let moment = 2000, idx = 0, len = tasks.length;
    const allData = [], allFn = [], zipFn = `${Task.partnerId} #${key}# ${fromDate}_${toDate}.zip`;
    for (const task of tasks) {
        const pf = `${++idx}/${len}`;
        addLog(`${name} 运行中 ${pf}`);
        if (task.options.isMmonthly && !plan.isMmonthly) {
            console.log(`${pf} skip1`);
            continue;
        }
        console.log(`${pf} start: ${JSON.stringify(task)}`);
        let data = await task.send();
        if (data === true || data === false) {
            console.log(`${pf} skip2`);
            continue;
        }

        let fn = task.getFileName();
        const isJson = fn.endsWith('.json');
        if (isJson) {
            const route = data.__route;
            delete data.__route;
            const headers = { 'Content-Type': 'application/json' }
            await uploadFile(fn, data, { isJson, headers, route });
            // const blob = new Blob([data], { "type": "application/json" });
            // downloadFile(fn, blob);
        } else {
            fn = fn.replace(/\.\w+$/g, ".zip");
            allData.push(data);
            allFn.push(fn);
            // downloadFile(fn, data);
        }
        console.log(`${pf} end: ${fn}`);
        await sleep(moment);
    }
    if (allData.length > 0) {
        const zip = await createZip(allData, allFn);
        const form = new FormData();
        form.append("zipfile", zip, zipFn);
        await uploadFile(zipFn, form);
    }
    addLog(`${name} 运行完成`);
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    (async () => {
        try {
            if (msg.type === "jump") {
                await webJump();
            } else if (msg.type === "run") {
                await run(msg.data);  // 默认
            }
            sendResponse({ status: "ok" });
        } catch (err) {
            sendResponse({ status: "error", error: err.message });
        }
    })();
    return true;
});
