<script lang="ts" setup>
import { computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import {
  getVehicleTemplates,
  createVehicleTemplate,
  updateVehicleTemplate,
  deleteVehicleTemplate,
} from '@/api/appointment'
import { VEHICLE_COLORS } from '@/utils/constants'

definePage({
  style: { navigationBarTitleText: '选择车辆' },
})

// ==================== 接收已有选中（用于回显） ====================
const preSelected = ref<any[]>([])

onLoad((options?: any) => {
  if (options?.vehicles) {
    try {
      preSelected.value = JSON.parse(decodeURIComponent(options.vehicles))
    } catch {}
  }
})

// ==================== 状态 ====================
const templates = ref<(any & { _checked?: boolean })[]>([])
const loading = ref(false)

// 新增/编辑弹窗
const showFormPopup = ref(false)
const editingItem = ref<any | null>(null)
const formPlate = ref('')
const formBrand = ref('')
const formColor = ref('')
const formSaving = ref(false)

// 删除确认
const showDeleteConfirm = ref(false)
const deletingId = ref<number>(0)

// ==================== 数据加载 ====================
async function loadTemplates() {
  loading.value = true
  try {
    const list = await getVehicleTemplates()
    templates.value = list.map((item: any) => ({
      ...item,
      _checked: preSelected.value.some((s: any) =>
        s.plate ? s.plate === item.license_plate : s.license_plate === item.license_plate
      ),
    }))
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

onShow(() => {
  loadTemplates()
})

// ==================== 选中 ====================
const selected = ref<any[]>([])

function toggleSelect(item: any & { _checked?: boolean }) {
  item._checked = !item._checked
  if (item._checked) {
    selected.value.push({ ...item })
  } else {
    const idx = selected.value.findIndex(s => s.id === item.id)
    if (idx > -1) selected.value.splice(idx, 1)
  }
}

function selectAll() {
  const allSelected = templates.value.every(t => t._checked)
  templates.value.forEach(t => { t._checked = !allSelected })
  selected.value = allSelected ? [] : templates.value.map(t => ({ ...t }))
}

/** 确定返回 */
function confirmSelection() {
  const pages = getCurrentPages()
  const prevPage = pages[pages.length - 2]
  if (prevPage) {
    // 统一转为 { brand, plate, color } 格式返回
    ;(prevPage as any).vehicleResult = selected.value.map((v: any) => ({
      brand: v.brand || '',
      plate: v.license_plate || v.plate || '',
      color: v.color || '',
    }))
  }
  uni.navigateBack()
}

const selectedCount = computed(() => selected.value.length)

// ==================== 新增/编辑 ====================
function openAddForm() {
  editingItem.value = null
  formPlate.value = ''
  formBrand.value = ''
  formColor.value = ''
  showFormPopup.value = true
}

function openEditForm(item: any) {
  editingItem.value = item
  formPlate.value = item.license_plate || item.plate || ''
  formBrand.value = item.brand || ''
  formColor.value = item.color || ''
  showFormPopup.value = true
}

async function saveForm() {
  if (!formPlate.value.trim()) { uni.showToast({ title: '请输入车牌号', icon: 'none' }); return }
  formSaving.value = true
  try {
    const data = {
      license_plate: formPlate.value.trim(),
      brand: formBrand.value,
      color: formColor.value,
    }
    if (editingItem.value && editingItem.value.id) {
      await updateVehicleTemplate(editingItem.value.id, data)
    } else {
      await createVehicleTemplate(data)
    }
    showFormPopup.value = false
    uni.showToast({ title: '保存成功', icon: 'success' })
    loadTemplates()
  } catch {} finally { formSaving.value = false }
}

// ==================== 删除 ====================
function confirmDelete(id: number) { deletingId.value = id; showDeleteConfirm.value = true }
async function doDelete() {
  try {
    await deleteVehicleTemplate(deletingId.value)
    showDeleteConfirm.value = false
    selected.value = selected.value.filter(s => s.id !== deletingId.value)
    loadTemplates()
  } catch {}
}
</script>

<template>
  <view class="min-h-screen bg-[#f5f7fa]">
    <!-- 工具栏 -->
    <view class="card mx-3 mt-3 flex items-center justify-between px-3 py-2">
      <view class="flex items-center gap-2">
        <wd-button plain @click="selectAll">
          {{ templates.every(t => t._checked) ? '取消全选' : '全选' }}
        </wd-button>
      </view>
      <view class="flex items-center gap-2">
        <text class="text-sm text-[#666]">已选 {{ selectedCount }} 项</text>
        <wd-button type="primary" @click="confirmSelection">确定</wd-button>
      </view>
    </view>

    <!-- 列表 -->
    <view class="mx-3 mt-2">
      <view v-if="loading" class="py-8 text-center text-[#999]">加载中...</view>
      <view v-else-if="templates.length === 0" class="card px-3 py-4 text-center text-sm text-[#999]">
        暂无保存的车辆模板
        <text class="text-[#2979ff]" @click="openAddForm">添加车辆</text>
      </view>
      <view v-else class="card">
        <view
          v-for="item in templates" :key="item.id"
          class="flex items-stretch border-b border-[#f0f0f0]"
          :class="{ 'bg-[#e8f4fd]': item._checked }"
        >
          <!-- 左侧：选择 + 内容 -->
          <view class="flex items-center flex-1 min-w-0 px-3 py-3 cursor-pointer" @click="toggleSelect(item)">
            <wd-checkbox :model-value="!!item._checked" class="mr-2" />
            <view class="flex-1 min-w-0">
              <text class="text-sm font-medium">{{ item.license_plate || item.plate }}</text>
              <view class="mt-1 text-xs text-[#999]">
                <text v-if="item.brand">{{ item.brand }}</text>
                <text v-if="item.color">｜{{ item.color }}</text>
              </view>
            </view>
          </view>
          <!-- 右侧：操作按钮 -->
          <view class="flex items-center gap-3 pl-3 pr-3 border-l border-[#f0f0f0]">
            <view class="flex items-center justify-center w-10 h-10 rounded-full bg-[#e8f0fe] active:bg-[#d0e0fd]" @click.stop="openEditForm(item)">
              <wd-icon name="edit" size="18px" color="#2979ff" />
            </view>
            <view class="flex items-center justify-center w-10 h-10 rounded-full bg-[#fef0f0] active:bg-[#fdd0d0]" @click.stop="confirmDelete(item.id!)">
              <wd-icon name="delete" size="18px" color="#dd524d" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部添加 -->
    <view class="fixed bottom-4 left-0 right-0 px-4">
      <wd-button type="primary" size="large" block plain @click="openAddForm">新增车辆模板</wd-button>
    </view>

    <!-- 新增/编辑弹窗 -->
    <wd-popup v-model="showFormPopup" position="bottom" :close-on-click-modal="false" custom-style="border-radius: 16px 16px 0 0;">
      <view class="p-4">
        <text class="mb-4 block text-lg font-bold">{{ editingItem ? '编辑车辆' : '新增车辆' }}</text>

        <view class="flex items-center mb-3">
          <text class="label-text">车牌号</text>
          <view class="flex-1"><wd-input v-model="formPlate" placeholder="请输入车牌号（必填）" clearable /></view>
        </view>
        <view class="flex items-center mb-3">
          <text class="label-text">品牌</text>
          <view class="flex-1"><wd-input v-model="formBrand" placeholder="品牌（选填）" clearable /></view>
        </view>
        <view class="flex items-center mb-3 min-h-[44px]">
          <text class="label-text">颜色</text>
          <picker mode="selector" :range="VEHICLE_COLORS" @change="e => formColor = VEHICLE_COLORS[e.detail.value]" class="flex-1">
            <view class="flex items-center py-2">
              <view class="flex-1 text-right">
                <text :class="formColor ? 'text-[#1a1a1a]' : 'text-[#c0c4cc]'">{{ formColor || '请选择颜色' }}</text>
              </view>
              <wd-icon name="right" size="14px" color="#ccc" class="ml-1" />
            </view>
          </picker>
        </view>

        <view class="mt-4 flex gap-3">
          <wd-button plain block @click="showFormPopup = false">取消</wd-button>
          <wd-button type="primary" block :loading="formSaving" @click="saveForm">保存</wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 删除确认 -->
    <wd-dialog v-model="showDeleteConfirm" title="确认删除" :show-cancel-button="true" @confirm="doDelete">
      <text>确定要删除该车辆模板吗？</text>
    </wd-dialog>

    <view class="h-20" />
  </view>
</template>

<style lang="scss" scoped>
.fixed { position: fixed; }
.cursor-pointer { cursor: pointer; }
.label-text { width: 5em; font-size: 14px; color: #666; flex-shrink: 0; }
.card { background: #fff; border-radius: 12px; overflow: hidden; }

</style>
