<template>
  <div class="qrcode-action-card">
    <el-image
      v-if="imageUrl"
      :src="imageUrl"
      :preview-src-list="[imageUrl]"
      preview-teleported
      fit="cover"
      class="qrcode-action-card__img"
    >
      <template #error>
        <div class="qrcode-action-card__error">{{ errorText || emptyText }}</div>
      </template>
    </el-image>
    <div v-else class="qrcode-action-card__error">{{ emptyText }}</div>
    <div v-if="showActionMask" class="qrcode-action-card__mask">
      <el-button v-if="showPreview" circle :disabled="!imageUrl" @click="handlePreview">
        <Icon icon="ep:zoom-in" />
      </el-button>
      <el-button v-if="showPrint" circle :disabled="!imageUrl || printDisabled" @click="handlePrint">
        <Icon icon="ep:printer" />
      </el-button>
      <el-button
        v-if="showRefresh"
        circle
        :loading="refreshLoading"
        :disabled="refreshDisabled || refreshLoading"
        @click="handleRefresh"
      >
        <Icon icon="ep:refresh" />
      </el-button>
    </div>
  </div>
  <HiprintPreviewDialog ref="hiprintPreviewDialogRef" />
</template>

<script setup lang="ts">
import request from '@/config/axios'
import HiprintPreviewDialog from '@/components/HiprintPreviewDialog/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
import { ElLoading } from 'element-plus'

const { t } = useI18n()
const message = useMessage()

const props = withDefaults(
  defineProps<{
    imageUrl?: string
    printId?: string | number
    printTitle?: string
    emptyText?: string
    refreshUrl?: string
    refreshMethod?: 'post' | 'put' | 'get'
    refreshDisabled?: boolean
    printDisabled?: boolean
    refreshConfirmText?: string
    errorText?: string
    showPreview?: boolean
    showPrint?: boolean
    showRefresh?: boolean
    printAdaptive?: boolean
    printPaperWidth?: number
    printPaperHeight?: number
    printMaxWidth?: number
    printMaxHeight?: number
    templateJsonUrl?: string
    templateJson?: any
    printData?: Record<string, any>
  }>(),
  {
    imageUrl: '',
    printId: '',
    printTitle: '二维码打印预览',
    emptyText: '',
    refreshUrl: '',
    refreshMethod: 'post',
    refreshDisabled: false,
    printDisabled: false,
    refreshConfirmText: '',
    errorText: '',
    showPreview: true,
    showPrint: true,
    showRefresh: true,
    printAdaptive: true,
    printPaperWidth: 80,
    printPaperHeight: 80,
    printMaxWidth: 180,
    printMaxHeight: 120,
    templateJsonUrl: '',
    templateJson: undefined,
    printData: () => ({})
  }
)

const emit = defineEmits<{
  (e: 'refresh-success', data: any): void
}>()

const hiprintPreviewDialogRef = ref()
const refreshLoading = ref(false)

const showActionMask = computed(() => props.showPreview || props.showPrint || props.showRefresh)

const buildQrcodeTemplateJson = (
  qrcodeUrl: string,
  printId: string,
  imageWidth: number,
  imageHeight: number,
  paperHeight: number
) => ({
  panels: [
    {
      index: 0,
      name: 1,
      width: imageWidth,
      height: paperHeight,
      paperHeader: 0,
      paperFooter: 0,
      printElements: [
        {
          options: {
            left: 0,
            top: 0,
            width: imageWidth,
            height: imageHeight,
            src: qrcodeUrl,
            field: 'qrcodeUrl',
            title: '二维码图片',
            testData: qrcodeUrl
          },
          printElementType: {
            title: '图片',
            type: 'image'
          }
        },
        {
          options: {
            left: 0,
            top: imageHeight + 2,
            height: 10,
            width: imageWidth,
            testData: printId,
            title: 'ID',
            field: 'printId',
            textAlign: 'center',
            fontSize: 10
          },
          printElementType: {
            title: '文本',
            type: 'text'
          }
        }
      ],
      paperNumberDisabled: true,
      paperNumberContinue: true,
      watermarkOptions: {},
      panelLayoutOptions: {}
    }
  ]
})

const getImageSize = (src: string) =>
  new Promise<{ width: number; height: number }>((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const width = img.naturalWidth || img.width
      const height = img.naturalHeight || img.height
      if (!width || !height) {
        reject(new Error('invalid image size'))
        return
      }
      resolve({ width, height })
    }
    img.onerror = () => reject(new Error('image load failed'))
    img.src = src
  })

const resolvePrintSize = async (src: string) => {
  const fallbackWidth = Math.max(20, Number(props.printPaperWidth) || 80)
  const fallbackHeight = Math.max(20, Number(props.printPaperHeight) || 80)
  if (!props.printAdaptive) {
    return { width: fallbackWidth, height: fallbackHeight }
  }
  try {
    const size = await getImageSize(src)
    const ratio = size.width / size.height
    if (!Number.isFinite(ratio) || ratio <= 0) {
      return { width: fallbackWidth, height: fallbackHeight }
    }
    if (ratio >= 1) {
      const height = fallbackHeight
      const width = Math.min(Math.max(fallbackWidth, Math.round(height * ratio)), Number(props.printMaxWidth) || 180)
      return { width, height }
    }
    const width = fallbackWidth
    const height = Math.min(Math.max(fallbackHeight, Math.round(width / ratio)), Number(props.printMaxHeight) || 120)
    return { width, height }
  } catch {
    return { width: fallbackWidth, height: fallbackHeight }
  }
}

const handlePreview = () => {
  if (!props.imageUrl) return
  createImageViewer({
    zIndex: 9999999,
    urlList: [props.imageUrl]
  })
}

const replaceTemplateValues = (templateJson: any, printData: Record<string, any>) => {
  if (!templateJson?.panels) return templateJson
  
  return {
    ...templateJson,
    panels: templateJson.panels.map((panel: any) => ({
      ...panel,
      printElements: panel.printElements?.map((element: any) => {
        if (!element?.options?.qid) return element
        
        const qid = element.options.qid
        const value = printData[qid]
        
        if (value === undefined || value === null) return element
        
        const newOptions = { ...element.options }
        
        if (qid === 'qrcodeUrl') {
          newOptions.src = value
          newOptions.testData = value
        } else {
          newOptions.field = qid
          if (newOptions.testData === undefined || newOptions.testData === '') {
            newOptions.testData = String(value)
          }
        }
        
        return {
          ...element,
          options: newOptions
        }
      }) || []
    }))
  }
}

const handlePrint = async () => {
  if (!props.imageUrl || !props.showPrint) return
  
  let templateJson: any
  let printData: Record<string, any>
  
  printData = {
    qrcodeUrl: props.imageUrl,
    printId: props.printId === undefined || props.printId === null ? '' : String(props.printId),
    ...props.printData
  }
  
  if (props.templateJson) {
    templateJson = replaceTemplateValues(props.templateJson, printData)
  } else if (props.templateJsonUrl) {
    try {
      const response = await request.get({ url: props.templateJsonUrl })
      templateJson = typeof response.data === 'string' ? JSON.parse(response.data) : response.data
      templateJson = replaceTemplateValues(templateJson, printData)
    } catch (error) {
      console.error('获取打印模板失败', error)
      message.error('获取打印模板失败')
      return
    }
  } else {
    const printSize = await resolvePrintSize(props.imageUrl)
    const imageWidth = printSize.width
    const imageHeight = printSize.height
    const printId = props.printId === undefined || props.printId === null ? '' : String(props.printId)
    const idAreaHeight = printId ? 14 : 0
    const paperHeight = imageHeight + idAreaHeight
    
    templateJson = buildQrcodeTemplateJson(props.imageUrl, printId, imageWidth, imageHeight, paperHeight)
  }
  
  const paperSize = templateJson?.panels?.[0] ? {
    width: templateJson.panels[0].width,
    height: templateJson.panels[0].height
  } : { width: 80, height: 80 }
  
  hiprintPreviewDialogRef.value?.open({
    title: props.printTitle,
    printData,
    templateJson,
    withDefaultQrcodeLayout: false,
    paperSize
  })
}

const handleRefresh = async () => {
  if (!props.refreshUrl || props.refreshDisabled || !props.showRefresh) return
  try {
    await message.confirm(props.refreshConfirmText || '确认刷新二维码吗？')
  } catch {
    return
  }
  refreshLoading.value = true
  const loading = ElLoading.service({
    lock: true,
    text: t('common.loading'),
    background: 'rgba(0, 0, 0, 0.3)'
  })
  try {
    let data
    if (props.refreshMethod === 'get') {
      data = await request.get({ url: props.refreshUrl })
    } else if (props.refreshMethod === 'put') {
      data = await request.put({ url: props.refreshUrl })
    } else {
      data = await request.post({ url: props.refreshUrl })
    }
    emit('refresh-success', data)
    message.success(t('common.updateSuccess'))
  } finally {
    loading.close()
    refreshLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.qrcode-action-card {
  position: relative;
  height: 150px;
  width: fit-content;
  min-width: 150px;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-fill-color-blank);
}

.qrcode-action-card__img {
  height: 150px;
  width: auto;
  display: block;
}

.qrcode-action-card__error {
  height: 150px;
  min-width: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  font-size: 12px;
  padding: 0 12px;
}

.qrcode-action-card__mask {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  background: rgba(0, 0, 0, 0.35);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.qrcode-action-card:hover .qrcode-action-card__mask {
  opacity: 1;
}
</style>
