<script setup lang="ts">
import type { SignatureCompleteData, SignatureComponentExpose, SignatureComponentProps } from './signature'
import { mobileUtil } from '@af-mobile-client-vue3/utils/mobileUtil'
import {
  showImagePreview,
  showToast,
  Button as VanButton,
  Field as VanField,
  Icon as VanIcon,
  Image as VanImage,
} from 'vant'
import { computed, inject, ref } from 'vue'

const props = withDefaults(defineProps<SignatureComponentProps>(), {
  label: '用户签字',
  required: false,
  disabled: false,
  uploadMode: 'server',
  imageList: Array<any>,
  formReadonly: false,
})

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

const signatureImage = ref<string>('')
const rawBase64Data = ref<string>('') // 保存原始base64数据
const hasSignature = ref(false)

// 从父组件获取 commonId，仅读取一次而非持有引用
const parentCommonId = (() => {
  try {
    const parent = inject<any>('provideParent', undefined)
    return parent?.commonId?.value ?? ''
  }
  catch {
    return ''
  }
})()

const imageList = ref<Array<any>>(props.imageList ?? [])
const signatureFormData: any = inject('getSignatureData')
const isRequired = computed(() => {
  const isSignature = signatureFormData?.getSignatureData()
  return !(isSignature?.f_signature && isSignature?.f_signature !== '现场签字')
})

// 处理签字后的上传
function getImageMimeType(fileName: string): string {
  const ext = fileName.split('.').pop()?.toLowerCase()
  if (ext === 'jpg' || ext === 'jpeg')
    return 'image/jpeg'
  if (ext === 'png')
    return 'image/png'
  if (ext === 'gif')
    return 'image/gif'
  return 'image/png' // 默认
}

function handleSignature() {
  if (props.disabled)
    return
  if (!isRequired.value) {
    showToast('只有现场签字才需要签字')
    return
  }

  mobileUtil.execute({
    funcName: 'showSignaturePad',
    param: {},
    callbackFunc: (result: any) => {
      if (result.status === 'success') {
        const mimeType = getImageMimeType(result.data.filePath)
        // 保存原始base64数据
        rawBase64Data.value = result.data.base64
        // 添加base64图片前缀用于显示
        signatureImage.value = `data:${mimeType};base64,${result.data.base64}`
        hasSignature.value = true
        const tempFile = {
          uid: Date.now() + Math.random().toString(36).substr(2, 5),
          name: result.data.filePath.split('/').pop(),
          status: 'uploading',
          message: '上传中...',
          url: `data:${mimeType};base64,${result.data.base64}`,
          isImage: true,
          type: mimeType,
        }
        if (imageList.value) {
          imageList.value = [tempFile]
        }

        const param = {
          resUploadMode: props.uploadMode,
          pathKey: 'Default',
          formType: 'image',
          useType: 'Default',
          resUploadStock: '1',
          filename: tempFile.name,
          // 暂无size
          // filesize: photoData.size,
          f_operator: 'server',
          imgPath: result.data.filePath,
          urlPath: `/api/${import.meta.env.VITE_APP_SYSTEM_NAME}/resource/upload`,
          commonId: parentCommonId,
        }

        // 添加上传队列
        mobileUtil.execute({
          funcName: 'queueUpload',
          param,
          callbackFunc: (res: any) => {
            console.warn('上传结果', res)
            // 成功
            if (res.data && res.data.enqueued) {
              const index = imageList.value.findIndex(item => item.uid === tempFile.uid)
              if (index !== -1) {
                delete imageList.value[index].message
                imageList.value[index].status = 'done'
                imageList.value[index].photo_name = tempFile.name
                imageList.value[index].type = mimeType
              }
              else {
                if (index !== -1) {
                  imageList.value[index].status = 'failed'
                  imageList.value[index].message = '上传失败'
                }
              }
            }
          },
        })
        emit('signatureComplete', {
          base64: result.data.base64,
          status: result.data.status,
        })
      }
    },
  })
}

function clearSignature() {
  signatureImage.value = ''
  rawBase64Data.value = ''
  hasSignature.value = false
  imageList.value = []
  emit('signatureComplete', {
    base64: '',
    status: 'cleared',
  })
}

// 预览签字照片
function previewSignature() {
  if (imageList.value) {
    showImagePreview(imageList.value.map(item => item.url))
  }
}

// 暴露方法供父组件调用
defineExpose<SignatureComponentExpose>({
  clearSignature,
  hasSignature: () => hasSignature.value,
  getSignatureData: () => rawBase64Data.value, // 返回原始base64数据
  previewSignature,
  getSignatureList: () => imageList.value.map(item => item.photo_name),
})
</script>

<template>
  <VanField
    center
    name="signature"
    :label="label"
    :required="required"
  >
    <template #input>
      <div class="signature-container">
        <!-- 签字照片预览 -->
        <div v-if="imageList.length > 0 || hasSignature" class="signature-preview">
          <VanImage
            v-for="(item, index) in imageList"
            :key="`${item}_${index}`"
            :src="item.url"
            alt="签字照片"
            class="signature-image"
            fit="contain"
            :show-loading="true"
            :show-error="true"
            loading-icon="photo-o"
            error-icon="warning-o"
            @click="previewSignature"
          />
        </div>

        <!-- 按钮行 -->
        <div class="button-row">
          <!-- 签字按钮 -->
          <VanButton
            v-if="!props.formReadonly"
            :disabled="disabled"
            type="default"
            size="small"
            class="signature-btn dashed-btn"
            @click="handleSignature"
          >
            <VanIcon :name="hasSignature ? 'edit' : 'edit'" class="btn-icon" />
            {{ imageList.length > 0 || hasSignature ? '重签' : '点击签字' }}
          </VanButton>

          <!-- 清除按钮 -->
          <VanButton
            v-if="(imageList.length > 0 || hasSignature) && !props.formReadonly"
            type="default"
            size="small"
            class="dashed-btn clear-btn"
            @click="clearSignature"
          >
            <VanIcon name="delete" class="btn-icon" />
            清除
          </VanButton>
        </div>
      </div>
    </template>
  </VanField>
</template>

<style scoped lang="less">
.signature-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.signature-preview {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;

  .signature-image {
    max-width: 200px;
    max-height: 120px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
  }
}

// 按钮行样式
.button-row {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
}

.signature-btn {
  flex-shrink: 0;
  margin-right: auto;
}

// 虚线按钮样式
.dashed-btn {
  border: 1px dashed #1989fa !important;
  background-color: transparent !important;
  color: #1989fa !important;
  border-radius: 4px !important;

  &:hover {
    border-color: #0570d9 !important;
    color: #0570d9 !important;
  }

  &:active {
    border-color: #0366d6 !important;
    color: #0366d6 !important;
    background-color: rgba(25, 137, 250, 0.1) !important;
  }

  &:disabled {
    border-color: #c8c9cc !important;
    color: #c8c9cc !important;
    background-color: transparent !important;
  }
}

// 按钮图标样式
.btn-icon {
  margin-right: 4px;
  font-size: 14px;
}
</style>
