import axios from 'axios'
import { MessageBox, Message } from '@zjlib/element-ui2'
import store from '@/store'
import { getToken } from '@/utils/auth'

export function replaceStringInObject(obj, target, replacement) {
  // 将对象转换为字符串
  let str = JSON.stringify(obj)
  // 替换所有目标字符串为替换字符串
  str = str.replace(new RegExp(target, 'g'), replacement)
  // 将字符串转换回对象
  return JSON.parse(str)
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000 // request timeout
})
const whiteCodes = [200, 201, 4444]

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['x-token'] = store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */ response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (whiteCodes.indexOf(res.code) < 0) {
      if (JSON.parse(response.config.data || '{}')?.returnErr || response.config.params?.returnErr) {
        return Promise.reject(res)
      }

      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 1001) {
        // to re-login
        MessageBox.confirm('登录失效，您可以取消停留在此页面，或重新登录', '登录失效', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.code === 4004) {
        // to re-login
        MessageBox.confirm('账号过期，请前往续费', '账号过期', {
          confirmButtonText: '去续费',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          window.location.href = window.location.href.split('#')[0] + '#/setting/personal?isRenew=true'
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return replaceStringInObject(
        res,
        'https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/',
        `${process.env.VUE_APP_BASE_API}img/get?key=`
      )
      // return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

export function zhapi(add, path) {
  if (add[add.length - 1] == '/' && path[0] == '/') {
    return add + path.substr(1)
  }
  return add + path
}

// post方式导出文件
export function postBlob(data) {
  return new Promise(function (r, j) {
    axios({
      method: 'post',
      url: zhapi(process.env.VUE_APP_BASE_API, data.url), // 后端接口地址
      responseType: 'blob', // bolb格式的请求方式
      headers: {
        'x-token': getToken() // 请求头
      },
      data: data.data // 需要传给后端的请求参数体
    })
      .then(res => {
        const BLOB = res.data
        const fileReader = new FileReader()
        fileReader.readAsDataURL(BLOB) // 对请求返回的文件进行处理
        fileReader.onload = e => {
          const a = document.createElement('a')
          a.download = data.name
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        r()
      })
      .catch(err => {
        console.log(err.message)
        j()
      })
  })
}

// get方式导出文件
export function getBlob(data) {
  return new Promise(function (r, j) {
    axios({
      url: zhapi(process.env.VUE_APP_BASE_API, data.url),
      method: 'get',
      responseType: 'blob',
      params: data.params, // 与post传参方式不同之处
      headers: {
        'x-token': getToken() // 请求头
      }
    })
      .then(res => {
        var blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
        })
        var filename = data.name + '.xlsx'
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = filename // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
        r()
      })
      .catch(err => {
        console.log(err.message)
        j()
      })
  })
}

/**
 * 导入功能
 * @param {*} url
 * @param {*} formData
 * @param {*} id
 */
export function handleImport(url, formData, id = '') {
  return new Promise((resolve, reject) => {
    axios
      .post(zhapi(process.env.VUE_APP_BASE_API, url), formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'x-token': getToken(),
          id
        }
      })
      .then(res => {
        if (res.data.code !== 200) {
          reject(new Error(res.data.message || 'Error'))
          return
        }
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
