/* eslint-disable */
import axios from 'axios'
import store from '@/store'
import qs from 'qs'
import {tansParams} from '@/store/common.js'
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) => {
    if (config.method === "post" && !config.notQs) {
      console.log(config)
      config.data = qs.stringify(config.data);
      // config.data = 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' + store.state.indexIdentity)

    //
    config.headers.token = token
    if (token) config.headers.authorization = token;
    return config;
  },
  (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 registerEmailCode = 'web/code/registerEmailCode';
      const passwordEmailCode = 'web/code/passwordEmailCode';
      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(registerEmailCode) != -1 ||
        config.url.indexOf(passwordEmailCode) != -1 ||
        config.url.indexOf(changePassCode) != -1 ||
        config.url.indexOf(passwordCode) != -1 ||
        config.url.indexOf(loginOut) != -1
      ) {
        return config
      }

      const token = localStorage.getItem('index-token' + store.state.indexIdentity)

      if (token) {
        // console.log(token,'11')
        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) => {
      // console.log(res, '11111')
      // console.log(res.data.code, 'res.data.code')
      if (res.data.code == 400034 ||
        res.data.code == 400035 ||
        // res.data.code == 400001 ||
        res.data.code == 400002 ||
        res.data.code == 400003) {

        router.push({
          path: '/' + store.state.indexIdentity,

        })
        Notification({
          message: res.data.message,
          duration: 1000,

        });
        return
      }
      if (res.data.code == 400023) {
        console.log(res)
        // console.log(store.state.indexIdentity, 'store.state.indexIdentity')
        let code = store.state.indexIdentity;
        let isLogout = res.config.url =='/web/auth/loginOut';
        window.localStorage.removeItem("doubt_code" + code);
        window.localStorage.removeItem("doubt_info" + code);
        window.localStorage.removeItem("doubt_check" + code);
        window.localStorage.removeItem("index-token" + code);
        window.localStorage.removeItem("phone" + code);
        window.localStorage.removeItem("camp_name" + code);
        window.localStorage.removeItem("system_color" + code);
        window.localStorage.removeItem("system_logo" + code);
        window.localStorage.removeItem("has_amount" + code);
        window.localStorage.removeItem("campsite_id" + code);
        window.localStorage.removeItem("order_no" + code);
        window.localStorage.removeItem("campindex_type" + code);
        window.localStorage.removeItem("bk_pic" + code);
        window.localStorage.removeItem("examine_status" + code);
        window.localStorage.removeItem("examine_reason" + code);
        window.localStorage.removeItem(
          "sign_up_file_18355151517" +
            window.localStorage.getItem("phone" + code) +
            code
        );
        window.localStorage.removeItem("schoolName" + code);
        window.localStorage.removeItem("restet_code_time" + code);
        window.localStorage.removeItem("camp_statement" + code)
        window.localStorage.removeItem("transfer_account" + code);
        window.localStorage.removeItem("payee" + code);
        window.localStorage.removeItem("bank_first" + code);
        window.localStorage.removeItem("bank_idcard" + code);
        window.localStorage.removeItem(
          "bank_info" + window.localStorage.getItem("phone" + code) + code
        );
        router.push({
          path: '/' + store.state.indexIdentity,
        })
        if(!isLogout){
          Notification({
            message: res.data.message,
            duration: 3000,
          });
        }
        return
      }
      if (res.data.code == 400003) {
        let code = this.$store.state.indexIdentity;
        window.localStorage.removeItem("doubt_code" + code);
        window.localStorage.removeItem("doubt_info" + code);
        window.localStorage.removeItem("doubt_check" + code);
        window.localStorage.removeItem("index-token" + code);
        window.localStorage.removeItem("phone" + code);
        window.localStorage.removeItem("camp_name" + code);
        window.localStorage.removeItem("system_color" + code);
        window.localStorage.removeItem("system_logo" + code);
        window.localStorage.removeItem("has_amount" + code);
        window.localStorage.removeItem("campsite_id" + code);
        window.localStorage.removeItem("order_no" + code);
        window.localStorage.removeItem("campindex_type" + code);
        window.localStorage.removeItem("bk_pic" + code);
        window.localStorage.removeItem("examine_status" + code);
        window.localStorage.removeItem("examine_reason" + code);
        window.localStorage.removeItem(
          "sign_up_file_18355151517" +
            window.localStorage.getItem("phone" + code) +
            code
        );
        window.localStorage.removeItem("schoolName" + code);
        window.localStorage.removeItem("transfer_account" + code);
        window.localStorage.removeItem("payee" + code);
        window.localStorage.removeItem("bank_first" + code);
        window.localStorage.removeItem("bank_idcard" + code);
        window.localStorage.removeItem(
          "bank_info" + window.localStorage.getItem("phone" + code) + code
        );
        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 == 40068

      // ) {
      //   store.state.showDialog = true
      //   store.state.dialogType = 1
      // }
      loadingInstance && loadingInstance.close()
      setTimeout(() => {
        allowRequest(reqList, res.config.url)
      }, 1000)
      return res
    },
    (error) => {
      console.log(error, 'err')
      // console.log(error.response.status, '5555')
      Message.closeAll()
      if (error.response.status === 404) {
        // return this.$message.error("营地报名已结束")
        // 未登录
        Notification({
          message: "营地报名已关闭",
          duration: 3000,
          // 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 download(url, params, filename) {
  console.log(url, params, filename)
  return instance.post(url, params, {
      transformRequest: [
        params => {
          return tansParams(params);
        }
      ],
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      responseType: "blob"
    })
    .then(data => {
      const content = data;
      console.log(content)
      const blob = new Blob([content]);
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a");
        elink.download = filename;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, filename);
      }
    })
    .catch(r => {
      console.error(r);
    });
}
// 合并多个请求
export function allRequest(arrRequest) {
  return axios.all(arrRequest)
}
