/* eslint-disable */
import axios from 'axios'
import store from '@/store'
import {
  SERVER_URL,
  DEVELOPMENT_SERVER_URL
} from '@/config/server'

import {
  Notification,
  Message,
  Loading
} from 'element-ui'
import router from '@/router'

const instance = axios.create({
  baseURL: SERVER_URL,
  timeout: 60000,
  method: "post",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  withCredentials: false,
 
});

instance.interceptors.request.use(
  (config) => {
    console.log(config, '111');
    if (config.method === "post" && !config.notQs) {
      config.data = qs.stringify(config.data);
    }
    if (config.url.indexOf(SERVER_URL) === -1) {
      console.log("upload");
      config.headers["Content-Type"] = "multipart/form-data";
    } else {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    }
    // 调用接口请求添加token认证信息
    // let token = localStorage.getItem("index-token");
    const token = localStorage.getItem('index-token')

    // 
    config.headers.token = token
    if (token) config.headers.authorization = token;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// instance.interceptors.response.use(
//   (response) => {
//     return response.data;
//   },
//   (error) => {
//     return Promise.reject(error);
//   }
// );

export default instance;

// 正在进行中的请求列表
const reqList = []

/**
 * 阻止重复请求
 * @param {array} reqList - 请求缓存列表
 * @param {string} url - 当前请求地址
 * @param {function} cancel - 请求中断函数
 * @param {string} errorMessage - 请求中断时需要显示的错误信息
 */
const stopRepeatRequest = function (reqList, url, cancel, errorMessage) {
  const errorMsg = errorMessage || ''
  for (let i = 0; i < reqList.length; i++) {
    if (reqList[i] === url) {
      // cancel(errorMsg);
      return
    }
  }
  reqList.push(url)
}
/**
 * 允许某个请求可以继续进行
 * @param {array} reqList 全部请求列表
 * @param {string} url 请求地址
 */
const allowRequest = function (reqList, url) {
  for (let i = 0; i < reqList.length; i++) {
    if (reqList[i] === url) {
      reqList.splice(i, 1)
      break
    }
  }
}
let loadingInstance = null

export function request(config) {
  const instance = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ?
      DEVELOPMENT_SERVER_URL : SERVER_URL,
    timeout: 60 * 1000
  })
  instance.interceptors.request.use(
    (config) => {
      const loginUrl = '/web/auth/login';
      const setAccountInfo = '/web/register/setAccountInfo';
      const passMsgOld = '/web/auth/changePassOld';
      const getCam = '/web/auth/getCam';
      const registerCode = '/web/code/registerCode';
      const passwordCode = '/web/code/passwordCode';
      const changePassCode = '/web/auth/changePassCode';
      const loginOut = '/web/auth/loginOut';
      console.log(config)
      if (
        config.url.indexOf(loginUrl) != -1 ||
        config.url.indexOf(setAccountInfo) != -1 ||
        config.url.indexOf(passMsgOld) != -1 ||
        config.url.indexOf(getCam) != -1 ||
        config.url.indexOf(registerCode) != -1 ||
        config.url.indexOf(changePassCode) != -1 ||
        config.url.indexOf(passwordCode) != -1||
        config.url.indexOf(loginOut) != -1
      ) {
        return config
      }
      const token = localStorage.getItem('index-token')
      if (token) {
        // console.log(token)
        config.headers.token = token
      } else {
        window.localStorage.clear()
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          } // 从哪个页面跳转
        })
        const error = new Error('请登录！')
        return Promise.reject(error)
      }

      let cancel
      // 设置cancelToken对象
      config.cancelToken = new axios.CancelToken(function (c) {
        cancel = c
      })
      if (
        config.url.indexOf('/web/config/getUniversity') == -1 &&
        config.url.indexOf('/web/config/getProfession') == -1
      ) {
        // 阻止重复请求。当上个请求未完成时，相同的请求不会进行
        stopRepeatRequest(
          reqList,
          config.url,
          cancel,
          `${config.url} 请求被中断`
        )
      }

      if (config.hasLoading) {
        const loadingText = config.loadingText ? config.loadingText : '请求中'
        loadingInstance = Loading.service({
          lock: true,
          fullscreen: true,
          text: loadingText,
          // spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.25)'
        })
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    (res) => {
      if (res.data.code == 400003) {
        window.localStorage.clear()
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          } // 从哪个页面跳转
        })
      } else if (
        res.data.code == 400801 ||
        res.data.code == 400910 ||
        res.data.code == 4002132 ||
        res.data.code == 400410 ||
        res.data.code == 401001
      ) {
        store.state.showDialog = true
        store.state.dialogType = 1
      }
      loadingInstance && loadingInstance.close()
      setTimeout(() => {
        allowRequest(reqList, res.config.url)
      }, 1000)
      return res
    },
    (error) => {
      Message.closeAll()
      // if (error.response.status === 401) {
      //   // 未登录
      //   Notification({
      //     message: "身份验证失败，请登录",
      //     duration: 1500,
      //     onClose() {
      //       console.log('error');
      //       router.push("/admin/login");
      //     },
      //   });
      //   return false;
      // }
      if (axios.isCancel(error)) {
        console.log(error.message)
      } else {
        // 增加延迟，相同请求不得在短时间内重复发送
        setTimeout(() => {
          allowRequest(reqList, error.config.url)
        }, 1000)
      }
      loadingInstance && loadingInstance.close()
      return Promise.reject(error)
    }
  )


  return instance(config)
}

/**
 * axios:upload 文件上传方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function upload(url, data = {}) {
  //  console.log(11111)
  return new Promise((resolve, reject) => {
    axios.post(url, data).then(
      (response) => {
        console.log(url)
        // console.log(11111)
        resolve(response);
      },
      (err) => {
        console.log(11111)
        reject(err);
      }
    );
  });
}
// 合并多个请求
export function allRequest(arrRequest) {
  return axios.all(arrRequest)
}
