import { CCPrintingAPI } from '@/utils/CCPrintingAPI.min.vue'
export function GetPrinters() {
  let cfgData = {}
  const resolveData = {
    printer: '',
    printers: []
  }
  cfgData.XAction = 'Printers'
  cfgData.XOpenId = process.env.VUE_APP_PRINTER_OPENID
  cfgData.XTokens = process.env.VUE_APP_PRINTER_TOKENS
  return new Promise((resolve, reject) => {
    CCPrintingAPI.Excute(
      cfgData,
      function(XTimeout) {},
      function(XFail) {
        reject('API可能未安装或未启动')
      },
      function(XSuccess) {
        var apiResult = JSON.parse(XSuccess.trim())
        if (apiResult.Status * 1 === 1) {
          // 获取到打印机列表
          if (apiResult.Message.length > 1) {
            for (var i = 1; i < apiResult.Message.length; i++) {
              resolveData.printers.push({
                label: apiResult.Message[i],
                value: apiResult.Message[i]
              })
            }
            // 设置上次使用的打印机
            resolveData.printer = resolveData.printers[0]
          }
        }
        resolve(resolveData)
      }
    )
  })
}

export function Print({ printer, Preview, TemplateURL, TemplateName, PrintData }) {
  var cfgData = {}
  cfgData.XAction = 'Print'
  cfgData.XOpenId = process.env.VUE_APP_PRINTER_OPENID
  cfgData.XTokens = process.env.VUE_APP_PRINTER_TOKENS

  /* 指定打印机*/
  cfgData.PrinterName = printer
  if (Preview) cfgData.Preview = Preview

  /* 模板方式，0-客户端模板，1-远程模板，
                    2-如果本地模板存在，使用本地，不存在使用远程模板，3-不使用模板*/
  cfgData.TemplateMode = '2'
  /* 远程模板URL或本地模板的文件夹*/
  // cfgData.TemplateURL = "http://img.51321.cn/web/chicore/VPrinting/API";
  // cfgData.TemplateURL = 'http://113.105.183.190:9167/bucket159'
  cfgData.TemplateURL = TemplateURL
  // cfgData.TemplateURL =  "D:\\\\";
  /* 模板文件名*/
  // cfgData.TemplateName = "183601-70X40.Lblx";
  // cfgData.TemplateName = '2024-04-10-16-10-49-1712736650022_Label3.Lblx'
  cfgData.TemplateName = TemplateName
  // cfgData.TemplateName = "Label2.Lblx";
  /* 打印数据的类型，0-数组，1-Json数组，元素为JSON对象，字段：值*/
  cfgData.PrintDataType = 1
  cfgData.PrintData = JSON.stringify(PrintData)
  /* 打印 发送给打印机进行打印*/
  return new Promise((resolve, reject) => {
    CCPrintingAPI.Excute(cfgData,
      function(XTimeout) { },
      function(XFail) {
        reject('API可能未安装或未启动')
      },
      function(XSuccess) {
        var apiResult = JSON.parse(XSuccess.trim())
        if (apiResult.Status === '1') {
          resolve(apiResult.Message)
          // document.getElementById("tipsmessage").innerHTML = apiResult.Message[0] + apiResult.Message[1];
        }
      }
    )
  })
}
