import axios from 'axios'
import store from '@/store'
import Qs from 'qs'
// import secret from '@/utils/secret.js'
import {
  getToken,
  removeToken
} from '@/utils/auth'
// 基本请求地址
// 使用配置代理模式
var baseURL = '/api56'
// if (process.env.VUE_APP_MODE == 'development') {
//   baseURL = process.env.VUE_APP_BASE_API
// }
import { set } from 'lodash'
import { Format } from "@fujica/utils"
// 不使用代理配置
// var baseURL = process.env.VUE_APP_BASE_API
// baseURL = 'http://pre-fsmanager.fujica.com.cn/api56/' //pre环境
//baseURL = 'http://master-test.fujica.com.cn:30062/api56/' //测试环境
// const baseURL = 'http://office.wookitech.com/api/v1' // 线上地址
// baseURL = 'https://fsmanager.fujica.com.cn/api56/' // 正式环境
// const baseURL = 'http://platform4.wookitech.com/api/v1' // platform4
//  baseURL = 'http://uat-fsmanager.fujica.com.cn/api56/' // uat

// const baseURL = 'http://office.wookitech.com/api/v1' // 线上地址
// const baseURL = 'http://platform4.wookitech.com/api/v1' // platform4
// const baseURL = 'http://172.16.11.200:8081' //

// create an axios instance
const service = axios.create({
  baseURL: baseURL, // url = base url + request url process.env.VUE_APP_BASE_API
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
  paramsSerializer: function(params) { // 序列化请求参数，避免get请求参数出现&,空格等识别错误的问题
    return Qs.stringify(params, { arrayFormat: 'brackets' })
  }
})

service.baseURL = baseURL // 传入对象

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['platform'] = 1 // 平台标识

    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['token'] = getToken()
    }

    /* 金额数据统一处理 */
    if (config.money?.length && (config.method == 'post' || config.method == 'put')) {
      if (config.data && Object.prototype.toString.call(config.data) === '[object Object]') {
        for (const key in config.data) {
          if (config.money.includes(key)) { // 需要转换的键
            set(config.data, key, parseInt(Format.money(config.data[key],{ fen: true })))
          }
        }
      }
    }

    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 => {
    // 用于导出取文件header里面的文件名 verifyid是登录的验证码
    if (response.data instanceof Blob && (response.data.type == 'application/vnd.ms-excel'||response.data.type == 'application/octet-stream' || response.headers.verifyid)) {
      return response
    }
    const res = response.data
    if (res.success) { // post请求成功时提示，toast字段为false时,不提示
      var succesFlag = response.config.toast == false ? response.config.toast : true
      if (response.config.method != 'get' && succesFlag) {
        ELEMENT.Message({
          message: res.msg || "操作成功",
          offset:60,
          type: 'success',
          duration: 3 * 1000
        })
      }
    }
    if (res.success == false) { // 请求失败时提示，errtoast字段为false时,不提示
      var errorFlag = response.config.errtoast == false ? response.config.errtoast : true
      if (errorFlag) {
        var msg = res.data && typeof res.data === 'string' ? res.data : res.msg
        ELEMENT.Message({
          message: msg || "操作失败",
          type: 'error',
          offset:60,
          duration: 3 * 1000
        })
      }
    }
    /* 金额数据统一处理 */
    if (response.config.money?.length) {
      const singleTransfer = (obj) => {
        for (const key in obj) {
          if (response.config.money.includes(key)) { // 需要转换的键
            set(obj, key, Format.money(obj[key], { yuan: true }))
          }
        }
      }
      if (res.data && Object.prototype.toString.call(res.data) === '[object Object]') {
        singleTransfer(res.data)
        if (res.data.records) {
          res.data.records.forEach(item => singleTransfer(item))
        }
      }
    }
    return res
  },
  error => {
    // http请求状态
    let {
      message
    } = error
    if (message) {
      if (message == 'Network Error') {
        message = '网络连接异常'
      } else if (message.includes('timeout')) {
        message = '系统接口请求超时'
      } else if (message.includes('Request failed with status code')) {
        var status = message.substr(message.length - 3)
        switch (status) {
          // 没有权限
          // eslint-disable-next-line no-lone-blocks
          case '401':
          {
            // eslint-disable-next-line no-mixed-spaces-and-tabs
            removeToken() // 清除token
            // eslint-disable-next-line no-mixed-spaces-and-tabs
            message = '您的登录状态已过期，请重新登录'
            setTimeout(function() {
              localStorage.removeItem('manager-userNameInfo')
              localStorage.removeItem('parkInfo')
              location.href = '/' // 跳转登录页
            }, 1000)
            break
          }
          default:
          {
            var msg = error.response.data.msg || error.response.data.message
            if (msg) {
              message = msg
            } else {
              message = '系统接口' + status + '异常'
            }
          }
        }
      }
      ELEMENT.Message({
        message: message,
        type: 'error',
        offset:60,
        duration: 3 * 1000
      })
    }
  }
)

export default service
