import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/token'
import errorCode from '@/utils/errorCode'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_MicroSrvProxy_API,
  // 超时
  timeout: 60000,
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Tenant'] = process.env.VUE_APP_TENANT
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.request.responseType == 'blob') {
      // 判断是否是文件流
      let fileReader = new FileReader()
      fileReader.readAsText(res.data)
      fileReader.onload = function () {
        try {
          let jsonData = JSON.parse(this.result) // 解析成功说明是普通对象数据，后端返回的是文件上传的错误信息
          res.data = jsonData
          processResponse(res)
          return
        } catch (err) {
          // 解析成对象失败，说明是文件流
          downLoadBlobFile(res)
          return
        }
      }
    }

    // 常规响应处理
    return processResponse(res)
  },
  (error) => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

service.postRequest = function postRequest(basePath, srvName, funcName, data) {
  if (data == undefined) {
    let nullParam = {
      nullparam: 0,
    }
    data = nullParam
  }

  // console.log(basePath, '   basePath   ')
  var base_Path = ''
  if (basePath == process.env.VUE_APP_FOSHAN_PATH) {
    base_Path = process.env.VUE_APP_MicroSrvProxy_foshan_API + basePath
  } else if (basePath == process.env.VUE_APP_AdminPath) {
    base_Path = process.env.VUE_APP_MicroSrvProxy_API + basePath
  } else {
    base_Path = process.env.VUE_APP_MicroSrvProxy_API + basePath
  }
  // console.log(base_Path, '   base_Path   ')
  return service.request({
    url: base_Path,
    method: 'post',
    headers: {
      'Content-Type': 'application/rpcx',
      'X-RPCX-SerializeType': '1',
      'X-RPCX-ServicePath': srvName,
      'X-RPCX-ServiceMethod': funcName,
    },
    data: data,
  })
}
// 发出请求并要求把客户端信息传输给后端（IP和User-Agent）
service.postRequestWithClientInfo = function postRequest(
  basePath,
  srvName,
  funcName,
  data
) {
  if (data == undefined) {
    let nullParam = { nullparam: 0 }
    data = nullParam
  }
  return service.request({
    url: basePath,
    method: 'post',
    headers: {
      'Content-Type': 'application/rpcx',
      'X-RPCX-SerializeType': '1',
      'X-RPCX-ServicePath': srvName,
      'X-RPCX-ServiceMethod': funcName,
      'X-RPCX-Meta': 'need_clint_Info=1',
    },
    data: data,
  })
}

// Excel文件下载（服务端生成文件流）
service.downloadExcel = function downloadExcel(
  basePath,
  srvName,
  funcName,
  data
) {
  if (data == undefined) {
    let nullParam = {
      nullparam: 0,
    }
    data = nullParam
  }
  var base_Path = ''
  if (basePath == process.env.VUE_APP_FOSHAN_PATH) {
    base_Path = process.env.VUE_APP_MicroSrvProxy_foshan_API + basePath
  } else if (basePath == process.env.VUE_APP_AdminPath) {
    base_Path = process.env.VUE_APP_MicroSrvProxy_API + basePath
  }
  service.request({
    url: base_Path,
    method: 'post',
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/rpcx',
      'X-RPCX-SerializeType': '1',
      'X-RPCX-ServicePath': srvName,
      'X-RPCX-ServiceMethod': funcName,
    },
    data: data,
  })
}

function processResponse(res) {
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200
  // 获取错误信息
  const message = errorCode[code] || res.data.msg || errorCode['default']
  if (code === 401) {
    MessageBox.confirm(
      '登录状态已过期，您可以继续留在该页面，或者重新登录',
      '系统提示',
      {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      store.dispatch('user/logout').then(() => {
        if (process.env.SSO_LOGIN) {
          sessionStorage.removeItem('SSO_Token')
          location.href = process.env.SSO_HREF
        } else {
          location.reload()
        }
      })
    })
  } else if (code === 500) {
    Message({
      message: message,
      type: 'error',
    })
    return Promise.reject(new Error(message))
  } else if (code !== 200) {
    Notification.error({
      title: message,
    })
    return Promise.reject('error')
  } else {
    // if (res.data.msg) {
    //   Message({
    //     message: res.data.msg,
    //     type: 'success'
    //   })
    // }
    return res.data
  }
}

function downLoadBlobFile(res, mimeType) {
  if (mimeType == undefined) {
    mimeType = 'application/vnd.ms-excel'
  }
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], {
    type: mimeType,
  })
  // //从response的headers中获取filename, 后端response.setHeader('Content-disposition', 'attachment filename=xxxx.docx') 设置的文件名
  var patt = new RegExp('filename=([^]+\\.[^\\.]+)*')
  var contentDisposition = decodeURI(
    res.headers['content-disposition'] || res.headers['Content-Disposition']
  )
  var result = patt.exec(contentDisposition)
  var fileName = 'data.xlsx'
  if (result != undefined) {
    fileName = result[1]
    fileName = decodeURI(escape(fileName))
    fileName = fileName.replace(/'/g, '')
  }
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

export default service
