import { retry } from "./util.js";

async function upload(url, body, headers) {
    console.log(`上传 ${url} ${body}`);
    let response = await fetch(url, {
        method: "POST", body, headers
    });
    console.log(response);
    let data = await response.json();
    if (data.status.toUpperCase() === "OK") {
        console.log(data);
        return true;
    } else {
        throw new Error(`上传失败, ${url}, ${JSON.stringify(data)}`);
    }
}
export async function checkLog(fn, insert = false) {
    const url = "https://walmart.meinuosha.com/index.php/index/index/Getspluginexporttablerecords?accessvalue=Walmart2025PY0307";
    let response = await fetch(url, {
        method: "POST",
        body: JSON.stringify({
            Recordparameter: insert ? "interposition" : "inquire",
            Derivedtablename: fn
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    });
    let data = await response.json();
    console.log(`${fn} ${JSON.stringify(data)}`);
    return data.status === "NO";
}
export async function uploadFile(fn, data, options = {}) {
    const fileURL = "https://walmart.meinuosha.com/index.php/index/index/Loanschedule?accessvalue=Walmart2025PY0307";
    const linkURL = "https://walmart.meinuosha.com/index.php/index/index/url_download_list?accessvalue=Walmart2025PY0307";
    let url;
    if (options.isJson) {
        url = `https://walmart.meinuosha.com/index.php/index/index/${options.route}?accessvalue=Walmart2025PY0307`;
        data = JSON.stringify(data);
    } else {
        url = options.isLink ? linkURL : fileURL;
    }
    if (options.isCheck && !await checkLog(fn)) return;
    const insert = await retry(
        async () => upload(url, data, options.headers),
        { delayMs: 1000 * 10, retries: 10 }
    );
    if (insert) await checkLog(fn, true);
}
