import request from '@/utils/request'

function normalizeApiError(res, fallbackMessage) {
  if (res && typeof res === 'object' && res.status === 'error') {
    return res.message || fallbackMessage
  }
  return fallbackMessage
}

export async function syncVehicleRegistry(items) {
  const res = await request({
    url: '/api/VehicleRegistry',
    method: 'post',
    data: items
  })
  if (res && typeof res === 'object' && res.status === 'error') {
    throw new Error(normalizeApiError(res, '对象注册同步失败'))
  }
  return res
}

export async function updateRunwayWarningRadius(value) {
  const res = await request({
    url: '/config/runway/warning_zone_radius/aircraft',
    method: 'post',
    data: { value }
  })
  if (res && typeof res === 'object' && res.status === 'error') {
    throw new Error(normalizeApiError(res, '修改预警区半径失败'))
  }
  return res
}

export async function updateRunwayAlertRadius(value) {
  const res = await request({
    url: '/config/runway/alert_zone_radius/aircraft',
    method: 'post',
    data: { value }
  })
  if (res && typeof res === 'object' && res.status === 'error') {
    throw new Error(normalizeApiError(res, '修改告警区半径失败'))
  }
  return res
}

export async function updateDivergingReleaseDistance(value) {
  const data = (() => {
    if (typeof value === 'number') return { value }
    if (!value || typeof value !== 'object') return {}
    if (Object.prototype.hasOwnProperty.call(value, 'value')) return { value: value.value }
    const payload = {}
    if (Object.prototype.hasOwnProperty.call(value, 'vehicleDistance')) payload.vehicleDistance = value.vehicleDistance
    if (Object.prototype.hasOwnProperty.call(value, 'aircraftDistance')) payload.aircraftDistance = value.aircraftDistance
    return payload
  })()
  const res = await request({
    url: '/config/collision/diverging_release_distance',
    method: 'post',
    data
  })
  if (res && typeof res === 'object' && res.status === 'error') {
    throw new Error(normalizeApiError(res, '修改冲突解除距离阈值失败'))
  }
  return res
}

export async function assignVehicleRoute(payload) {
  const res = await request({
    url: '/api/vehicle-route/assignment',
    method: 'post',
    data: payload
  })
  if (res && typeof res === 'object' && res.status === 'error') {
    throw new Error(normalizeApiError(res, '车辆路线分配失败'))
  }
  return res
}
