import axios from 'axios';
import { showToast } from 'vant';

// import router from '@/router/index';
// import { A_COMMON_CLEAR_TOKEN } from '@/stores/constance/constance.common.js';

import * as config from '@/config';
// import { useRoute } from 'vue-router';
// import {proxyUrl} from config.default
// const NODE_ENV = import.meta.env.VITE_APP_ENV;
const baseURL = config.default.proxyUrl;
// axios.defaults.withCredentials = true;

// create an axios instance
const service = axios.create({
  // url = base url + request url
  baseURL: `${baseURL}/api`,
  // withCredentials: true, // send cookies when cross-domain requests
  // request timeout
  timeout: 30000
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    if (!config.headers) {
      config.headers.Accept = 'application/json';
    }
    let plantToken = localStorage.getItem('plantToken');

    const params = new URLSearchParams(new URL(window.location.href).search);
    
    // 如果 token 不存在， 试图尝试让用户输入 token ，然后放入本地 token 内容中
    // 仅限开发环境中
    // if (!plantToken && !import.meta.env.PROD) {
    if (!plantToken && params.get('apptoken')) {
      // console.log(params.get('apptoken'));
      // alert(params.get('apptoken'));
      // plantToken = prompt('token 不存在，请输入 plant token');
      plantToken = params.get('apptoken');
      plantToken && localStorage.setItem('plantToken', plantToken);
    }

    config.headers.Authorization = `${plantToken}`;
    config.headers.Source = 1;
    // if (!config.headers.remoteIp) {
    //   config.baseURL += '/api';
    // }
    // delete config.headers.host;
    config.headers.remoteIp = localStorage.getItem('plantIp') || '127.0.0.1';
    // if (store.state.common.token) {
    //   config.headers['Login-Type'] = 'pc';
    //   config.headers.Authorization = `Bearer ${store.state.common.token}`;
    // }
    return config;
  },
  (error) => Promise.reject(error)
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (
      response.status === 200
      || response.status === 201
      || response.status === 202
      || response.status === 204
    ) {
      if (response.config.method === 'put') {
        // message.success('保存中...');
      }
      return Promise.resolve(response);
    }
    // return Promise.reject(/* new Error(response.message || 'Error') */);
  },
  (error) => {
    // for debug
    // if (error.response.status === 401) {
    //   const query = router.currentRoute.value.query;
    //   //关闭已弹出的所有弹框，防止弹框重叠
    //   // Modal.destroyAll();
    //   store.dispatch(A_COMMON_CLEAR_TOKEN);
    //   window.parent.postMessage(
    //     {
    //       code: '301',
    //       params: {}
    //     },
    //     '*'
    //   );
    //   store.commit('common/M_COMMON_SET_TOKEN_UNAUTHORIZED', false);
    // } else if (error.response.status === 403) {
    //   router.push({
    //     path: '/error/403'
    //   });
    // } else if (error.response.status === 404) {
    //   router.push({
    //     path: '/error/404'
    //   });
    // } else if (error.response.status === 500) {
    //   router.push({
    //     path: '/error/500'
    //   });
    // } else {
    //   // message.error(error.response.data?.message || '服务器错误');
    // }
    if (error.response.data?.message) {
      showToast({
        message: error.response.data?.message
      });
    }

    return Promise.reject(error.response);
  }
);

export default service;
