<template>
  <el-button size="small" type="primary" :loading="loading" @click="openPrint">
    <Icon icon="ep:printer" class="mr-4px" />
    {{ buttonText }}
  </el-button>
  <HiprintPreviewDialog ref="printDialogRef" />
</template>

<script setup lang="ts">
import HiprintPreviewDialog from '@/components/HiprintPreviewDialog/index.vue'

const props = withDefaults(
  defineProps<{
    title: string
    buttonText?: string
    printData?: Record<string, any>
    templateJson?: Record<string, any>
    loadLabel?: () => Promise<{ printData: Record<string, any>; templateJson?: Record<string, any> }>
  }>(),
  {
    buttonText: '打印'
  }
)

const printDialogRef = ref()
const loading = ref(false)

const openPrint = async () => {
  loading.value = true
  try {
    const label = props.loadLabel ? await props.loadLabel() : undefined
    const printData = label?.printData || props.printData || {}
    const templateJson = label?.templateJson || props.templateJson
    printDialogRef.value?.open({
      title: props.title,
      printData,
      templateJson,
      withDefaultQrcodeLayout: !templateJson,
      paperSize: { width: 80, height: 60 }
    })
  } finally {
    loading.value = false
  }
}
</script>
