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

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

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

// 从父组件获取 commonId，仅读取字符串值，不持有父级 provideParent 对象
const parentCommonId = (() => {
  try {
    const parent = inject<any>('provideParent', undefined)
    if (!parent) {
      return ''
    }
    if (typeof parent.commonId === 'object' && parent.commonId && 'value' in parent.commonId) {
      return String(parent.commonId.value ?? '')
    }
    return String(parent.commonId ?? '')
  }
  catch {
    return ''
  }
})()
const signatureImage = ref<string>('')
const rawBase64Data = ref<string>('') // 保存原始base64数据
const hasSignature = ref(false)
const imageList = ref<Array<any>>(props.imageList ?? [])
console.log('imageList', imageList.value)
console.log('props.imageList', props.imageList)
// 处理签字后的上传
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

  mobileUtil.execute({
    funcName: 'showSignaturePad',
    param: {},
    callbackFunc: (result: any) => {
      console.log('签字结果:', result)
      if (result.status === 'success') {
        const mimeType = getImageMimeType(result.data.filePath)
        // 保存原始base64数据
        rawBase64Data.value = result.data.base64
        const previewUrl = toDataUrl(result.data.base64, mimeType)
        signatureImage.value = previewUrl
        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: previewUrl,
          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,
        }
        if (props.isAsyncUpload) {
          // 添加上传队列
          mobileUtil.execute({
            funcName: 'queueUpload',
            param,
            callbackFunc: (res: any) => {
              console.warn('上传结果', res)
              let resStatus = 'success'
              // 成功
              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 {
                resStatus = 'error'
                // 上传失败，显示错误提示并清除图片
                const errorMessage = res.message || res.error || '上传失败，请重试'
                showToast({
                  message: errorMessage,
                  type: 'fail',
                  duration: 3000,
                })
                clearSignature()
              }
              emit('signatureComplete', {
                status: resStatus,
                data: imageList.value?.length > 0 ? imageList.value[0] : null,
              })
            },
          })
        }
        else {
          // 上传到服务器
          mobileUtil.execute({
            funcName: 'uploadResource',
            param,
            callbackFunc: (result: any) => {
              const index = imageList.value.findIndex(item => item.uid === tempFile.uid)
              if (result.status === 'success') {
                if (index !== -1) {
                  imageList.value[index].uid = result.data.id
                  imageList.value[index].id = result.data.id
                  imageList.value[index].photo_name = result.data.f_filename
                  imageList.value[index].f_downloadpath = result.data.f_downloadpath
                  delete imageList.value[index].message
                  imageList.value[index].status = 'done'
                }
              }
              else {
                // 上传失败，显示错误提示并清除图片
                const errorMessage = result.message || result.error || '上传失败，请重试'
                showToast({
                  message: errorMessage,
                  type: 'fail',
                  duration: 3000,
                })
                clearSignature()
              }
              emit('signatureComplete', {
                status: result.status,
                data: result.data,
              })
            },
          })
        }
      }
    },
  })
}

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) => { return { photo_name: item.photo_name, id: item.id, f_downloadpath: item.f_downloadpath } }),
})
</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>
