<script lang="ts" setup>
import { computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import type { IGoodsTemplate } from '@/api/types/appointment'
import {
  getGoodsTemplates,
  createGoodsTemplate,
  updateGoodsTemplate,
  deleteGoodsTemplate,
} from '@/api/appointment'

definePage({
  style: {
    navigationBarTitleText: '选择携带物品',
  },
})

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

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

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

// 新增/编辑弹窗
const showFormPopup = ref(false)
const editingItem = ref<IGoodsTemplate | null>(null)
const formName = ref('')
const formQuantity = ref(1)
const formModel = ref('')
const formRemark = ref('')
const formSaving = ref(false)

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

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

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

// ==================== 选中 ====================
const selected = ref<(IGoodsTemplate & { _checked?: boolean })[]>([])

function toggleSelect(item: IGoodsTemplate & { _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) {
    ;(prevPage as any).goodsResult = selected.value
  }
  uni.navigateBack()
}

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

// ==================== 新增/编辑 ====================
function openAddForm() {
  editingItem.value = null
  formName.value = ''
  formQuantity.value = 1
  formModel.value = ''
  formRemark.value = ''
  showFormPopup.value = true
}

function openEditForm(item: IGoodsTemplate) {
  editingItem.value = item
  formName.value = item.name
  formQuantity.value = item.quantity
  formModel.value = item.model || ''
  formRemark.value = item.remark || ''
  showFormPopup.value = true
}

async function saveForm() {
  if (!formName.value.trim()) { uni.showToast({ title: '请输入物品名称', icon: 'none' }); return }
  formSaving.value = true
  try {
    if (editingItem.value && editingItem.value.id) {
      await updateGoodsTemplate(editingItem.value.id, {
        name: formName.value.trim(), quantity: formQuantity.value,
        model: formModel.value, remark: formRemark.value,
      })
    } else {
      await createGoodsTemplate({
        name: formName.value.trim(), quantity: formQuantity.value,
        model: formModel.value, remark: formRemark.value,
      })
    }
    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 deleteGoodsTemplate(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.name }}</text>
              <text class="ml-2 text-xs text-[#999]">x{{ item.quantity }}</text>
              <view class="mt-1 text-xs text-[#999] truncate">
                <text v-if="item.model">型号：{{ item.model }}</text>
                <text v-if="item.remark">｜{{ item.remark }}</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>
          <wd-input v-model="formName" placeholder="请输入物品名称（必填）" clearable />
        </view>
        <view class="flex items-center mb-3">
          <text class="label-text">数量</text>
          <wd-input v-model.number="formQuantity" placeholder="请输入数量" type="number" min="1" />
        </view>
        <view class="flex items-center mb-3">
          <text class="label-text">型号</text>
          <wd-input v-model="formModel" placeholder="型号（选填）" clearable />
        </view>
        <view class="flex items-start mb-3">
          <text class="label-text mt-2">备注</text>
          <view class="flex-1"><wd-textarea v-model="formRemark" placeholder="备注（选填）" :maxlength="100" fixed /></view>
        </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>
