import axios from 'axios'
import errorCode from '@/utils/errorCode'

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

const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.uniEnv.VUE_APP_MicroSrvProxy_API,
  // 超时
  timeout: 60000,
})
// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Tenant'] = process.uniEnv.VUE_APP_TENANT
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (uni.getStorageSync('opms_token') && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + uni.getStorageSync('opms_token') // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.request && 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) => {
    uni.showToast({
      title: error.message,
      icon: 'none',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

service.postRequest = function postRequest(basePath, srvName, funcName, data) {
  if (data == undefined) {
    let nullParam = {
      nullparam: 0,
    }
    data = nullParam
  }
  var base_Path = ''
  if (basePath == process.uniEnv.VUE_APP_FOSHAN_PATH) {
    base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_foshan_API + basePath
  } else if (basePath == process.uniEnv.VUE_APP_AdminPath || process.uniEnv.VUE_APP_ParentPath) {
    base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  } else {
    base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  }
  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,
      SrvEnv: 'dev',
    },
    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.uniEnv.VUE_APP_AdminPath) {
    base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  } else if (basePath == process.uniEnv.VUE_APP_ParentPath) {
    base_Path = process.uniEnv.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,
  })
}

axios.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    var settle = require('axios/lib/core/settle')
    var buildURL = require('axios/lib/helpers/buildURL')
    uni.request({
      method: config.method.toUpperCase(),
      url: buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config,
        }

        settle(resolve, reject, response)
      },
    })
  })
}

function processResponse(res) {
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200
  // 获取错误信息
  const message = errorCode[code] || res.data.msg || errorCode['default']
  if (code === 1010 || code === 1011) {
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 3 * 1000,
      complete: () => {
        uni.reLaunch({
          url: '/pages/login/index',
        })
      },
    })
  } else if (code === 500) {
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 3 * 1000,
    })
    return Promise.reject(new Error(message))
  } else if (code !== 200) {
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 3 * 1000,
    })
    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
