import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as api from '@/api/screen'

// ===== 开发调试开关 =====
// 正式联调前请关闭此开关
const ENABLE_APPOINTMENT_CONFIRM_MOCK = import.meta.env.DEV
// =========================

export const useVisitorStore = defineStore('visitor', () => {
  // 当前访客信息
  const currentVisitor = ref({
    name: '',
    mobile: '',
    idCardNo: '',
    gender: '',
    nation: '',
    address: '',
    photoUrl: ''
  })

  // 预约信息
  const appointmentInfo = ref(null)

  // 登记信息
  const registrationInfo = ref({
    visitorName: '',
    mobile: '',
    idCardNo: '',
    visitType: 'walk_in',
    registerType: 'manual',
    visitorSource: '',
    visitReason: '',
    visitedPerson: '',
    appointmentNo: ''
  })

  // 登记表单验证状态
  const formErrors = ref({})

  // 来访事由选项
  const visitReasonOptions = [
    { value: 'business', label: '商务洽谈' },
    { value: 'interview', label: '面试应聘' },
    { value: 'delivery', label: '快递/外卖' },
    { value: 'maintenance', label: '设备维修' },
    { value: 'visit_friend', label: '探亲访友' },
    { value: 'consultation', label: '咨询业务' },
    { value: 'other', label: '其他事宜' }
  ]

  // 方法
  function setIdCardInfo(info) {
    currentVisitor.value = {
      ...currentVisitor.value,
      name: info.name || '',
      idCardNo: info.idCardNo || '',
      gender: info.gender || '',
      nation: info.nation || '',
      address: info.address || '',
      photoUrl: info.photoUrl || ''
    }
    // 自动填充登记信息
    registrationInfo.value.visitorName = info.name || ''
    registrationInfo.value.idCardNo = info.idCardNo || ''
  }

  function setMobile(mobile) {
    currentVisitor.value.mobile = mobile
    registrationInfo.value.mobile = mobile
  }

  function setFormField(field, value) {
    registrationInfo.value[field] = value
    if (formErrors.value[field]) {
      delete formErrors.value[field]
    }
  }

  function validateForm() {
    const errors = {}
    if (!registrationInfo.value.visitorName?.trim()) {
      errors.visitorName = '请输入访客姓名'
    }
    if (!registrationInfo.value.mobile?.trim()) {
      errors.mobile = '请输入手机号'
    } else if (!/^1[3-9]\d{9}$/.test(registrationInfo.value.mobile)) {
      errors.mobile = '手机号格式不正确'
    }
    formErrors.value = errors
    return Object.keys(errors).length === 0
  }

  async function queryAppointment(mobile) {
    try {
      const res = await api.queryAppointment({ mobile })
      appointmentInfo.value = res
      return res
    } catch (e) {
      appointmentInfo.value = null
      throw e
    }
  }

  /**
   * Mock 预约数据，用于开发调试
   * 正式联调前请关闭 ENABLE_APPOINTMENT_CONFIRM_MOCK
   */
  function setMockAppointment(mobile = '13800000000') {
    const now = new Date()
    const dateStr = now.toISOString().slice(0, 10)
    const timeStr = `${dateStr} 14:30`
    const mockData = {
      appointmentNo: `APT${dateStr.replace(/-/g, '')}0001`,
      visitorName: '张三',
      mobile: mobile,
      idCardNo: '320***********1234',
      visitedPerson: '李经理',
      visitedDepartment: '综合管理部',
      appointmentTime: timeStr,
      visitPurpose: '业务拜访',
      companyName: '测试单位',
      remark: '前端调试预约数据',
      _isMock: true
    }
    appointmentInfo.value = mockData
    return mockData
  }

  async function submitRegistration() {
    if (!validateForm()) {
      throw new Error('表单验证失败')
    }
    // 开发环境：Mock 提交成功
    if (import.meta.env.DEV) {
      const now = new Date()
      const pad = (n) => String(n).padStart(2, '0')
      const dateTime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
      registrationInfo.value = {
        ...registrationInfo.value,
        registerTime: dateTime
      }
      return registrationInfo.value
    }
    try {
      const res = await api.submitVisitorRegistration(registrationInfo.value)
      return res
    } catch (e) {
      throw e
    }
  }

  async function readIdCard() {
    try {
      const res = await api.readIdCard()
      setIdCardInfo(res)
      return res
    } catch (e) {
      throw e
    }
  }

  function clearVisitorData() {
    currentVisitor.value = {
      name: '',
      mobile: '',
      idCardNo: '',
      gender: '',
      nation: '',
      address: '',
      photoUrl: ''
    }
    appointmentInfo.value = null
    registrationInfo.value = {
      visitorName: '',
      mobile: '',
      idCardNo: '',
      visitType: 'walk_in',
      registerType: 'manual',
      visitorSource: '',
      visitReason: '',
      visitedPerson: '',
      appointmentNo: ''
    }
    formErrors.value = {}
  }

  return {
    currentVisitor,
    appointmentInfo,
    registrationInfo,
    formErrors,
    visitReasonOptions,
    setIdCardInfo,
    setMobile,
    setFormField,
    validateForm,
    queryAppointment,
    submitRegistration,
    readIdCard,
    clearVisitorData,
    // 开发调试用
    setMockAppointment,
    ENABLE_APPOINTMENT_CONFIRM_MOCK
  }
})
