import request from './index'
import { getObjValue } from 'js-fast-way'
import { apiErrorMessage, apiWarningMessage } from '~com/message/index.js'

//封装的请求
export const httpApi = async (obj, message = true) => {
    return new Promise((resolve) => {
        //发起请求
        request(obj).then(async (response) => {
            resolve(await getResData(response, false))
        }).catch(async (response) => {
            if (message) {
                const msg = getMsgVal(response)
                if (msg) window.$message?.error(msg)
            }
            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?.status,
            headers: headers, disposition: getDisposition(headers),
            message: getMsgVal(response), error: error,
        }
        //处理延迟响应
        if (!error) {
            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)
            }
        } else {
            resolve(httpData)
        }
    })
}

//获取msg消息内容
const getMsgVal = (response) => {
    const { code, msg, error_description } = getObjValue(response.data)
    if (code === 404) {
        apiErrorMessage()
        return ''
    } else if (code === 500 || code === 503 || code === 504) {
        apiWarningMessage()
        return ''
    } else {
        return msg || error_description || '未知错误'
    }
}

//响应头中获取content-disposition
const getDisposition = (headers) => {
    try {
        return headers['content-disposition']
    } catch {
        return ''
    }
}
