import Vue from 'vue'
import axios from 'axios'
//import QS from 'qs';
import router from '../router'
import CancelToken from './cancelToken'
function getApi() {
  return window.apiHostSetting.VUE_APP_API_URL
}
function getWsUrl() {
  return window.apiHostSetting.VUE_APP_WS_URL
}
function getStaticPath() {
  return window.apiHostSetting.VUE_APP_BASE_URL
}
function monitorPost(url, options) {
  axios.post(url, options)
}
const baseURL = getApi()
// zimg图片服务器地址
const zImgPath = window.apiHostSetting.VUE_APP_ZIMG_URL
// 文件存储路径地址
const filePath = getStaticPath() + 'upload/erp'
const instance = axios.create({
  baseURL: baseURL+'api/',
  timeout: 5 * 60 * 1000,
  // headers: {
  //   "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  // },
  validateStatus: (status) => status >= 200 && status < 500, // 默认的,
  length: 0,
})
let HTTPNUM = 0
let loading
const cancelToken = new CancelToken()
console.log(cancelToken)
instance.interceptors.request.use(
  (config) => {
    if (config.data && typeof config.data === 'object') {
      const data = config.data
      for (const key in data) {
        if (data[key] === '') {
          data[key] = null
        }
      }
      config.data = data
    }
    if (HTTPNUM === 0) {
      loading = Vue.prototype.$loading({
        background: 'rgba(0, 0, 0, 0.3)',
      })
    }
    HTTPNUM++
    cancelToken.add(config)
    return config
  },
  (error) => {
    cancelToken.clear()
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    cancelToken.remove(res.config)
    HTTPNUM--
    if (HTTPNUM === 0) {
      loading.close()
    }
    if (res.status === 200) {
      if (res.data.code === 401) {
        // token过期
        if (HTTPNUM === 0) {
          Vue.prototype.$message({
            type: 'error',
            message: res.data.message,
          })
          sessionStorage.setItem('active', 'true')
          // router
          //   .replace({
          //     name: 'login',
          //   })
          //   .catch((err) => {
          //     console.log(err)
          //   })
        }
        return Promise.reject(res.data)
      } else if (res.data.code === 402) {
        Vue.prototype.$message({ message: res.data.message, type: 'warning' })
        return Promise.reject(res.data)
      } else if (res.data.code === 403) {
        // token过期
        if (HTTPNUM === 0) {
          Vue.prototype.$message({
            type: 'error',
            message: res.data.message,
          })
          sessionStorage.setItem('active', 'true')
          router
            .replace({
              name: 'login',
            })
            .catch((err) => {
              console.log(err)
            })
        }
        return Promise.reject(res.data)
      } else if (res.data.code === 500) {
        Vue.prototype.$alert(
          '<div style="max-height:500px;overflow:auto">' +
            res.data.message +
            '</div>',
          '错误提示',
          {
            dangerouslyUseHTMLString: true,
          }
        )
        return Promise.reject(res.data)
      } else {
        return Promise.resolve(res)
      }
    } else {
      if (HTTPNUM === 0) {
        switch (res.status) {
          case 400:
            Vue.prototype.$alert('请求参数有误', '提示', {
              confirmButtonText: '确定',
              callback: () => {},
            })
            break
          case 404:
            Vue.prototype.$alert('请求不存在', '提示', {
              confirmButtonText: '确定',
              callback: () => {},
            })
            break
          default:
            break
        }
      }

      return Promise.reject(res)
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    cancelToken.clear()
    HTTPNUM--
    if (HTTPNUM == 0) {
      Vue.prototype.$alert(error.message, 'Error', {
        confirmButtonText: '确定',
        callback: () => {},
      })
      loading.close()
    }
    return Promise.reject(error)
  }
)

function get(url, params) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, { params })
      .then((res) => {
        if (res.status === 200 && res.data) {
          resolve(res.data)
        } else {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
function post(url, params, headers) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, params, headers)
      .then((res) => {
        if (res.status === 200 && res.data) {
          resolve(res.data)
        } else {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
function downloadFile(url, params, headers) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, params, headers)
      .then((res) => {
        if (res.status === 200) {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
function downloadPng(url, params, headers) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, { params }, headers)
      .then((res) => {
        if (res.status === 200) {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
function uploadfile(url, fomData) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, fomData, {
        headers: { 'content-type': 'multipart/form-data' },
      })
      .then((res) => {
        if (res.status === 200 && res.data) {
          resolve(res.data)
        } else {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
function postFormData(url, params) {
  let formdata = new FormData()
  for (const key in params) {
    formdata.append(key, params[key])
  }
  return new Promise((resolve, reject) => {
    instance
      .post(url, formdata, {
        headers: { 'content-type': 'multipart/form-data' },
      })
      .then((res) => {
        if (res.status === 200 && res.data) {
          resolve(res.data)
        } else {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
export {
  get,
  baseURL,
  post,
  downloadFile,
  uploadfile,
  filePath,
  postFormData,
  monitorPost,
  getWsUrl,
  downloadPng,
  zImgPath,
}
