import request from "./index";
import {getObjValue} from "js-fast-way"

//封装的请求
export const httpApi = async (obj, message = true) => {
    return new Promise((resolve) => {
        //发起请求
        request(obj).then((response) => {
            resolve(getResData(response, false));
        }).catch((response) => {
            if (message) {
                window.$message?.error(getMsgVal(response));
            }
            resolve(getResData(response, true));
        })
    });
}

//处理数据
const getResData = (response, error = false) => {
    const headers = getObjValue(response?.headers), resData = getObjValue(response?.data);
    return {
        response,
        res: resData,
        data: resData?.data,
        code: resData?.code,
        msg: resData?.msg,
        status: response?.status,
        disposition: headers['content-disposition'],
        message: getMsgVal(response),
        error: error
    }
}

//获取msg消息内容
const getMsgVal = (response) => {
    const {msg, error_description} = getObjValue(response.data)
    return msg || error_description || '未知错误';
}
