import { api, dataApi } from '@/services/api'
import { request } from 'umi';
import { jm } from './useBase64'
async function useFetch(props: { url: string, method?: 'POST' | 'GET' | 'DELETE' | 'PUT', params?: any, headers?: Headers | string[][] | Record<string, string> | undefined, excelName?: string, newUrl?: string }) {
    let data: any = null
    let { url, method, params, headers, excelName, newUrl } = props
    if (url) {
        request(api + '/refresh', {
            method: 'PUT',
        });
        await fetch(`${newUrl ? newUrl : dataApi}/api` + url, {
            method,
            mode: 'cors',
            headers: headers ? headers : { 'Content-Type': 'application/json;charset=UTF-8', 'Authorization': 'Bearer ' + jm(), },
            body: JSON.stringify(params)
        }).then(async (res: any) => {
            if (params?.download) {
                let name = excelName
                if (params?.pitcher) {
                    name += `_${params?.pitcher}`
                }
                if (params?.channel) {
                    name += `_${params?.channel}`
                }
                if (params?.platform) {
                    name += `_${params?.platform}`
                }
                if (params?.start) {
                    name += `_${params?.start}_${params?.end}`
                }
                if (params?.book) {
                    name += `_${params?.book}`
                }
                if (params?.state) {
                    name += `_${params?.state}`
                }
                if (params?.type || params?.location) {
                    name += `_${params?.type || params?.location}`
                }
                if (params?.date_range) {
                    name += `_近${params?.date_range}天`
                }
                if (params?.order) {
                    name += `_${params?.order}`
                }
                let str = await res.text()
                str = "data:application/csv," + encodeURIComponent(str)
                let downloadElement = document.createElement('a');
                downloadElement.href = str;
                downloadElement.download = `${name}.csv`; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
            } else {
                return res.json()
            }
        }).then(res => { data = res })
    }
    return { ...data }
}

export default useFetch
