<script setup lang="ts">
import XForm from '@af-mobile-client-vue3/components/data/XForm/index.vue'
import { runLogic } from '@af-mobile-client-vue3/services/api/common'
import { showDialog, showToast } from 'vant'
import { inject, nextTick, onBeforeMount, ref } from 'vue'
import upaddress from './upaddress.vue'

const props = withDefaults(defineProps<{
  id?: string
  userDetail?: Record<string, any>
  isReadOnly?: boolean
}>(), {
  id: '',
  userDetail: null,
  isReadOnly: false,
})

const emit = defineEmits<{
  (e: 'photoQualityChange', type: string): void
}>()

const isInit = ref(false)
const formData = ref({} as any)
const formRefs = ref()
const upaddressRef = ref()
// 从父组件获取校验码配置键名，仅读取字符串值，不持有父级 provideParent 对象
const verificationCodeKey = (() => {
  try {
    const parent = inject<any>('provideParent', undefined)
    if (!parent) {
      return ''
    }
    if (typeof parent.verificationCodeKey === 'object' && parent.verificationCodeKey && 'value' in parent.verificationCodeKey) {
      return String(parent.verificationCodeKey.value ?? '')
    }
    return String(parent.verificationCodeKey ?? '')
  }
  catch {
    return ''
  }
})()
// 是否渲染弹框
const show = ref(false)

async function updataaddress() {
  show.value = true
  await nextTick()
  upaddressRef.value.showUpaddress()
}
function submitaddress(row) {
  Object.assign(formData.value, row)
}
function lookIdNumber() {
  showDialog({
    title: '身份证信息',
    message: formData.value.f_idnumber || '暂无身份证号',
    showCancelButton: false,
    confirmButtonText: '关闭',
  })
}
onBeforeMount(() => {
  if (props.userDetail) {
    formData.value = { ...props.userDetail.userinfo }
  }
  isInit.value = true
})
defineExpose({
  getData() {
    return formData.value
  },
  validate: async () => {
    const errors = []

    // 验证 XForm 表单
    if (formRefs.value) {
      try {
        if (typeof formRefs.value.validate === 'function') {
          await formRefs.value.validate()
        }
        else {
          await formRefs.value.submit()
        }
      }
      catch (error) {
        if (Array.isArray(error)) {
          errors.push(...error)
        }
        else if (error && error.message) {
          errors.push(error.message)
        }
        else {
          errors.push('表单验证失败')
        }
      }
    }

    // 如果有错误，抛出异常
    if (errors.length > 0) {
      return Promise.reject(errors)
    }

    return Promise.resolve()
  },
})

// 发送验证码
function sendVerificationCode() {
  try {
    const verificationCodeKeyValue = verificationCodeKey
    const form = formRefs.value.getFormData()
    if (form?.f_contact_phone && /^1[3-9]\d{9}$/.test(form?.f_contact_phone)) {
      runLogic('sendVerificationCode', { codeKey: verificationCodeKeyValue, phone: form?.f_contact_phone }, 'af-safecheck')
    }
    else {
      showToast('请输入正确的电话号码')
    }
  }
  catch (error) {
    console.error('发送验证码失败', error)
  }
}
</script>

<template>
  <XForm
    v-if="isInit"
    ref="formRefs"
    mode="新增"
    config-name="CheckUserInfoForm"
    :show-tab-header="false"
    service-name="af-safecheck"
    :form-readonly="props.isReadOnly"
    :form-data="formData"
    :is-group-form="true"
    :is-async-upload="true"
    @look="lookIdNumber"
    @upaddress="updataaddress"
    @send-verification-code="sendVerificationCode"
    @photo-quality-change="(type: string) => emit('photoQualityChange', type)"
  />
  <upaddress v-if="show" ref="upaddressRef" :address="formData" :is-read-only="props.isReadOnly" @submit="submitaddress" />
</template>

<style scoped lang="less">

</style>
