import { sleep, xpath, createZip, fmt0, downloadFile } 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();
    }
};
export async function run(options = {}) {
    const { uri, plan, sn, isDownload = false } = 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;
    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 || task?.task0.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 });
            if (isDownload) {
                const blob = new Blob([data], { "type": "application/json" });
                downloadFile(fn, blob);
            }
        } else {
            fn = fn.replace(/\.\w+$/g, ".zip");
            allData.push(data);
            allFn.push(fn);
        }
        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);
        isDownload && downloadFile(zipFn, zip);
    }
    addLog(`${name} 运行完成`);
}
if (typeof chrome !== 'undefined' && chrome.runtime) {
    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;
    });
}
