import config from '@/config.js'
import util from '@/util/index.js'
import dayjs from 'dayjs'

const api = window.axios.create({
  timeout: 1000 * 30, // 请求超时
  baseURL: config.baseApi,
})

// request拦截器
api.interceptors.request.use(
  (options) => {
    if (!options.url.includes(`/api/login`)) {
      // 判断请求是否是登录接口
      options.headers.Authorization = `Bearer ` + localStorage.getItem(`token`) // 如果不是登录接口，就给请求头里面设置token
    }
    options.baseURL = config.baseApi
    return options
  },
  (error) => {
    Promise.reject(error)
  }
)
// response拦截器
api.interceptors.response.use(
  (response) => {
    const data = response.data
    if ([`2`, `3`].includes(String(data.code || response.status)[0])) {
      if (util.isType(data, `blob`)) {
        return response
      } else if (data.data === undefined) {
        return data
      } else {
        return response.data.data
      }
    } else {
      return Promise.reject(data.msg || data)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

const install = (Vue) => {
  Vue.prototype.$http = api
}

export { api }

/**
key 是监听的键
api 是 get 请求的地址
当 api 是函数时直接运行函数
arg 是 get 请求参数
可以通过 this.$apiObj.键名.arg = {} 修改参数
time 是更新频率
*/
const apiObj = {
  // 当前天气
  currentWeather: {
    api: `/api/currentWeather`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
  // 当前时间
  currentTime: {
    api: async (arg) => {
      const dateBox = {
        date: dayjs(Date.now()).format(`YYYY/MM/DD`),
        time: dayjs(Date.now()).format(`HH:mm:ss`),
      }
      return dateBox
    },
    time: 1000,
  },
  variousRegions: {
    api: `/api/analysisOfTransplantYieldInVariousRegions`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
  weatherForecast: {
    api: `/api/weatherForecast`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
  eachRegion: {
    api: `/api/transplantAreaInEachRegion`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
  situation: {
    api: `/api/analysisOfTransplantingSituation`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
  statistics: {
    api: `/api/realTimeStatistics`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
  trendAnalysis: {
    api: `/api/transplantTrendAnalysis`,
    // 1小时
    // time: 1000 * 60 * 60,
    time: 1000 * 5,
  },
}

export default {
  apiObj,
  install,
}
