import axios, { AxiosRequestConfig, Method } from 'axios'
//import qs from 'qs'
//import cryptojs from 'crypto-js'
//import { addPending, removePending } from './pending'
import service from '@/services'
import { loginStore } from '@/stores'
import { CommonResult, ResultCode } from './interface'

const axiosInstance = axios.create({
    timeout: 30000,
})

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        //addPending(config) //将当前请求添加到列表中
        //请求头签名
        const sign = {
            token: loginStore.getters.token,
            signsecret: 'qz7qWOMXKTMT5JlDs5w4NTPwWeR3xhF1v6wqbZ9cExmP6cc3spvNAp1wJJ1SqRI5',
            timestamp: new Date().getTime(),
        }
        //设置请求头
        config.headers = {
            Authorization: sign.token,
            //Signid: 'eecd3f37625f4501b88e9f0fa14b4b51',
            //Sign: cryptojs.SHA256(qs.stringify(sign)).toString(),
            //Timestamp: sign.timestamp.toString(),
        }
        return config
    },
    (err) => {
        console.error(err)
        return Promise.reject('出现错误，请稍后再试')
    }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
    (res) => {
        //removePending(res) //在请求结束后，移除本次请求
        return res
    },
    (err) => {
        if (err.message === 'Network Error') {
            return Promise.reject('无网络连接，请检查网络')
        }
        if (err.response) {
            const { msg, message } = err.response.data ?? {}
            switch (err.response.status) {
                case 408: {
                    return Promise.reject('请求超时，请稍后再试')
                }
                default: {
                    return Promise.reject(msg || message)
                }
            }
        }
        return Promise.reject('出现错误，请稍后再试')
    }
)

/**
 * Http 通用请求
 * @param url 
 * @param method 
 * @param payload 
 * @param errMsg 
 * @returns 
 */
export async function commonRequest<T>(url: string, method: Method = 'get', payload?: unknown, errMsg?: string) {
    await service.onReady().then((config) => {
        axiosInstance.defaults.baseURL = config.goCommonSearchUrl
    })
    const config: AxiosRequestConfig = {
        url,
        method,
    }
    if (payload instanceof Object) {
        if (['post', 'POST', 'put', 'PUT', 'patch', 'PATCH'].includes(method)) {
            config.data = payload
        } else {
            config.params = payload
        }
    }
    return await axiosInstance(config).then((res) => {
        return res.data as T
    }).catch((err) => {
        const msg = err ?? (errMsg ? '请求失败: ' + errMsg : '请求失败，请稍后重试')
        return Promise.reject(msg)
    })
}

/**
 * Http 请求
 * @param url 
 * @param method 
 * @param payload 
 * @param errMsg 
 * @returns 
 */
export async function httpRequest<T>(url: string, method: Method = 'get', payload?: unknown, errMsg?: string) {
    const res = await commonRequest<CommonResult<T>>(url, method, payload, errMsg)
    switch (res.code) {
        case ResultCode.InvalidToken:
            return Promise.reject('令牌无效')
        case ResultCode.Success:
            return res
        default:
            return Promise.reject(res.msg)
    }
}

/**
 * 获取服务配置地址
 * @param key 
 * @returns 
 */
export function getServiceUrl<K extends keyof typeof service.config>(key: K) {
    return service.config[key]
}