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

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: 'SCREEN',
    visitorSource: '',
    visitReason: '',
    visitedPerson: '',
    appointmentNo: '',
    visitorPhoto: ''
  })

  // 登记表单验证状态
  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 || info.idNum || '',
      gender: info.gender || '',
      nation: info.nation || '',
      address: info.address || '',
      photoUrl: info.photoUrl || ''
    }
    // 自动填充登记信息
    registrationInfo.value.visitorName = info.name || ''
    registrationInfo.value.idCardNo = info.idCardNo || info.idNum || ''
    registrationInfo.value.visitorPhoto = info.photoUrl || ''
  }

  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(params) {
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'visitor.js:queryAppointment',message:'store queryAppointment 被调用',data:{params},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    try {
      const res = await api.queryAppointment(params)
      // #region debug log
      fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'visitor.js:queryAppointment',message:'api.queryAppointment 返回',data:{res},timestamp:Date.now()})}).catch(()=>{});
      // #endregion
      // 后端返回格式: { code, msg, data }
      appointmentInfo.value = res.data || res
      // #region debug log
      fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'visitor.js:queryAppointment',message:'设置 appointmentInfo',data:{appointmentInfo:appointmentInfo.value},timestamp:Date.now()})}).catch(()=>{});
      // #endregion
      return appointmentInfo.value
    } catch (e) {
      // #region debug log
      fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'visitor.js:queryAppointment',message:'api.queryAppointment 异常',data:{error:e?.message||e},timestamp:Date.now()})}).catch(()=>{});
      // #endregion
      appointmentInfo.value = null
      throw e
    }
  }

  async function submitRegistration() {
    if (!validateForm()) {
      throw new Error('表单验证失败')
    }
    // 开发环境：Mock 提交成功（临时禁用以测试后端接口）
    // TODO: 正式部署时删除此 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)
      // 后端返回格式: { code, msg, data }
      return res.data || res
    } catch (e) {
      throw e
    }
  }

  async function readIdCard() {
    try {
      const res = await api.readIdCard()
      // 后端返回格式: { code, msg, data }
      const info = res.data || res

      // 验证身份证数据是否有效
      if (!info.name || !info.idCardNo) {
        throw new Error('未检测到身份证，请确认身份证已放置正确')
      }

      setIdCardInfo(info)
      return info
    } 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: 'SCREEN',
      visitorSource: '',
      visitReason: '',
      visitedPerson: '',
      appointmentNo: '',
      visitorPhoto: ''
    }
    formErrors.value = {}
  }

  return {
    currentVisitor,
    appointmentInfo,
    registrationInfo,
    formErrors,
    visitReasonOptions,
    setIdCardInfo,
    setMobile,
    setFormField,
    validateForm,
    queryAppointment,
    submitRegistration,
    readIdCard,
    clearVisitorData
  }
})
