import { hiprint } from 'sv-print'
import { toRaw, ref, h, onMounted, createApp } from 'vue'
import { ElMessage, ElLoading, ElDialog, ElSelect, ElOption, ElButton } from 'element-plus'
import { initWebSocket, getWsInstance, destroyWebSocket } from '@/utils/websocket'
import { useFontStore } from '@/store/modules/font'
import pluginApiPdf from '@sv-print/plugin-api-pdf3'
import pluginApiImage from '@sv-print/plugin-api-image'
import pluginEleBwip from "@sv-print/plugin-ele-bwip-js";
import pluginTextAuto from '@sv-print/plugin-text-auto'
hiprint.register({
  authKey: '53616C7465645F5F286B418F99190EA3DC1F152B8B1B393ECD4C3D064C735A6A',
  plugins: [
    pluginApiPdf(), // 插件参数
    pluginApiImage(), // 插件参数
    pluginTextAuto({
      sizeList: [10, 9, 8, 7, 6, 5], // 适应最小字体选项
      maxIterations: 15, // 适应次数
      enablePrecision: true, // 启用精确适应
      precision: 0.5, // 适应精确step
      precisionCount: 10, // 适应精确次数
      lineHeightMode: 'auto', // 行高模式 auto | original | normal | unset
      overrideHidden: false, // 超出是否隐藏
      extendsCss: {
        // 扩展css
        'word-wrap': 'break-word' // 单词换行
      }
    }), // 插件参数
    pluginEleBwip({})
  ]
})
const printExeApiUrl = `http://${window.location.hostname}:${import.meta.env.VITE_PRINT_EXE_API_URL}`
interface PrintOptions {
  template: any
  printData: any
}
let printLoading = false
// 使用全局的socketOpen变量
declare global {
  interface Window {
    socketOpen: boolean
  }
}
// 通用WebSocket请求方法
const sendWebSocketRequest = (
  requestType: string,
  responseType: string,
  timeoutMessage: string,
  data?: any
) => {
  // 使用全局WebSocket实例
  const ws = getWsInstance()
  return new Promise((resolve, reject) => {
    // 检查WebSocket连接状态
    if (ws.readyState !== WebSocket.OPEN) {
      reject(new Error('WebSocket连接未建立'))
      return
    }

    const handleMessage = (event: MessageEvent) => {
      console.log(`收到${responseType}消息:`, event.data)
      try {
        const data = JSON.parse(event.data)
        console.log('解析后的数据:', data)
        if (data.Type === responseType) {
          ws.removeEventListener('message', handleMessage)
          resolve(data)
        }
        if (data.Type === 'error' || data.Type === 'Error' || !data.Success) {
          ws.removeEventListener('message', handleMessage)
          reject(new Error(data.Error?.Message || data.Data.Message || '打印失败'))
        }
      } catch (parseError) {
        console.error(`解析${responseType}消息失败:`, parseError)
      }
    }

    ws.addEventListener('message', handleMessage)

    console.log(`发送${requestType}请求`)
    ws.send(
      JSON.stringify({
        ...data
      })
    )

    // 超时处理
    setTimeout(() => {
      ws.removeEventListener('message', handleMessage)
      reject(new Error(timeoutMessage))
    }, 10000)
  })
}
const browserPrintFun = async (options: PrintOptions) => {
  const { template, printData } = options

  if (!template || !printData) {
    return
  }

  try {
    template.panels[0].printElements.forEach((element) => {
      if (element.printElementType.type === 'text' || element.printElementType.type === 'longText') {
        element.options.styler = `function(value, options, target,templateData,paperNo,rootData){ return { wordBreak:'normal', whiteSpace:'normal' }; }`
      }
    })
    // console.log('template:', template)
    const printTemplate = new hiprint.PrintTemplate({
      template: template
    })
    await printTemplate.print(printData,{}, {
      styleHandler: () => {
        let fontStyles = localStorage.getItem('fontStyles') || ''
        
        const fontFamilyMap = new Map<string, string>()
        const fontFaceRegex = /@font-face\s*\{[^}]*font-family:\s*'([^']+)';[^}]*src:\s*url\([^)]+\)[^}]*\}/g
        let match
        while ((match = fontFaceRegex.exec(fontStyles)) !== null) {
          fontFamilyMap.set(match[1], match[0])
        }
        
        const uniqueFontFaces = Array.from(fontFamilyMap.values())
        fontStyles = uniqueFontFaces.join('\n')
        
        // console.log('fontStyles from localStorage:', fontStyles)
        return `
          <style>
            ${fontStyles}
          </style>
        `
      }
    })
  } catch (error) {
    console.error('浏览器打印失败:', error)
  }
}
const mut_browserPrintFun = async (options: PrintOptions) => {
  const { templateList } = options
  const templates = []
  for (const item of templateList) {
    // console.log('item.templateJson:', item.templateJson)
    item.templateJson.panels[0].printElements.forEach((element) => {
      if (element.printElementType.type === 'text' || element.printElementType.type === 'longText') {
        element.options.styler = `function(value, options, target,templateData,paperNo,rootData){ return { wordBreak:'normal', whiteSpace:'normal' }; }`
      }
    })
    // 创建模板对象
    const printTemplate = new hiprint.PrintTemplate({
      template: item.templateJson
    })
    templates.push({
      template: printTemplate,
      data: item.printData
    })
  }
  try {
    // 多模板直接打印
    await hiprint.print(
      { 
        templates
      },
      {
        styleHandler: () => {
          let fontStyles = localStorage.getItem('fontStyles') || ''
          const fontFamilyMap = new Map<string, string>()
          const fontFaceRegex = /@font-face\s*\{[^}]*font-family:\s*'([^']+)';[^}]*src:\s*url\([^)]+\)[^}]*\}/g
          let match
          while ((match = fontFaceRegex.exec(fontStyles)) !== null) {
            fontFamilyMap.set(match[1], match[0])
          }
          
          const uniqueFontFaces = Array.from(fontFamilyMap.values())
          fontStyles = uniqueFontFaces.join('\n')
          
          // console.log('fontStyles from localStorage:', fontStyles)
          return `
            <style>
              ${fontStyles}
            </style>
          `
        }
      },
      function (data) {
        // console.log('操作成功', data)
      },
      function (e) {
        console.log('打印失败', e)
      }
    )
  } catch (error) {
    console.error('浏览器打印失败:', error)
  }
}
const silentPrintFun = async (
  options: PrintOptions,
  pageSize?: { name: string; width: number; height: number },
  type?: string
) => {
  const { template, printData } = options
  if (!template || !printData) {
    return
  }

  try {
    const printTemplate = new hiprint.PrintTemplate({
      template: template
    })
    const result = await printTemplate.print2(printData)
    // console.log('静默打印结果:', result)
    if (result.success) {
      ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
    // const pageWidth = template.panels[0].paperList.width * 1000
    // const pageHeight = template.panels[0].paperList.height * 1000
    // const top = template.panels[0].paperList.topOffset * 0.35 || 0
    // const left = template.panels[0].paperList.leftOffset * 0.35 || 0
    // const printOptions = {
    //   margins: {
    //     top,
    //     left
    //   }
    // }
    // if (type == 'pdf') {
    //   if (pageSize && pageSize.name) {
    //     printOptions.paperName = pageSize.name
    //   }
    // } else {
    //   if (pageSize && pageSize.name) {
    //     printOptions.pageSize = pageSize.name
    //   } else if (pageSize && pageSize.width && pageSize.height) {
    //     printOptions.pageSize = { width: pageSize.width * 1000, height: pageSize.height * 1000 }
    //   } else {
    //     printOptions.pageSize = { width: pageWidth, height: pageHeight }
    //   }
    // }
    // if (pageSize && pageSize.printer) {
    //   printOptions.printer = pageSize.printer
    // }

    //  if (type === 'emit') {
    //   console.log('----hiprint-----', hiprint)
    //   const pdf = await printTemplate.toPdf({},{
    //     isDownload: false, // 不自动下载
    //     name: 'pdf名称',
    //     type: 'blob', // 默认 blob
    //   });
    //   const buffer = await pdf.arrayBuffer();
    //   console.log(buffer);
    //   hiprint.hiwebSocket.socket.emit('news',{
    //       type: 'url_pdf',
    //       paperSize: pageSize.name,
    //       pdf_path: buffer,
    //   });

    //   const jqueryObj = await printTemplate.getHtml(printData);
    //   const html = jqueryObj.html();
    //   hiprint.hiwebSocket.socket.emit('news', {
    //       // "printer": "PDFwriter",
    //       "type": "pdf",
    //       // "toNet": true, // 是否仅渲染返回 网络pdf地址
    //       "html": html,
    //       "printer": printOptions.printer,
    //       "pageSize": printOptions.pageSize,
    //       "printDialog": true,
    //       "templateId": new Date().getTime().toString(), // 用于 success，error 回调中区分是哪个模板
    //   });
    // } else {
    //   if (type === 'pdf') {
    //     printOptions.type = 'pdf'
    //     printOptions.printDialog = false
    //     console.log('printOptions:', printOptions)
    //   }
    //   const result = await printTemplate.print2(printData, printOptions)
    //   console.log('静默打印结果:', result)
    //   if (result.success) {
    //     ElMessage.success(result.msg)
    //   } else {
    //     ElMessage.error(result.msg)
    //   }
    // }
  } catch (error) {
    console.error('静默打印失败:', error)
  }
}
const silentPrintFun2 = async (
  options: PrintOptions,
  pageSize?: { name: string; width: number; height: number },
  type?: string,
  isMut
) => {
  if (isMut) {
    // 多模板打印逻辑
    const { templateList } = options
    if (!templateList) {
      return
    }
    // console.log('--------多模板打印---------', templateList)
    try {
      let resArray: any[] = []
      const Items = []
      for (const templateItem of templateList) {
        const printTemplate = new hiprint.PrintTemplate({
          template: templateItem.templateJson
        })
        // 判断printData是否是数组
        if (Array.isArray(templateItem.printData)) {
          // 数组表示多条数据，需要循环渲染获取图片的base64
          for (const dataItem of templateItem.printData) {
            await globalThis.document.fonts.ready
            const res = await printTemplate.toImage(dataItem, {
              embedFonts: true,
              isDownload: false, // 不自动下载
              name: 'test',
              limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
              type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
              pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
              quality: 1, // 默认 0.92  图片质量 0-1
              toType: 'url', // 默认 url   支持: url、blob
              onProgress: (cur, total) => {
                const percent = Math.floor((cur / total) * 100)
                // console.log('toImage 进度', percent)
              }
            })
            // console.log('base64', res[0].split(',')[1])
            resArray.push({
              base64: res[0].split(',')[1],
              Width: templateItem.templateJson.panels[0].paperList.width,
              Height: templateItem.templateJson.panels[0].paperList.height
            })
          }
        } else {
          // 非数组表示单条数据
          await globalThis.document.fonts.ready
          const res = await printTemplate.toImage(templateItem.printData, {
            embedFonts: true,
            isDownload: false, // 不自动下载
            name: 'test',
            limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
            type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
            pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
            quality: 1, // 默认 0.92  图片质量 0-1
            toType: 'url', // 默认 url   支持: url、blob
            onProgress: (cur, total) => {
              const percent = Math.floor((cur / total) * 100)
              // console.log('toImage 进度', percent)
            }
          })
          resArray = [
            {
              base64: res[0].split(',')[1],
              Width: templateItem.templateJson.panels[0].paperList.width,
              Height: templateItem.templateJson.panels[0].paperList.height
            }
          ]
        }
      }
      // console.log('toImage 导出结果数组', resArray)
      resArray.forEach((item) => {
        const obj = {
          ImageType: 'base64',
          ImageData: item.base64,
          Alignment: 0,
          Width: item.Width,
          Height: item.Height
        }
        Items.push(obj)
      })
      const response = await fetch(
        `${printExeApiUrl}/api/default-printer?apiKey=${import.meta.env.VITE_PRINT_EXE_API_KEY}`
      )
      const data = await response.json()
      // console.log('返回数据:', data)
      if (data && data.Data && data.Data.Name) {
        const pageWidth = templateList[0].templateJson.panels[0].paperList.width
        const pageHeight = templateList[0].templateJson.panels[0].paperList.height
        // 找到默认打印机
        const printRes = await fetch(`${printExeApiUrl}/api/print/batch`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            ApiKey: import.meta.env.VITE_PRINT_EXE_API_KEY,
            PrinterName: data.Data.Name,
            Items,
            Width: pageWidth,
            Height: pageHeight
          })
        })
        const resData = await printRes.json()
        // console.log('打印数据:', resData)
        if (resData.Success === true) {
          ElMessage.success('操作成功')
        } else {
          ElMessage.error('打印失败:' + resData.Data.message)
        }
      } else {
        ElMessage.error('未找到默认打印机')
      }
    } catch (error) {
      console.error('静默打印失败:', error)
    }
  } else {
    const { template, printData } = options
    if (!template || !printData) {
      return
    }
    try {
      const printTemplate = new hiprint.PrintTemplate({
        template: template
      })
      // 判断printData是否是数组
      let resArray: any[] = []
      if (Array.isArray(printData)) {
        // 数组表示多条数据，需要循环渲染获取图片的base64
        for (const dataItem of printData) {
          await globalThis.document.fonts.ready
          const res = await printTemplate.toImage(dataItem, {
            embedFonts: true,
            isDownload: false, // 不自动下载
            name: 'test',
            limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
            type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
            pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
            quality: 1, // 默认 0.92  图片质量 0-1
            toType: 'url', // 默认 url   支持: url、blob
            onProgress: (cur, total) => {
              const percent = Math.floor((cur / total) * 100)
              // console.log('toImage 进度', percent)
            }
          })
          // console.log('base64', res[0].split(',')[1])
          resArray.push(res[0].split(',')[1])
        }
      } else {
        // 非数组表示单条数据
        await globalThis.document.fonts.ready
        const res = await printTemplate.toImage(printData, {
          embedFonts: true,
          isDownload: false, // 不自动下载
          name: 'test',
          limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
          type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
          pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
          quality: 1, // 默认 0.92  图片质量 0-1
          toType: 'url', // 默认 url   支持: url、blob
          onProgress: (cur, total) => {
            const percent = Math.floor((cur / total) * 100)
            // console.log('toImage 进度', percent)
          }
        })
        resArray = [res[0].split(',')[1]]
      }
      // console.log('toImage 导出结果数组', resArray)
      const Items = []
      resArray.forEach((item) => {
        const obj = {
          ImageType: 'base64',
          ImageData: item,
          Alignment: 0
        }
        Items.push(obj)
      })
      // console.log('Items', Items)
      const response = await fetch(
        `${printExeApiUrl}/api/default-printer?apiKey=${import.meta.env.VITE_PRINT_EXE_API_KEY}`
      )
      const data = await response.json()
      // console.log('返回数据:', data)
      if (data && data.Data && data.Data.Name) {
        const pageWidth = template.panels[0].paperList.width
        const pageHeight = template.panels[0].paperList.height
        // 找到默认打印机
        const printRes = await fetch(`${printExeApiUrl}/api/print/batch`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            ApiKey: import.meta.env.VITE_PRINT_EXE_API_KEY,
            PrinterName: data.Data.Name,
            Items,
            Width: pageWidth,
            Height: pageHeight
          })
        })
        const resData = await printRes.json()
        // console.log('打印数据:', resData)
        if (resData.Success === true) {
          ElMessage.success('操作成功')
        } else {
          ElMessage.error('打印失败:' + resData.Data.message)
        }
      } else {
        ElMessage.error('未找到默认打印机')
      }
    } catch (error) {
      console.error('静默打印失败:', error)
    }
  }
}
const silentPrintFun2_socket = async (
  options: PrintOptions,
  pageSize?: { name: string; width: number; height: number },
  type?: string,
  isMut?: boolean,
  defaultPrinterName?: string
) => {
  let statsArray = []
  if (isMut) {
    // 多模板打印逻辑
    const { templateList } = options
    if (!templateList) {
      return
    }
    // console.log('--------多模板打印---------', templateList)
    // options.printData为数量大于1条的数组时，需要根据每个item的id判断是否为相同数据，如果是需要把相同数据的数量统计出来，返回一个统计后的数组对象[{data: 根据id去重的数组, copies: 数量}]
    // 根据id分组统计数量
    templateList.forEach((templateItem) => {
      templateItem.templateJson.panels[0].printElements.forEach((element) => {
        if (element.printElementType.type === 'text' || element.printElementType.type === 'longText') {
          element.options.styler = `function(value, options, target,templateData,paperNo,rootData){ return { wordBreak:'normal', whiteSpace:'normal' }; }`
        }
      })
      // console.log('templateItem:', templateItem)
      const groupedData = new Map()
      templateItem.printData.forEach(item => {
        const id = item.id
        if (groupedData.has(id)) {
          groupedData.get(id).copies++
        } else {
          groupedData.set(id, { data: toRaw(item), copies: 1 })
        }
      })
      // 转换为数组格式
      statsArray.push(Array.from(groupedData.values()))
    })
    // console.log('统计后的打印数据:', statsArray)
    try {
      let resArray: any[] = []
      const Items = []
      for (const templateItem of templateList) {
        const dataId = templateItem.printData[0].id
        const purchaseOrderItem = templateItem.printData[0].purchaseOrderItem
        const copies = templateItem.printData.length || 1
        const printTemplate = new hiprint.PrintTemplate({
          template: templateItem.templateJson
        })
        // 判断printData是否是数组
        if (Array.isArray(templateItem.printData)) {
          // 数组表示多条数据，需要循环渲染获取图片的base64
          // for (const dataItem of templateItem.printData) {
          //   const res = await printTemplate.toImage(dataItem, {
          //     isDownload: false, // 不自动下载
          //     name: 'test',
          //     limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
          //     type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
          //     pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
          //     quality: 1, // 默认 0.92  图片质量 0-1
          //     toType: 'url', // 默认 url   支持: url、blob
          //     onProgress: (cur, total) => {
          //       const percent = Math.floor((cur / total) * 100)
          //       console.log('toImage 进度', percent)
          //     }
          //   })
          //   console.log('base64', res[0].split(',')[1])
          //   resArray.push({
          //     base64: res[0].split(',')[1],
          //     Width: templateItem.templateJson.panels[0].paperList.width,
          //     Height: templateItem.templateJson.panels[0].paperList.height
          //   })
          // }
          const toImgArr = []
          for (const dataItem of statsArray) {
            toImgArr.push({
              data: dataItem[0].data,
              copies,
              dataId: dataId,
              purchaseOrderItem
            })
            // console.log('-----dataItem-----', dataItem[0])
            // const res = await printTemplate.toImage(dataItem[0].data, {
            //   isDownload: false, // 不自动下载
            //   name: 'test',
            //   limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
            //   type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
            //   pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
            //   quality: 1, // 默认 0.92  图片质量 0-1
            //   toType: 'url', // 默认 url   支持: url、blob
            //   onProgress: (cur, total) => {
            //     const percent = Math.floor((cur / total) * 100)
            //     console.log('toImage 进度', percent)
            //   }
            // })
            // resArray.push({
            //   id: dataItem[0].data.id,
            //   base64: res[0].split(',')[1],
            //   copies: dataItem[0].copies || 1,
            //   Width: templateItem.templateJson.panels[0].paperList.width,
            //   Height: templateItem.templateJson.panels[0].paperList.height
            // })
            // console.log('---resArray-----', resArray)
            // // resArray根据id去重
            // resArray = [...resArray.reduce((map, item) => {
            //   if (!map.has(item.id)) {
            //     map.set(item.id, item);
            //   }
            //   return map;
            // }, new Map()).values()];
          }
          for(let i = 0; i < toImgArr.length; i++) {
            const item = toImgArr[i]
            await globalThis.document.fonts.ready
            const res = await printTemplate.toImage(item.data, {
              embedFonts: true,
              isDownload: false, // 不自动下载
              name: 'test',
              limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
              type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
              pixelRatio: 3, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
              quality: 1, // 默认 0.92  图片质量 0-1
              toType: 'url', // 默认 url   支持: url、blob
              onProgress: (cur, total) => {
                const percent = Math.floor((cur / total) * 100)
              }
            })
            resArray.push({
              dataId: item.dataId,
              purchaseOrderItem: item.purchaseOrderItem,
              base64: res[0].split(',')[1],
              copies: item.copies || 1,
              Width: templateItem.templateJson.panels[0].paperList.width,
              Height: templateItem.templateJson.panels[0].paperList.height
            })
          }
        } else {
          // 非数组表示单条数据
          await globalThis.document.fonts.ready
          const res = await printTemplate.toImage(templateItem.printData, {
            embedFonts: true,
            isDownload: false, // 不自动下载
            name: 'test',
            limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
            type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
            pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
            quality: 1, // 默认 0.92  图片质量 0-1
            toType: 'url', // 默认 url   支持: url、blob
            onProgress: (cur, total) => {
              const percent = Math.floor((cur / total) * 100)
            }
          })
          resArray = [
            {
              base64: res[0].split(',')[1],
              copies: 1,
              Width: templateItem.templateJson.panels[0].paperList.width,
              Height: templateItem.templateJson.panels[0].paperList.height
            }
          ]
        }
      }
      // resArray根据dataId去重
      resArray = [...resArray.reduce((map, item) => {
        if (!map.has(item.dataId)) {
          map.set(item.dataId, item);
        }
        return map;
      }, new Map()).values()];
      resArray.forEach((item) => {
        const obj = {
          imageType: 'base64',
          imageData: item.base64,
          copies: item.copies,
          width: item.Width,
          height: item.Height,
          purchaseOrderItem: item.purchaseOrderItem
        }
        Items.push(obj)
      })
      // Items需要根据purchaseOrderItem排序，需要注意兼容没有purchaseOrderItem的情况
      Items.sort((a, b) => {
        if (a.purchaseOrderItem && b.purchaseOrderItem) {
          return a.purchaseOrderItem - b.purchaseOrderItem
        }
        return 0
      })
      const pageWidth = templateList[0].templateJson.panels[0].paperList.width
      const pageHeight = templateList[0].templateJson.panels[0].paperList.height
      const printRes = await sendWebSocketRequest(
        'batch_print_image',
        'batch_print_response',
        '获取状态超时',
        {
          type: 'batch_print_image',
          apiKey: import.meta.env.VITE_PRINT_EXE_API_KEY,
          data: {
            printerName: defaultPrinterName,
            items: Items,
            width: pageWidth,
            height: pageHeight
          }
        }
      )
      console.log('打印结果', printRes)
      if (printRes.Success) {
        printLoading = false
        ElMessage.success('操作成功')
      } else {
        printLoading = false
        ElMessage.error(printRes.Data.Message || '打印失败')
      }
    } catch (error) {
      printLoading = false
      console.error('静默打印失败:', error)
    }
  } else {
    if (Array.isArray(options.printData) && options.printData.length > 1) {
      // 根据id分组统计数量
      const groupedData = new Map()
      options.printData.forEach(item => {
        const id = item.id
        if (groupedData.has(id)) {
          groupedData.get(id).copies++
        } else {
          groupedData.set(id, { data: toRaw(item), copies: 1 })
        }
      })
      // 转换为数组格式
      statsArray = Array.from(groupedData.values())
    }
    const { template, printData } = options
    if (!template || !printData) {
      return
    }
    try {
      template.panels[0].printElements.forEach((element) => {
        if (element.printElementType.type === 'text' || element.printElementType.type === 'longText') {
          element.options.styler = `function(value, options, target,templateData,paperNo,rootData){ return { wordBreak:'normal', whiteSpace:'normal' }; }`
        }
      })
      const printTemplate = new hiprint.PrintTemplate({
        template: template
      })
      // 判断printData是否是数组
      let resArray: any[] = []
      if (Array.isArray(printData)) {
        // 数组表示多条数据，需要循环渲染获取图片的base64
        // for (const dataItem of printData) {
        //   const res = await printTemplate.toImage(dataItem, {
        //     isDownload: false, // 不自动下载
        //     name: 'test',
        //     limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
        //     type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
        //     pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
        //     quality: 1, // 默认 0.92  图片质量 0-1
        //     toType: 'url', // 默认 url   支持: url、blob
        //     onProgress: (cur, total) => {
        //       const percent = Math.floor((cur / total) * 100)
        //       console.log('toImage 进度', percent)
        //     }
        //   })
        //   console.log('base64', res[0].split(',')[1])
        //   resArray.push(res[0].split(',')[1])
        // }
          await globalThis.document.fonts.ready
          const res = await printTemplate.toImage(printData[0], {
            embedFonts: true,
            isDownload: false, // 不自动下载
            name: 'test',
            limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
            type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
            pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
            quality: 1, // 默认 0.92  图片质量 0-1
            toType: 'url', // 默认 url   支持: url、blob
            onProgress: (cur, total) => {
              const percent = Math.floor((cur / total) * 100)
            }
          })
          resArray.push(res[0].split(',')[1])
      } else {
        // 非数组表示单条数据
        await globalThis.document.fonts.ready
        const res = await printTemplate.toImage(printData, {
          embedFonts: true,
          isDownload: false, // 不自动下载
          name: 'test',
          limit: 10, // 默认 10  多少页为一个 图片文件, 太多 图片文件就很长
          type: 'image/jpeg', // 默认 image/jpeg   --> canvas.toDataURL(type, quality)
          pixelRatio: 2, // 图片像素比  2: 提高清晰度 默认 window.devicePixelRatio.
          quality: 1, // 默认 0.92  图片质量 0-1
          toType: 'url', // 默认 url   支持: url、blob
          onProgress: (cur, total) => {
            const percent = Math.floor((cur / total) * 100)
          }
        })
        resArray = [res[0].split(',')[1]]
      }
      const Items = []
      resArray.forEach((item) => {
        const obj = {
          imageType: 'base64',
          imageData: item,
          copies: printData.length
        }
        Items.push(obj)
      })
      const pageWidth = template.panels[0].paperList.width
      const pageHeight = template.panels[0].paperList.height
      // 找到默认打印机
      const printRes = await sendWebSocketRequest(
        'batch_print_image',
        'batch_print_response',
        '获取状态超时',
        {
          type: 'batch_print_image',
          apiKey: import.meta.env.VITE_PRINT_EXE_API_KEY,
          data: {
            printerName: defaultPrinterName,
            items: Items,
            width: pageWidth,
            height: pageHeight
          }
        }
      )
      console.log('打印结果', printRes)
      if (printRes.Success) {
        printLoading = false
        ElMessage.success('操作成功')
      }
    } catch (error) {
      printLoading = false
      console.error('静默打印失败:', error)
      // ElMessage.error('静默打印失败:' + error + `;即将为您调用浏览器打印`)
      // setTimeout(() => {
      //   if (isMut) {
      //     mut_browserPrintFun(options)
      //   } else {
      //     browserPrintFun(options)
      //   }
      // }, 1500)
    }
  }
}
const mut_silentPrintFun = async (
  options: PrintOptions,
  pageSize: { name: string; width: number; height: number },
  type?: string
) => {
  const { templateList } = options
  const templates = []
  for (const item of templateList) {
    // 创建模板对象
    const printTemplate = new hiprint.PrintTemplate({
      template: item.templateJson
    })
    const pageWidth = item.templateJson.panels[0].paperList.width * 1000
    const pageHeight = item.templateJson.panels[0].paperList.height * 1000
    const top = item.templateJson.panels[0].paperList.topOffset * 0.35 || 0
    const left = item.templateJson.panels[0].paperList.leftOffset * 0.35 || 0
    const printOptions = {
      margins: {
        top,
        left
      }
    }
    if (type == 'pdf') {
      if (pageSize && pageSize.name) {
        printOptions.paperName = pageSize.name
      }
    } else {
      if (pageSize && pageSize.name) {
        printOptions.pageSize = pageSize.name
      } else if (pageSize && pageSize.width && pageSize.height) {
        printOptions.pageSize = { width: pageSize.width * 1000, height: pageSize.height * 1000 }
      } else {
        printOptions.pageSize = { width: pageWidth, height: pageHeight }
      }
    }
    if (type === 'pdf') {
      printOptions.type = 'pdf'
      printOptions.printDialog = false
    }
    templates.push({
      template: printTemplate,
      data: item.printData,
      options: printOptions
    })
  }
  try {
    // 多模板直接打印
    const result = await hiprint.print2({ templates })
    if (result.success) {
      ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    console.error('静默打印失败:', error)
  }
}
export const printFun = async (
  options: PrintOptions,
  pageSize?: { name: string; width: number; height: number },
  type?: string,
  isMut?: boolean,
  printType?: string
) => {
  printLoading = true
  console.log('socketOpen', window.socketOpen)
  try {
    if (getWsInstance()) {
      destroyWebSocket()
    }
    await initWebSocket() // 手动调用重连方法
    window.socketOpen = true
  } catch (error) {
  }
  // 再次检查连接状态
  console.log('最新socketOpen状态:', window.socketOpen)
  if (printType === 'browser' || !window.socketOpen) {
    printLoading = false
    // 直接调用浏览器打印
    if (isMut) {
      await mut_browserPrintFun(options)
    } else {
      await browserPrintFun(options)
    }
    return
  }
  const printStatusData = await sendWebSocketRequest(
    'get_status',
    'status_response',
    '获取状态超时',
    {
      type: 'get_status',
      apiKey: `${import.meta.env.VITE_PRINT_EXE_API_KEY}`
    }
  )
  let defaultPrinterData = null
  let allPrinterData = null
  let allPrinterDataList = []
  if (printStatusData.Success) {
    allPrinterData = await sendWebSocketRequest(
      'get_printers',
      'printers_response',
      '获取所有打印机超时',
      {
        type: 'get_printers',
        apiKey: `${import.meta.env.VITE_PRINT_EXE_API_KEY}`
      }
    )
    if (allPrinterData.Success) {
      // 获取打印机列表成功
      allPrinterDataList = allPrinterData.Data || []
    } else {
      // 调用默认打印机
      defaultPrinterData = await sendWebSocketRequest(
        'get_default_printer',
        'default_printer_response',
        '获取默认打印机超时',
        {
          type: 'get_default_printer',
          apiKey: `${import.meta.env.VITE_PRINT_EXE_API_KEY}`
        }
      )
      if (!defaultPrinterData.Success) {
        printLoading = false
      }
    }
  }
  // const hiwebSocket = hiprint.hiwebSocket
  // const clientInfo = hiprint.hiwebSocket.clientInfo
  // console.log('------hiwebSocket------', hiprint.hiwebSocket)
  // console.log('------客户端信息------', clientInfo)

  // let response = null
  // console.log('---本机地址---', `${printExeApiUrl}`)
  // try {
  //   response = await fetch(
  //     `${printExeApiUrl}/api/status?apiKey=${import.meta.env.VITE_PRINT_EXE_API_KEY}`
  //   )
  //   console.log('客户端响应', response)
  // } catch (error) {
  //   console.error('无法访问打印服务:', error)
  //   response = false
  // }
  // if (response && response.statusText == 'OK') {
  //   await silentPrintFun2(options, pageSize, type, isMut)
  // } else {
  //   // 没有客户端，浏览器打印
  //   if (isMut) {
  //     await mut_browserPrintFun(options)
  //   } else {
  //     await browserPrintFun(options)
  //   }
  // }
  if (printStatusData && printStatusData.Success) {
    // await silentPrintFun2(options, pageSize, type, isMut)
    if (allPrinterDataList.length > 0) {
      const printerSelectRef = ref(null)
      const selectedPrinterValue = ref('')
      const dialogVisible = ref(true)
      
      const printerOptions = allPrinterDataList.map((item) => ({
        value: item.Name,
        label: item.Name
      }))
      
      const dialogContainer = document.createElement('div')
      document.body.appendChild(dialogContainer)
      
      let appInstance: any = null
      const state: any = {
        printerSelectRef,
        selectedPrinterValue,
        dialogVisible,
        printerOptions
      }
      
      const dialogPromise = new Promise<string>((resolve) => {
        const app = createApp({
          setup() {
            return state
          },
          render() {
            return h(
              ElDialog,
              {
                modelValue: state.dialogVisible.value,
                'onUpdate:modelValue': (val: boolean) => {
                  state.dialogVisible.value = val
                  if (!val) {
                    resolve('')
                  }
                },
                title: '请选择打印机',
                width: '400px',
                onClose: () => {
                  resolve('')
                }
              },
              {
                default: () =>
                  h(
                    'div',
                    {
                      style: {
                        padding: '20px'
                      }
                    },
                    h(
                      ElSelect,
                      {
                        ref: state.printerSelectRef,
                        modelValue: state.selectedPrinterValue.value,
                        'onUpdate:modelValue': (val: string) => {
                          state.selectedPrinterValue.value = val
                        },
                        placeholder: '请选择打印机',
                        style: {
                          width: '300px'
                        }
                      },
                      {
                        default: () =>
                          state.printerOptions.map((option: any) =>
                            h(
                              ElOption,
                              {
                                key: option.value,
                                label: option.label,
                                value: option.value
                              }
                            )
                          )
                      }
                    )
                  ),
                footer: () =>
                  h(
                    'div',
                    {
                      style: {
                        textAlign: 'right',
                        marginTop: '20px'
                      }
                    },
                    h(
                      ElButton,
                      {
                        type: 'primary',
                        onClick: () => {
                          state.dialogVisible.value = false
                          setTimeout(() => {
                            resolve(state.selectedPrinterValue.value)
                          }, 0)
                        }
                      },
                      { default: () => '确定' }
                    )
                  )
              }
            )
          }
        })
        
        app.use(ElDialog)
        app.use(ElSelect)
        app.use(ElOption)
        app.use(ElButton)
        app.mount(dialogContainer)
        
        appInstance = app
        
        setTimeout(() => {
          if (state.printerSelectRef.value) {
            state.printerSelectRef.value.focus()
          }
        }, 100)
      })
      
      const selectedPrinter = await dialogPromise
      const printName = state.selectedPrinterValue.value
      if (appInstance && appInstance.unmount) {
        appInstance.unmount()
      }
      document.body.removeChild(dialogContainer)
      if (printName) {
        await silentPrintFun2_socket(options, pageSize, type, isMut, printName)
      } else {
        await silentPrintFun2_socket(options, pageSize, type, isMut, '')
      }
    } else {
      if (defaultPrinterData && defaultPrinterData.Success && defaultPrinterData.Data.Name) {
        await silentPrintFun2_socket(options, pageSize, type, isMut, defaultPrinterData.Data.Name)
      } else {
        await silentPrintFun2_socket(options, pageSize, type, isMut, '')
      }
    }

  } else {
    printLoading = false
    // 没有客户端，浏览器打印
    if (isMut) {
      await mut_browserPrintFun(options)
    } else {
      await browserPrintFun(options)
    }
  }
}
export const browserPrint = async (options: PrintOptions) => {
  await browserPrintFun(options)
}

export const mut_browserPrint = async (options: PrintOptions) => {
  await mut_browserPrintFun(options)
}

export const silentPrint = async (
  options: PrintOptions,
  pageSize?: { name: string; width: number; height: number },
  type?: string
) => {
  await silentPrintFun(options, pageSize, type)
}

export const mut_silentPrint = async (
  options: PrintOptions,
  pageSize: { name: string; width: number; height: number },
  type?: string
) => {
  await mut_silentPrintFun(options, pageSize, type)
}
