<script setup lang="ts">
import {
  showImagePreview,
  showToast,
  Button as VanButton,
  Icon as VanIcon,
  Popup as VanPopup,
  Signature as VanSignature,
} from 'vant'
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'

interface Props {
  /** 签名图片的 base64 字符串 */
  modelValue?: string
  /** 签名笔画的宽度，默认为 3 */
  lineWidth?: number
  /** 签名笔画的颜色，默认为黑色 '#000' */
  strokeStyle?: string
  /** 签名画布的背景颜色，默认为白色 '#fff' */
  backgroundColor?: string
  /** 未签名时按钮显示的文字，默认为 '签名' */
  buttonText?: string
  /** 自定义 CSS 类名 */
  customClass?: string
  /** 是否隐藏底部按钮组，默认为 false */
  hideButtons?: boolean
  /** 按钮尺寸，可选值为 'small' | 'normal' | 'large'，默认为 'normal' */
  buttonSize?: 'small' | 'normal' | 'large'
  /** 确认按钮文字，默认为 '确认' */
  confirmButtonText?: string
  /** 清除按钮文字，默认为 '清除' */
  clearButtonText?: string
  /** 是否显示签名预览图，默认为 true */
  showPreview?: boolean
  /** 签名完成后是否显示重新签名按钮，默认为 false */
  showButtonAfterSigned?: boolean
  /** 是否显示签名按钮，默认为 true */
  showSignButton?: boolean
}

withDefaults(defineProps<Props>(), {
  modelValue: '',
  lineWidth: 3,
  strokeStyle: '#000',
  backgroundColor: '#fff',
  buttonText: '签名',
  customClass: '',
  hideButtons: false,
  buttonSize: 'normal',
  confirmButtonText: '确认',
  clearButtonText: '清除',
  showPreview: true,
  showButtonAfterSigned: false,
  showSignButton: true,
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
  'save': [image: string]
  'clear': []
}>()

interface SignatureResult {
  image: string
}

const showSignature = ref(false)

function onSubmit({ image }: SignatureResult) {
  if (!image) {
    showToast('获取签名失败')
    return
  }
  emit('update:modelValue', image)
  emit('save', image)
  showSignature.value = false
}

function onClear() {
  emit('update:modelValue', '')
  emit('clear')
  showSignature.value = false
}

const signatureRef = ref()

function handleSubmit() {
  try {
    signatureRef.value?.submit()
  }
  catch (error) {
    showToast('签名提交失败')
    console.error('Signature submit error:', error)
  }
}

const popupStyle = computed(() => ({
  width: '100%',
  height: window.innerHeight > window.innerWidth ? 'auto' : '100%',
}))

function handleOrientationChange() {
  if (showSignature.value) {
    nextTick(() => {
      signatureRef.value?.resize()
    })
  }
}
function handlePreviewClick(image: string) {
  console.log('image:', image)
  if (image.startsWith('data:image')) {
    // base64 图片：打开签名面板进行编辑
    showSignature.value = true
  }
  else {
    // 外部图片路径：只显示图片预览，不打开签名面板
    showImagePreview({
      images: [image],
      startPosition: 0,
    })
  }
}
onMounted(() => {
  window.addEventListener('orientationchange', handleOrientationChange)
})

onBeforeUnmount(() => {
  window.removeEventListener('orientationchange', handleOrientationChange)
})
// 暴露方法给父组件
defineExpose({
  openSignature() {
    showSignature.value = true
  },
})
</script>

<template>
  <div class="x-signature" role="application" aria-label="签名面板">
    <div class="signature-content">
      <div v-if="modelValue && showPreview" class="signature-preview" @click="handlePreviewClick(modelValue)">
        <img :src="modelValue" alt="签名预览">
      </div>
      <VanButton
        v-if="showSignButton && (!modelValue || showButtonAfterSigned)"
        type="primary"
        size="small"
        aria-label="打开签名面板"
        @click="showSignature = true"
      >
        {{ modelValue ? '重新签名' : buttonText }}
      </VanButton>
    </div>

    <VanPopup v-model:show="showSignature" class="signature-popup" :style="popupStyle">
      <div class="signature-wrapper">
        <VanSignature
          ref="signatureRef"
          :line-width="lineWidth"
          :stroke-style="strokeStyle"
          :background-color="backgroundColor"
          @submit="onSubmit"
          @clear="onClear"
        />
        <!-- 自定义浮动按钮，仅在横屏时显示 -->
        <div class="custom-buttons">
          <VanButton round size="small" aria-label="清除签名" @click="onClear">
            <VanIcon name="delete" />
          </VanButton>
          <VanButton round type="primary" size="small" @click="handleSubmit">
            <VanIcon name="success" />
          </VanButton>
        </div>
      </div>
    </VanPopup>
  </div>
</template>

<style scoped lang="less">
.x-signature {
  width: 100%;

  .signature-content {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .signature-preview {
    flex: 1;
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      max-width: 100%;
      max-height: 80px;
      height: auto;
      display: block;
      margin: 0 auto;
    }
  }

  .van-button {
    flex-shrink: 0;
  }

  :deep(.van-popup) {
    max-width: none !important;
    width: 100% !important;
    top: 20% !important;
    transform: none !important;
    transition: all 0.3s ease-in-out;
  }

  .signature-wrapper {
    width: 100%;
    height: 100%;
    position: relative;

    :deep(.van-signature) {
      width: 100% !important;
      height: 100% !important;
      max-width: none !important;
    }

    // 默认隐藏自定义按钮
    .custom-buttons {
      display: none;
    }
  }

  // 横屏模式样式
  @media screen and (orientation: landscape) {
    :deep(.van-popup) {
      top: 0 !important;
      right: 0 !important;
      bottom: 0 !important;
      left: 0 !important;
      width: 100% !important;
      height: 100% !important;
      display: flex;
      flex-direction: column;
    }

    .signature-wrapper {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);

      :deep(.van-signature) {
        // 隐藏原有的底部按钮
        .van-signature__footer {
          display: none;
        }
      }

      :deep(.van-signature__content) {
        height: 95% !important;
      }

      // 显示自定义浮动按钮
      .custom-buttons {
        position: absolute;
        right: 32px;
        bottom: 32px;
        display: flex;
        gap: 16px;

        .van-button {
          width: 48px !important;
          height: 48px !important;
          border-radius: 50% !important;
          padding: 0 !important;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
          transition: transform 0.2s ease;

          &--default {
            background: #fff;
          }

          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
  }

  // 优化按钮触摸反馈
  .custom-buttons {
    .van-button {
      transition: transform 0.2s ease;

      &:active {
        transform: scale(0.95);
      }
    }
  }
}
</style>
