import axios from 'axios'
import request from '@/utils/request'

export interface TaskChainVO {
  id: number
  code: string
  warehouse: string
  firstTaskVendor: string
  status: string
  type: string
  businessNo: string
  description: string
  sourceLocation: string
  sourcePoint: string
  sourceContainer: string
  targetType: string
  targetCode: string
  targetLocation: string
  targetPoint: string
  elevatorId: number
  priority: number
  executionTime: number
  completeTime?: string
  cancelReason: string
  cancelTime: string
  createTime: string
}

export interface TaskVO {
  id: number
  chainCode: string
  code: string
  machineCallCode: string
  vendor: string
  status: string
  type: string
  exceptionReason: string
  sourceLocation: string
  sourcePoint: string
  sourceContainer: string
  targetLocation: string
  targetPoint: string
  targetType: string
  targetCode: string
  executionTime: number
  startTime: string
  completeTime: string
  cancelReason: string
  cancelTime: string
  batchNo: number
  remark: string
  createTime: string
}

export interface TaskChainDetailVO extends TaskChainVO {
  tasks: TaskVO[]
}

export interface PageResult<T> {
  records: T[]
  total: number
  size: number
  current: number
  pages: number
}

export interface ChainQueryParams {
  page: number
  size: number
  code?: string
  warehouse?: string
  status?: string
  type?: string
  businessNo?: string
  sourceContainer?: string
  targetCode?: string
  startTime?: string
  endTime?: string
}

export function getChainPage(params: ChainQueryParams) {
  return request.get<never, { code: number; data: PageResult<TaskChainVO> }>(
    '/api/robot/external/admin/machine-task/chain/page',
    { params },
  )
}

export interface TaskChainStatsVO {
  inProgress: number
  waiting: number
  completedToday: number
  failedToday: number
}

export function getChainStats() {
  return request.get<never, { code: number; data: TaskChainStatsVO }>(
    '/api/robot/external/admin/machine-task/chain/stats',
  )
}

export function getChainDetail(code: string) {
  return request.get<never, { code: number; data: TaskChainDetailVO }>(
    `/api/robot/external/admin/machine-task/chain/detail/${code}`,
  )
}

export function dispatchScan(warehouse: string) {
  return request.get<never, { code: number; data: boolean }>(
    '/api/robot/external/admin/machine-task/dispatch/scan',
    { params: { warehouse } },
  )
}

export function dispatchExecute(warehouse: string, chainCode: string) {
  return request.get<never, { code: number; data: boolean }>(
    '/api/robot/external/admin/machine-task/dispatch/execute',
    { params: { warehouse, chainCode } },
  )
}

export const taskStatusOptions = [
  { value: 'CREATED', label: '已创建' },
  { value: 'READY', label: '准备就绪' },
  { value: 'IN_PROGRESS', label: '进行中' },
  { value: 'WAITING_WAKE', label: '待唤醒' },
  { value: 'WAITING_RELEASE', label: '待释放' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELED', label: '已取消' },
  { value: 'FAILED', label: '失败' },
]

export function cancelChain(chainCode: string, reason?: string, moveOut = false) {
  return request.post<never, { code: number; data: boolean }>(
    '/api/robot/external/admin/machine-task/chain/cancel',
    null,
    { params: { chainCode, reason, moveOut } },
  )
}

/** 业务取消（MachineTaskController POST /task/cancel，@RequestBody MachineCancelReqDTO） */
export function cancelTaskByBusinessNo(businessNo: string, reason?: string) {
  return request.post<
    never,
    { code: number; data: string[] | null }
  >('/api/robot/external/admin/machine-task/task/cancel', {
    businessNo,
    ...(reason != null && reason !== '' ? { reason } : {}),
  })
}

export function deleteTask(taskCode: string) {
  return request.post<never, { code: number; data: boolean }>(
    '/api/robot/external/admin/machine-task/task/delete',
    null,
    { params: { taskCode } },
  )
}

export function forceTaskStatus(taskCode: string, status: string) {
  return request.post<never, { code: number; data: boolean }>(
    '/api/robot/external/admin/machine-task/task/forceStatus',
    null,
    { params: { taskCode, status } },
  )
}

// ==================== 模拟回调 ====================

export interface CallbackScenario {
  key: string
  label: string
  url: string
  fields: CallbackField[]
}

export interface CallbackField {
  name: string
  label: string
  type: 'string' | 'select' | 'number' | 'boolean'
  options?: { value: string; label: string }[]
}

const hkFields: CallbackField[] = [
  { name: 'robotTaskCode', label: '机器调用编号', type: 'string' },
  { name: 'singleRobotCode', label: '机器人标识', type: 'string' },
  { name: 'currentSeq', label: '当前执行顺序', type: 'string' },
]

const zsTaskStatusOptions = [
  { value: 'RUNNING', label: '执行中' },
  { value: 'FINISHED', label: '已完成' },
  { value: 'TERMINATED', label: '取消' },
  { value: 'PENDING', label: '挂起' },
]

const zsTaskStepOptions = [
  { value: '', label: '无' },
  { value: 'CHAIN', label: '托盘到达输送' },
  { value: 'IN_LIFTER', label: '托盘进提升机' },
  { value: 'OUT_LIFTER', label: '托盘出提升机' },
  { value: 'VEHICLE_MOVE', label: '四向车搬运' },
  { value: 'VEHICLE_WILL_PICK', label: '四向车准备举升托盘' },
]

const zsTaskInfoBackFields: CallbackField[] = [
  { name: 'taskCode', label: '机器调用编号', type: 'string' },
  { name: 'palletCode', label: '托盘码', type: 'string' },
  { name: 'status', label: '任务状态', type: 'select', options: zsTaskStatusOptions },
  { name: 'taskStep', label: '任务步骤', type: 'select', options: zsTaskStepOptions },
  { name: 'hasPick', label: '是否取货', type: 'boolean' },
  { name: 'start', label: '取货点', type: 'string' },
  { name: 'end', label: '放货点', type: 'string' },
  { name: 'actualStart', label: '实际取货点', type: 'string' },
  { name: 'actualEnd', label: '实际放货点', type: 'string' },
  { name: 'statusCode', label: '取消原因', type: 'string' },
  { name: 'pendingCode', label: '挂起原因', type: 'string' },
]

const zsExceptionFields: CallbackField[] = [
  { name: 'location', label: '点位ID', type: 'string' },
  { name: 'palletCode', label: '托盘码', type: 'string' },
  { name: 'reason', label: '异常原因', type: 'string' },
]

const zsPalletCodeInFields: CallbackField[] = [
  { name: 'location', label: '点位ID', type: 'string' },
  { name: 'palletCode', label: '托盘码', type: 'string' },
  { name: 'warehouseCode', label: '仓库编号', type: 'string' },
  { name: 'weigth', label: '物料重量(g)', type: 'number' },
  { name: 'longLevel', label: '长度等级', type: 'number' },
  { name: 'widthLevel', label: '宽度等级', type: 'number' },
  { name: 'highLevel', label: '高度等级', type: 'number' },
]

const hkArriveWcs: CallbackScenario = {
  key: 'arriveWcs', label: 'AGV到达立库提升机',
  url: '/api/robot/external/hk/arriveWcs', fields: hkFields,
}
const hkArriveStation: CallbackScenario = {
  key: 'arriveStation', label: 'AGV到达工作站点',
  url: '/api/robot/external/hk/arriveStation', fields: hkFields,
}

export const callbackScenarioMap: Record<string, CallbackScenario[]> = {
  HK_INBOUND: [hkArriveWcs],
  HK_MOVE: [hkArriveWcs],
  HK_OUTBOUND_WAIT: [hkArriveWcs, hkArriveStation],
  HK_ARRIVE_ELEVATOR: [hkArriveWcs],
  HK_ARRIVE_STATION: [hkArriveStation],
  HK_PICK_PALLET: [{ key: 'pickPalletDone', label: 'AGV完成取货', url: '/api/robot/external/hk/pickPalletDone', fields: hkFields }],
  HK_PICK_UP: [{ key: 'pickUp', label: '海康举起托盘', url: '/api/robot/external/hk/pickUp', fields: hkFields }],
  HK_PUT_PALLET: [{ key: 'putPalletDone', label: 'AGV完成放货', url: '/api/robot/external/hk/putPalletDone', fields: hkFields }],
  HK_LEAVE_START_POINT: [{ key: 'leaveStartPoint', label: 'AGV离开起点', url: '/api/robot/external/hk/leaveStartPoint', fields: hkFields }],
  ZS_INBOUND: [{ key: 'taskInfoBack', label: '任务状态回传', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_OUTBOUND: [{ key: 'taskInfoBack', label: '任务状态回传', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_PRE_PICK_UP: [{ key: 'taskInfoBack', label: '四向车准备举升托盘', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_PICK_UP: [{ key: 'taskInfoBack', label: '智世举起目标托盘', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_OUTBOUND_IN_LIFTER: [{ key: 'taskInfoBack', label: '托盘进提升机', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_OUTBOUND_FINISH: [{ key: 'taskInfoBack', label: '智世出库完成', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_MOVE: [{ key: 'taskInfoBack', label: '任务状态回传', url: '/api/robot/external/zs/wms/taskInfoBack', fields: zsTaskInfoBackFields }],
  ZS_OUTER_DETECT: [{ key: 'exceptionPickUpNotify', label: '外形检测异常', url: '/api/robot/external/zs/wms/exceptionPickUpNotify', fields: zsExceptionFields }],
  ZS_APPLY_INBOUND: [{ key: 'palletCodeIn', label: '请求入库', url: '/api/robot/external/zs/wms/palletCodeIn', fields: zsPalletCodeInFields }],
}

export function sendMockCallback(url: string, data: Record<string, unknown>) {
  const base = import.meta.env.VITE_API_BASE || ''
  const token = localStorage.getItem('token')
  return axios.post(`${base}${url}`, data, {
    headers: {
      Authorization: token || '',
      Source: 'web',
    },
    timeout: 15000,
  })
}
