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

//封装的请求
export const httpApi = async (obj) => {
    return new Promise((resolve) => {
        //发起请求
        request(obj).then(async (response) => {
            resolve(await getResData(response, false))
        }).catch(async (response) => {
            resolve(await getResData(response, true))
        })
    })
}

//处理数据
const getResData = async (response, error = false) => {
    return new Promise((resolve) => {
        const { headers, data, config } = response
        const resData = getObjValue(data)
        const httpData = {
            response,
            res: data,
            data: resData?.data,
            code: resData?.code,
            msg: resData?.msg,
            status: response?.statusCode,
            headers: headers,
            message: getMsgVal(response),
            error: error,
        }
        //处理延迟响应
        if (error) {
            resolve(httpData)
        } else {
            const { startTime, endTime } = config.metadata
            if (config.isDelay) {
                const duration = endTime - startTime
                if (duration < 500) {
                    setTimeout(() => {
                        resolve(httpData)
                    }, 1000 - duration)
                } else {
                    resolve(httpData)
                }
            } else {
                resolve(httpData)
            }
        }
    })
}

//获取msg消息内容
const getMsgVal = ({statusCode, data}) => {
    const { code, msg, error_description } = getObjValue(data)
    if (statusCode === 404 || statusCode === 500 || statusCode === 504) {
        return '服务器异常，请联系管理员！'
    }
    if (code === 404 || code === 500 || code === 504) {
        return '服务器异常，请联系管理员！'
    } else {
        return msg || error_description || '未知错误'
    }
}
