"use strict";
import axios from "axios";
import router from "@/router";
import CryptoJS from './crypto'
import { showLoadingToast,showToast,closeToast } from "vant";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//loading动画白名单
const LOADINGWHITELIST=[
  '/public/wechat_warning',
  '/report/saveReportContent',
  '/report/editDayWeekChapter',
  '/english_report/saveReportContent',
  '/datamanage/edb_info/refresh',
  '/datamanage/edb_info/refresh/all'
]
//l 下载请求列表
const DownloadRequestslist = [
  '/resource/file/download',
]
// 请求数
let LOADINGCOUNT = 0;
let LOADING;

let config = {
  baseURL: import.meta.env.VITE_APP_API_URL,
  timeout: 10*60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    if(!LOADINGWHITELIST.includes(config.url)){
      if (LOADINGCOUNT === 0) {
        LOADING = showLoadingToast ({
          message: "loading...",
          duration: 0,
          forbidClick: true,
        });
      }
      LOADINGCOUNT++;
    }
    
    config.headers.Authorization=localStorage.getItem('token')||''
    if(DownloadRequestslist.includes(config.url)) config.responseType = 'blob'
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    let data
    if(import.meta.env.MODE==='production' && !DownloadRequestslist.includes(config.url)){  // 生产环境解密 --下载数据请求不需要解密
      const headKeyStr=response.headers.dk
      const desKey=CryptoJS.Des3Decrypt(headKeyStr,'JMCqSoUrTAmyNNIRb0TtlrPk') 
      data=JSON.parse(CryptoJS.Des3Decrypt(response.data,desKey));//解密
    }else{
      if(DownloadRequestslist.includes(config.url)) data = response
      else data=response.data
    }
    //关闭loading
    if(!LOADINGWHITELIST.includes(response.config.url)){
      LOADINGCOUNT--;
      if (LOADINGCOUNT === 0) {
        // closeToast()
        LOADING.close()
      }
    }
    

    if(response.status!==200){
      setTimeout(() => {
        showToast('网络异常')
      }, 100);
    }

    if(!data){
      setTimeout(() => {
        showToast('服务器开了个小差')
      }, 100);
    }
    if(data.Ret===408){//token失效
      showToast(data.Msg)
      router.replace('/login')
    }
    if(data.Ret===403){
      setTimeout(() => {
        showToast(data.Msg||'网络异常')
      }, 100);
    }

    return data;
  },
  function (error) {
    //关闭loading
    LOADINGCOUNT--;
    if (LOADINGCOUNT === 0) {
      // closeToast()
      LOADING.close()
    }
    console.log(error);
    setTimeout(() => {
      showToast(error.message)
    }, 300);
    // Do something with response error
    return Promise.reject(error);
  }
);

/**
 * 导出get请求方法
 * @url 请求地址
 * @params get请求参数
 */
export const get = (url, params) => {
  return _axios.get(url, { params });
};

/**
 * 导出post请求方法
 * @url 请求地址
 * @params post请求参数
 */
export const post = (url, params) => {
  return _axios.post(url, params);
};
