import axios from 'axios'
import {Loading, Message} from "element-ui";
import {blobValidate, tansParams} from "@/utils/ruoyi";
import errorCode from "@/utils/errorCode";
import { saveAs } from 'file-saver'

const request = axios.create({
	// 从环境变量获取baseURL，如果没有设置则使用默认值
    baseURL: process.env.VUE_APP_BASE_URL || 'https://api.fooder.tw',
	timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(config => {
	config.headers['Content-Type'] = "application/json";
	if(config.headers.isToken){
		config.headers['token'] = localStorage.getItem('token');  // 设置请求头
	}
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        // console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)
let downloadLoadingInstance;
export function download(url, params, filename, config,t) {
    const safeT = t || ((key) => key); // 如果t不存在，直接返回key
    downloadLoadingInstance = Loading.service({ text: 'Loading', spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return request.post(url, params, {
        // transformRequest: [(params) => { return tansParams(params) }],
        params:params,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob',
        ...config
    }).then(async (data) => {
        const isBlob = blobValidate(data);
        if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg);
        }
        downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        Message.error('Error')
        downloadLoadingInstance.close();
    })
}

export default request

