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

const WORKERMAN_URL = process.env.VUE_APP_WORKERMAN_URL || 'http://127.0.0.1:34351'
const WORKERMAN_API = process.env.VUE_APP_WORKERMAN_API || WORKERMAN_URL

const workerman = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

function normalizePayload (data = {}) {
  return data.sendData || data
}

function readBusinessError (data) {
  if (!data || typeof data !== 'object') return ''
  const code = data.code ?? data.errcode
  if (code === undefined || Number(code) === 0) return ''
  return data.errmsg || data.msg || data.message || 'Workerman 接口返回失败'
}

function buildRequestErrorMessage (error) {
  if (error.response) {
    return `Workerman 接口请求失败：HTTP ${error.response.status}`
  }
  if (error.code === 'ECONNABORTED') {
    return `Workerman 接口请求超时，请确认 ${WORKERMAN_URL} 是否可访问`
  }
  if (error.request) {
    return `Workerman 接口无响应，请确认浏览器可以访问 ${WORKERMAN_URL}`
  }
  return error.message || 'Workerman 接口请求失败'
}

export function sendWorkerman (data) {
  return workerman.post(WORKERMAN_API, normalizePayload(data)).then(response => {
    const result = response.data
    const businessError = readBusinessError(result)
    if (businessError) {
      Message.error(businessError)
      const error = new Error(businessError)
      error.__workermanHandled = true
      throw error
    }
    if (result === undefined || result === null || result === '') {
      const message = 'Workerman 接口未返回有效数据'
      Message.error(message)
      const error = new Error(message)
      error.__workermanHandled = true
      throw error
    }
    return result
  }).catch(error => {
    if (error.__workermanHandled) throw error
    const message = buildRequestErrorMessage(error)
    Message.error(message)
    throw error
  })
}

export function trayLogin (param) {
  return sendWorkerman({
    action: 'set_tray_login',
    param
  })
}

export function trayUnbinding (tray) {
  return sendWorkerman({
    action: 'set_tray_unbinding',
    param: { tray }
  })
}

export function trayInactivity (tray) {
  return sendWorkerman({
    action: 'set_tray_inactivity',
    param: { tray }
  })
}

export function batteryInactivity (data) {
  return sendWorkerman({
    action: 'set_battery_inactivity',
    param: { data }
  })
}
