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

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

/**
 * 请求拦截器
 */
http.interceptors.request.use(
    (config) => {
        const { getToken } = useLoginStore();
        //removePending(config); //在请求开始前，对之前的请求做检查取消操作
        //addPending(config); //将当前请求添加到列表中

        //请求头签名
        const sign = {
            token: getToken(),
            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('网络异常，请稍后再试');
    }
)

/**
 * 响应拦截器
 */
http.interceptors.response.use(
    (res) => {
        //removePending(res); //在请求结束后，移除本次请求
        return res;
    },
    (err) => {
        if (!axios.isCancel(err)) {
            console.error(err);
        }
        // 异常提示待优化
        return Promise.reject(err.response?.data.msg || '服务器异常，请稍后再试');
    }
)

/**
 * Http请求
 */
export async function httpRequest<T extends { req?: unknown, rsp?: unknown }>(url: string, method: Method, params: HttpRequest<T>) {
    const { success, fail, complete } = params;
    const { goCommonSearchUrl } = service.config;

    const requestConfig: AxiosRequestConfig = {
        url: goCommonSearchUrl + url,
        method: method,
    }

    if (['post', 'POST', 'put', 'PUT', 'patch', 'PATCH'].includes(method)) {
        requestConfig.data = params.data ?? {};
    } else {
        requestConfig.params = params.data ?? {};
    }

    await http(requestConfig).then((res) => {
        const data = res.data as HttpResponse<T['rsp']>;
        switch (data.code) {
            case ResultCode.InvalidToken:
                //退出登录
                //store.dispatch("user/logout", () => {
                //    window.location.reload();
                //});
                return Promise.reject('令牌无效');
            case ResultCode.Success:
                success && success(data);
                return Promise.resolve();
            default:
                fail && fail(data.msg);
                return Promise.reject(data.msg);
        }
    }).catch((err) => {
        fail && fail(err);
        return Promise.reject(err);
    }).finally(() => {
        complete && complete();
    })
}