import request from './request';
import settings from './settings';
import { ElMessage, ElLoading } from 'element-plus';
import qs from 'qs';

async function send_request({ url, method = "POST", params, useQS = false, callback }) {
    if (!url) {
        return false;
    }

    const loading = ElLoading.service({
        lock: true,
        text: '请稍候',
        background: 'rgba(0, 0, 0, 0.7)',
    });

    let opt = {
        baseURL: settings.backendHost,
        url: url,
        method: method,
        withCredentials: true,
    }

    if (method.toUpperCase() == "POST") {
        // POST 请求参数
        opt.headers = { 'content-type': 'application/x-www-form-urlencoded' }
        opt.data = useQS ? qs.stringify(params) : params
    } else if (method.toUpperCase() == "GET") {
        // GET 请求参数
        opt.params = params
    }

    return request(opt).then((response) => {
        let result = response.data;
        // 判断后端是否处理成功
        if (!result.success) {
            ElMessage.error(result?.msg || "服务器错误");
            return null;
        }
        let data = result.data;
        if (typeof (callback) === "function") {
            callback(data);
        }
        return data;
    }).catch((err) => {
        console.error(err);
        ElMessage.error(err.message);
        return false;
    }).finally(() => {
        loading.close();
    })
}

export default send_request;
