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, checkLog } 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`;
    const isSingle = uri == TABLE.PAYMENT.uri;
    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 fn = task.getFileName();
        const isJson = fn.endsWith('.json');
        if (!isJson) fn = fn.replace(/\.\w+$/g, ".zip");
        if ((isSingle || isJson) && !await checkLog(fn)) {
            console.log(`${pf} skip2`);
            continue;
        }

        let data = await task.send();
        if (data === true || data === false) {
            console.log(`${pf} skip3`);
            continue;
        }

        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);
                console.log(data);
            }
        } else {
            if (isSingle) {
                const zip = await createZip([data], [fn]);
                const form = new FormData();
                form.append("zipfile", zip, fn);
                await uploadFile(fn, form);
            } else {
                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, { isCheck: true });
        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;
    });
}
