import { httpApi } from 'hc-vue3-ui'
import router from '~src/router/index'
import pinia from '~src/store/init'
import { useAppStore } from '~src/store'
import website from '~src/config'

//初始变量
const store = useAppStore(pinia)

//封装的请求
export const HcApi = async (obj, msg = true) => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
        //处理统一的请求头
        obj.headers = obj.headers ?? {}
        obj.headers['Client-Id'] = obj.headers['Client-Id'] ?? website.clientId
        obj.headers['Tenant-Id'] = obj.headers['Tenant-Id'] ?? store.tenantId
        //发起请求
        const res = await httpApi(obj)
        const { error, code } = res
        if (!error && code === 200) {
            res.isRes = true
            resolve(res)
        } else {
            res.isRes = false
            getResData(res, msg)
            resolve(res)
        }
    })
}

//处理数据
const getResData = ({ code, msg }, isMsg) => {
    if (code === 401) {
        window.$message?.error('身份失效,请重新登录！')
        router.push({ path: '/login' })
    } else if (isMsg) {
        window.$message?.error(msg || '操作失败')
    }
}
