import { ElMessage, ElMessageBox } from 'element-plus'
import { mapEditApi } from '@/api/mapEdit'
import { reflectionApi, type ReflectionKind, type ReflectionMethod } from '@/api/reflection'

/** 需在 Web 端先选站点再执行的动作（后端方法内部依赖 SimpleUI.GetPoint，iframe 下不可靠）。 */
const SITE_PICK_METHOD_NAMES = new Set(['Goto', 'GotoSite'])
const SITE_PICK_LABEL_HINTS = ['去某地', '前往站点']

export function methodNeedsSitePick(m: ReflectionMethod): boolean {
  if (m.params?.length) return false
  if (SITE_PICK_METHOD_NAMES.has(m.methodName)) return true
  const label = m.label ?? ''
  return SITE_PICK_LABEL_HINTS.some((h) => label.includes(h))
}

export interface SitePickOption {
  id: number
  name: string
  label: string
}

export async function loadSitePickOptions(): Promise<SitePickOption[]> {
  const rows = await reflectionApi.listObjects('site')
  return rows
    .map((s) => ({
      id: s.id,
      name: s.name,
      label: `#${s.id} ${s.name || '站点'}`
    }))
    .sort((a, b) => a.id - b.id)
}

/** 在地图上拾取目标站点（调用 SimpleLite pick 会话）。 */
export async function pickTargetSiteOnMap(): Promise<number | null> {
  try {
    ElMessage.info({ message: '请在 3D 地图上点击目标站点附近', duration: 4000 })
    const r = await mapEditApi.pick()
    if (r.siteId == null || r.siteId < 0) {
      ElMessage.warning('未识别到附近站点，请靠近站点再点击')
      return null
    }
    return r.siteId
  } catch (e) {
    if (e instanceof Error && /取消|cancel|499/i.test(e.message)) return null
    ElMessage.error(`地图拾取失败：${e instanceof Error ? e.message : String(e)}`)
    return null
  }
}

function isHttp404(e: unknown): boolean {
  if (e && typeof e === 'object' && 'response' in e) {
    const status = (e as { response?: { status?: number } }).response?.status
    if (status === 404) return true
  }
  const msg = e instanceof Error ? e.message : String(e)
  return /status code 404/i.test(msg)
}

export async function executeCarGotoSite(carId: number, siteId: number): Promise<boolean> {
  try {
    const r = await reflectionApi.gotoCarSite(carId, siteId)
    ElMessage.success(r.message || `已下发前往站点 #${siteId}`)
    return true
  } catch (e) {
    if (!isHttp404(e)) {
      ElMessage.error(`前往站点失败：${e instanceof Error ? e.message : String(e)}`)
      return false
    }
    // goto-site 路由未加载（旧 DLL）：回退 execute WebGotoSite（DummyCar / Car 上均有）
    try {
      const r2 = await reflectionApi.execute('car', carId, 'WebGotoSite', { siteId })
      ElMessage.success(r2.returnValue ? `已执行：${r2.returnValue}` : `已下发前往站点 #${siteId}`)
      return true
    } catch (e2) {
      const msg2 = e2 instanceof Error ? e2.message : String(e2)
      const needDeploy =
        /WebGotoSite|goto-site|不存在可调用方法/i.test(msg2)
      ElMessage.error(
        needDeploy
          ? `${msg2}。当前 SimpleLite 仍是旧版 DLL：请先完全关闭 SimpleLite 窗口，再在 PowerShell 执行 Migu2.0/scripts/redeploy-simplelite.ps1，然后重新登录；或调用 POST /api/health/simplelite/restart-for-update`
          : `前往站点失败：${msg2}`
      )
      return false
    }
  }
}

export async function executeReflectionMethod(
  kind: ReflectionKind,
  objectId: number,
  m: ReflectionMethod
): Promise<boolean> {
  const label = m.label || m.methodName
  const params: Record<string, string> = {}
  for (const p of m.params) {
    try {
      const { value } = await ElMessageBox.prompt(
        `参数 ${p.name}（${p.typeName}）`,
        label,
        {
          inputValue: p.defaultValue ?? '',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      )
      params[p.name] = value ?? ''
    } catch {
      return false
    }
  }

  try {
    const r = await reflectionApi.execute(kind, objectId, m.methodName, params)
    ElMessage.success(r.returnValue ? `已执行：${r.returnValue}` : `已执行 ${label}`)
    return true
  } catch (e) {
    ElMessage.error(`执行失败：${e instanceof Error ? e.message : String(e)}`)
    return false
  }
}
