import { defineNuxtPlugin } from '#app'
import axios from 'axios'
import { getToken } from '@/store/useCookieStore'

export default defineNuxtPlugin(() => {

    let Url = {
        //正式环境
        // webUrl: 'https://flzxw.bjzxtw.org.cn', //接口地址
        // CwebUrl: 'nw.nfcpgx.org.cn' //页面地址
        //pre环境
        webUrl: 'https://apipre1.bjzxtw.org.cn', //pre接口地址
        CwebUrl: 'pre.nfcpgx.org.cn' //页面地址
    }

    const service = axios.create({
        baseURL: Url.webUrl
    });

    // 请求拦截器
    service.interceptors.request.use(config => {
        // console.log("请求拦截器",config);
        // 从cookie中获取数据
        const token = getToken()
        // const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3ZWIiLCJ1aWQiOjIwMywidXNlcl9uYW1lIjoiMTM1MjAxNzU4MzEiLCJtb2JpbGUiOiIxMzUyMDE3NTgzMSIsImVtYWlsIjoiIiwibGV2ZWxfaWQiOjAsInR5cGVfaWQiOjEwMDAwLCJtZXRhZGF0YSI6eyJ1c2VyX2lkIjoyMDN9LCJqd3Rfc2NlbmUiOiJkZWZhdWx0IiwianRpIjoiZGVmYXVsdF82OGNjZTVjY2YzYjk3NC44NTA1MTQzMiIsImlhdCI6MTc1ODI1ODYzNiwibmJmIjoxNzU4MjU4NjM2LCJleHAiOjE3NTgzNDUwMzZ9.tszeUAIHXwH1c8Cz8Sbk0bXB6--bWPri_1Xj5bSraD0"
        
        if (token) {
            config.headers.token = token;
        }

        config.headers.Userurl = Url.CwebUrl;
        return config;
    }, error => {
        console.log(error)
        return Promise.reject(error);
    });

    // 响应拦截器
    service.interceptors.response.use(response => {
        if (response.status >= 200 && response.status <= 210) {
            return response.data;
        } else if (response.status == 404) {
            console.error(response.data.errmsg);
        } else {

        }
    },
        error => {
            console.log('err' + error);
        })

    return {
        provide: {
            axios: service
        }
    }
});

