<script lang="ts" setup>
import { computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import type { IVisitorVO } from '@/api/types/appointment'
import {
  getMyVisitors,
  saveVisitorTemplate,
  deleteVisitorTemplate,
} from '@/api/appointment'

definePage({
  style: { navigationBarTitleText: '访客信息' },
})

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

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

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

// 新增/编辑弹窗
const showFormPopup = ref(false)
const editingItem = ref<IVisitorVO | null>(null)
const formName = ref('')
const formPhone = ref('')
const formCompany = ref('')
const formIdType = ref('身份证')
const formIdNumber = ref('')
const formSaving = ref(false)


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

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

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

function toggleSelect(item: IVisitorVO & { _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).visitorResult = selected.value.map(v => ({
      name: v.name, phone: v.phone, company: v.company,
      gender: v.gender, id_type: v.id_type, id_number: v.id_number,
    }))
  }
  uni.navigateBack()
}

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

// ==================== 新增/编辑 ====================
function openAddForm() {
  editingItem.value = null
  formName.value = ''
  formPhone.value = ''
  formCompany.value = ''
  formIdType.value = '身份证'
  formIdNumber.value = ''
  showFormPopup.value = true
}

function openEditForm(item: IVisitorVO) {
  editingItem.value = item
  formName.value = item.name
  formPhone.value = item.phone
  formCompany.value = item.company || ''
  formIdType.value = item.id_type || '身份证'
  formIdNumber.value = item.id_number || ''
  showFormPopup.value = true
}

async function saveForm() {
  if (!formName.value.trim()) { uni.showToast({ title: '请输入姓名', icon: 'none' }); return }
  if (!/^1[3-9]\d{9}$/.test(formPhone.value)) { uni.showToast({ title: '请输入正确的手机号', icon: 'none' }); return }
  if (!formCompany.value.trim()) { uni.showToast({ title: '请输入来访单位', icon: 'none' }); return }
  if (!formIdNumber.value.trim()) { uni.showToast({ title: '请输入身份证号', icon: 'none' }); return }
  formSaving.value = true
  try {
    await saveVisitorTemplate({
      name: formName.value.trim(), phone: formPhone.value.trim(),
      company: formCompany.value, id_type: formIdType.value, id_number: formIdNumber.value,
    })
    showFormPopup.value = false
    uni.showToast({ title: '保存成功', icon: 'success' })
    loadTemplates()
  } catch {} finally { formSaving.value = false }
}

// ==================== 删除 ====================
function confirmDelete(id: number) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该访客吗？',
    success: (res) => {
      if (res.confirm) {
        doDelete(id)
      }
    },
  })
}
async function doDelete(id: number) {
  try {
    await deleteVisitorTemplate(id)
    selected.value = selected.value.filter(s => s.id !== id)
    loadTemplates()
    uni.showToast({ title: '已删除', icon: 'success' })
  } catch (err: any) {
    uni.showToast({ title: err?.message || '删除失败', icon: 'none' })
  }
}
</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-4 py-6 text-center text-sm text-[#999]">
        暂无常用访客
      </view>
      <view v-else class="card">
        <view
          v-for="(item, idx) in templates" :key="item.id"
          class="flex items-stretch px-4"
          :class="{ 'border-b border-[#f0f0f0]': idx < templates.length - 1, 'bg-[#e8f4fd]': item._checked }"
        >
          <!-- 左侧：选择 + 内容 -->
          <view class="flex items-center flex-1 min-w-0 py-3" @click="toggleSelect(item)">
            <wd-checkbox :model-value="!!item._checked" class="mr-3" />
            <view class="flex-1 min-w-0">
              <text class="text-sm font-medium">{{ item.name }}</text>
              <text class="ml-2 text-xs text-[#999]">{{ item.phone }}</text>
              <view class="mt-1 text-xs text-[#999] truncate">
                <text>{{ item.company || '无单位' }}</text>
                <text v-if="item.id_number">｜{{ item.id_number }}</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="formName" placeholder="请输入姓名" clearable /></view>
        </view>
        <view class="flex items-center mb-3">
          <text class="label-text">手机号</text>
          <view class="flex-1"><wd-input v-model="formPhone" placeholder="请输入手机号" type="number" :maxlength="11" clearable /></view>
        </view>
        <view class="flex items-center mb-3">
          <text class="label-text">来访单位</text>
          <view class="flex-1"><wd-input v-model="formCompany" placeholder="请输入来访单位" clearable /></view>
        </view>
        <view class="flex items-center mb-3">
          <text class="label-text">身份证号</text>
          <view class="flex-1"><wd-input v-model="formIdNumber" placeholder="请输入身份证号" :maxlength="18" clearable /></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>


    <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>
