<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { saveVisitorTemplate } from '@/api/appointment'
import { GENDER_OPTIONS } from '@/utils/constants'

definePage({
  style: { navigationBarTitleText: '编辑外部来访人员' },
})

const form = ref({
  name: '', phone: '', company: '', gender: 1, id_type: '身份证', id_number: '',
})
const saving = ref(false)

onLoad((options?: any) => {
  if (options?.visitor) {
    try {
      const data = JSON.parse(decodeURIComponent(options.visitor))
      form.value = { ...form.value, ...data }
    } catch {}
  }
})

function selectGender() {
  uni.showActionSheet({
    itemList: ['男', '女'],
    success: (r) => { form.value.gender = r.tapIndex + 1 },
  })
}

async function handleSave() {
  if (!form.value.name.trim()) { uni.showToast({ title: '请输入姓名', icon: 'none' }); return }
  if (!/^1[3-9]\d{9}$/.test(form.value.phone)) { uni.showToast({ title: '请输入正确的手机号', icon: 'none' }); return }
  saving.value = true
  try {
    await saveVisitorTemplate({
      name: form.value.name, phone: form.value.phone, company: form.value.company,
      gender: form.value.gender, id_type: form.value.id_type, id_number: form.value.id_number,
    })
    uni.showToast({ title: '保存成功', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 500)
  } catch { uni.showToast({ title: '保存失败', icon: 'none' }) } finally { saving.value = false }
}
</script>

<template>
  <view class="min-h-screen bg-[#f5f7fa] px-4 pt-4">
    <view class="rounded-2xl bg-white p-4 shadow-sm">
      <view class="space-y-3">
        <wd-input v-model="form.name" placeholder="姓名（必填）" clearable />
        <wd-input v-model="form.phone" placeholder="手机号（必填）" type="number" :maxlength="11" clearable />
        <wd-input v-model="form.company" placeholder="来访单位" clearable />
        <wd-cell
          title="性别"
          :value="GENDER_OPTIONS.find(g => g.value === form.gender)?.label || '请选择'"
          is-link
          @click="selectGender"
        />
        <wd-input v-model="form.id_type" placeholder="证件类型" clearable />
        <wd-input v-model="form.id_number" placeholder="证件号" clearable />
      </view>
    </view>

    <view class="mt-6">
      <wd-button type="primary" size="large" block round :loading="saving" @click="handleSave">
        保存
      </wd-button>
    </view>
  </view>
</template>
