import axios from 'axios'
import { Message } from 'element-ui'

const http = axios.create({
  timeout: 5000 // 请求超时时间
})

http.interceptors.request.use(config => {
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug

  Promise.reject(error)
})

// respone拦截器
http.interceptors.response.use(response => {
  console.log(response)
  let code = response.status
  if (code) {
    if (code !== 200) {
      Message({
        message: response.statusText,
        type: 'error'
      })
    } else {
      return response.data
    }
  }
}, error => {
  return Promise.reject(error)
})

export function getConfig (ip) {
  return http.post(`http://${ip}:9001/config`)
}

// 更新配置
export function upDataConfig ({ ip, path, action, data }) {
  return http.post(`http://${ip}:9001/config/${path}`, {
    action: action,
    data: data
  })
}

// 升级终端
export function upgradeForm ({ ip, data }) {
  return http.post(`http://${ip}:9001/upgrade`, data)
}

// 重启
export function reboot (ip) {
  return http.post(`http://${ip}:9001/cmd`, {
    cmd: 'reboot',
    isRoot: true
  })
}

// 开门一次
export function openGateInOnce (ip) {
  return http.post(`http://${ip}:9001/config/gate`, {
    action: 'openInOnce'
  })
}

// 门常开
export function keepOpenGate (ip) {
  return http.post(`http://${ip}:9001/config/gate`, {
    action: 'keepOpen'
  })
}

// 关门
export function closeGate (ip) {
  return http.post(`http://${ip}:9001/config/gate`, {
    action: 'closeDoor'
  })
}
