<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="dialogWidth"
    :fullscreen="dialogFullscreen"
    :scroll="dialogScroll"
    :max-height="dialogScroll ? '400px' : 'auto'"
  >
    <Preview
      ref="previewRef"
      :template="template"
      :print-data="printData"
      :mut-template-list="mutTemplateList"
      :is-mut="isMut"
      :show-line-info="showLineInfo"
    />
    <!-- <div class="settings">
      <el-input v-model="pageSize.printer" placeholder="打印机名称" />
      <el-input v-model="pageSize.name" placeholder="纸张尺寸（如：A5）" />
      <el-input v-model="pageSize.width" placeholder="纸张宽度（mm）" />
      <el-input v-model="pageSize.height" placeholder="纸张高度（mm）" />
    </div> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSilentPrint" :loading="silentPrintLoading"
          >打印</el-button
        >
        <!-- <el-button type="primary" @click="handleSilentPrint('pdf')">静默打印pdf</el-button> -->
        <!-- <el-button type="primary" @click="handleSilentPrint('emit')">pdf静默打印emit</el-button> -->
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { hiprint } from 'sv-print'
import Dialog from '@/components/Dialog/src/Dialog.vue'
import Preview from './preview.vue'
import {
  browserPrint,
  silentPrint,
  mut_browserPrint,
  mut_silentPrint,
  printFun
} from '@/utils/print'

// Props
import { withDefaults } from 'vue'

const props = withDefaults(
  defineProps<{
    title?: string
    width?: string
    fullscreen?: boolean
    scroll?: boolean
    showLineInfo?: boolean
  }>(),
  {
    title: '打印预览',
    width: '80%',
    fullscreen: true,
    scroll: true,
    showLineInfo: false
  }
)

// 响应式变量
const dialogVisible = ref(false)
const previewRef = ref<any>()
const template = ref<any>(null)
const printData = ref<any>(null)
const mutTemplateList = ref<any>([])
const dialogTitle = ref(props.title)
const dialogWidth = ref(props.width)
const dialogFullscreen = ref(props.fullscreen)
const dialogScroll = ref(props.scroll)
const isMut = ref(false)
const showLineInfo = ref(props.showLineInfo)
const silentPrintLoading = ref(false)
const pageSize = reactive({
  name: '',
  width: '',
  height: '',
  printer: ''
})
// Emits
const emit = defineEmits<{
  (e: 'close'): void
}>()

// 打开弹窗方法
const open = async (options: {
  template: any
  printData: any
  title?: string
  width?: string
  fullscreen?: boolean
  scroll?: boolean
}) => {
  // 设置模板和打印数据
  template.value = options.template
  printData.value = options.printData
  isMut.value = false
  // 打开弹窗
  dialogVisible.value = true
  // const clientInfo = hiprint.hiwebSocket.clientInfo
  // console.log('------hiwebSocket------', hiprint.hiwebSocket)
  // console.log('------客户端信息------', clientInfo)
}
// 多模板打开弹窗方法
const mutOpen = async (options: { templates: any }) => {
  mutTemplateList.value = options.templates
  isMut.value = true
  console.log(options.templates)
  // 打开弹窗
  dialogVisible.value = true
}
// 关闭弹窗方法
const close = () => {
  dialogVisible.value = false
  emit('close')
}
const printWithIframe = (html) => {
  try {
    // 1. 创建隐藏的 iframe
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    document.body.appendChild(iframe)

    // 2. 获取 iframe 的文档对象
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document

    // 3. 写入要打印的内容
    const printContent = html
    iframeDoc.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <style>
                    /* 自定义打印样式 */
                    <link rel="stylesheet" type="text/css" media="print" href="/print-lock.css" />
                    <link rel="stylesheet" href="/static/hiprint/css/hiprint.css" />
                </style>
            </head>
            <body>${printContent}</body>
            </html>
        `)
    iframeDoc.close()

    // 4. 等待 iframe 加载完成后打印
    iframe.onload = function () {
      iframe.contentWindow.print()
      // 5. 打印完成后移除 iframe
      setTimeout(() => {
        document.body.removeChild(iframe)
      }, 1000)
    }
  } catch (error) {
    console.error('打印失败：', error)
    alert('打印功能调用失败，请检查浏览器设置')
  }
}
const printSpecificArea = (className) => {
  // 保存当前页面的整个 HTML
  const originalContent = document.body.innerHTML
  try {
    // 1. 获取要打印的内容
    const printContent = document.getElementsByClassName(className)[0].innerHTML

    // 3. 将页面内容替换为要打印的内容
    document.body.innerHTML = printContent

    // 4. 调用打印功能
    window.print()

    // 5. 打印完成后恢复原页面内容
    document.body.innerHTML = originalContent

    // 6. 重新绑定事件（可选，根据页面复杂度）
    // window.location.reload() // 简单粗暴的方式，也可以针对性重新绑定
  } catch (error) {
    console.error('打印失败：', error)
    alert('打印功能调用失败，请检查浏览器设置')
    // 出错时也要恢复原页面
    document.body.innerHTML = originalContent
  }
}
// 浏览器打印方法
const handleBrowserPrint = async () => {
  // console.log(previewRef.value.processedHtml)
  // if (previewRef.value.processedHtml) {
  //   printWithIframe(previewRef.value.processedHtml)
  //   // printSpecificArea('preview-content')
  // }
  if (isMut.value) {
    await mut_browserPrint({
      templateList: mutTemplateList.value
    })
  } else {
    await browserPrint({
      template: template.value,
      printData: printData.value
    })
  }
}

// 静默打印方法
const handleSilentPrint = async (type?: string) => {
  try {
    silentPrintLoading.value = true
    setTimeout(() => {
      silentPrintLoading.value = false
    }, 5000)
    if (isMut.value) {
      await printFun({ templateList: mutTemplateList.value }, null, null, true)
    } else {
      await printFun(
        {
          template: template.value,
          printData: printData.value
        },
        null,
        null,
        false
      )
    }
  } catch (error) {
    console.error('静默打印失败:', error)
  } finally {
    setTimeout(() => {
      silentPrintLoading.value = false
    }, 5000)
  }
}

// 暴露方法给父组件
defineExpose({
  open,
  mutOpen,
  close,
  handleBrowserPrint,
  handleSilentPrint
})
</script>

<style scoped>
.settings {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 150px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}
</style>
