<script setup lang="ts">
import type { SignatureComponentExpose, SignatureComponentProps } from './signature'
import XSignature from '@af-mobile-client-vue3/components/data/XSignature/index.vue'
import { upload } from '@af-mobile-client-vue3/services/api/common'
import { isNativeApp } from '@af-mobile-client-vue3/utils/environment'
import { showFailToast, Field as VanField } from 'vant'
import { onMounted, ref, watch } from 'vue'
import SignatureComponent from './SignatureComponent.vue'

const props = withDefaults(defineProps<SignatureComponentProps & {
  serviceName?: string
}>(), {
  label: '用户签字',
  required: false,
  disabled: false,
  uploadMode: 'server',
  imageList: null,
  formReadonly: false,
  isAsyncUpload: false,
  serviceName: undefined,
})

const emit = defineEmits<{
  signatureComplete: [data: any]
}>()

// App / Flutter 壳走原生签字板；浏览器、微信等走 H5 签名
const isApp = ref(isNativeApp())
onMounted(() => {
  // 部分 WebView 桥接注入略晚于首屏，挂载后再判一次
  isApp.value = isNativeApp()
})

const nativeSignatureRef = ref<InstanceType<typeof SignatureComponent>>()
const webSignatureImage = ref('')
const webSignatureData = ref<any>(null)
const webUploading = ref(false)

const serviceName = props.serviceName || import.meta.env.VITE_APP_SYSTEM_NAME

watch(
  () => props.imageList,
  (list) => {
    if (isApp.value || !Array.isArray(list) || !list[0]?.url)
      return
    webSignatureImage.value = list[0].url
  },
  { immediate: true, deep: true },
)

async function uploadWebSignature(base64Image: string) {
  const blob = await (await fetch(base64Image)).blob()
  const filename = `signature_${Date.now()}.png`
  const file = new File([blob], filename, { type: blob.type || 'image/png' })
  const formData = new FormData()
  formData.append('avatar', file)
  formData.append('resUploadMode', props.uploadMode)
  formData.append('pathKey', 'Default')
  formData.append('formType', 'image')
  formData.append('useType', 'Default')
  formData.append('resUploadStock', '1')
  formData.append('filename', filename)
  formData.append('filesize', (file.size / 1024 / 1024).toFixed(4))
  formData.append('f_operator', 'server')

  return upload(formData, serviceName, { 'Content-Type': 'multipart/form-data' })
}

function resetWebSignature() {
  webSignatureImage.value = ''
  webSignatureData.value = null
}

async function handleWebSignatureSave(base64Image: string) {
  if (props.disabled || props.formReadonly || webUploading.value)
    return

  webUploading.value = true
  try {
    const res: any = await uploadWebSignature(base64Image)
    if (!res?.data?.id) {
      showFailToast('签名上传失败')
      resetWebSignature()
      return
    }
    webSignatureData.value = res.data
    emit('signatureComplete', { status: 'success', data: res.data })
  }
  catch (error) {
    console.error('签名上传失败:', error)
    showFailToast('签名上传失败')
    resetWebSignature()
  }
  finally {
    webUploading.value = false
  }
}

function handleWebSignatureClear() {
  resetWebSignature()
  emit('signatureComplete', { base64: '', status: 'cleared' })
}

defineExpose<SignatureComponentExpose>({
  clearSignature() {
    if (isApp.value)
      nativeSignatureRef.value?.clearSignature()
    else
      handleWebSignatureClear()
  },
  hasSignature() {
    if (isApp.value)
      return nativeSignatureRef.value?.hasSignature() ?? false
    return !!webSignatureData.value?.id || !!webSignatureImage.value
  },
  getSignatureData() {
    if (isApp.value)
      return nativeSignatureRef.value?.getSignatureData() ?? ''
    return webSignatureImage.value.replace(/^data:image\/\w+;base64,/, '')
  },
  previewSignature() {
    nativeSignatureRef.value?.previewSignature()
  },
  getSignatureList() {
    if (isApp.value)
      return nativeSignatureRef.value?.getSignatureList() ?? []
    if (!webSignatureData.value)
      return []
    return [{
      photo_name: webSignatureData.value.f_filename,
      id: webSignatureData.value.id,
      f_downloadpath: webSignatureData.value.f_downloadpath,
    }]
  },
})
</script>

<template>
  <!-- App：原生签字板 -->
  <SignatureComponent
    v-if="isApp"
    ref="nativeSignatureRef"
    :label="label"
    :required="required"
    :disabled="disabled"
    :upload-mode="uploadMode"
    :image-list="imageList"
    :form-readonly="formReadonly"
    :is-async-upload="isAsyncUpload"
    @signature-complete="emit('signatureComplete', $event)"
  />
  <!-- 非 App：H5 在线签名（浏览器、微信等） -->
  <VanField
    v-else
    center
    name="signature"
    :label="label"
    :required="required"
  >
    <template #input>
      <XSignature
        v-model="webSignatureImage"
        button-text="点击签字"
        :show-button-after-signed="true"
        :show-sign-button="!formReadonly"
        :show-preview="true"
        @save="handleWebSignatureSave"
        @clear="handleWebSignatureClear"
      />
    </template>
  </VanField>
</template>
