import getLodop from '@vue2-client/services/LodopFuncs'
import hiPrintCss from './css/hiPrintCss'
import lodopCss from './css/lodopCss'

export function printHtml (type, data) {
  if (type === 'lodop') {
    return PrintByLodop(data)
  } else {
    return Promise.resolve(new Error('未知得打印类型'))
  }
}

export function printPdf (type, data) {
  if (type === 'lodop') {
    return PrintPdfByLodop(data)
  } else {
    return Promise.resolve(new Error('未知得打印类型'))
  }
}

// PDF文档来源地址或内容，字符型，可以是URL、本地路径和内容BASE64码三种方式
// 高版本 lodop 才支持， 但是需要付费，暂时放弃这种方法
function PrintPdfByLodop (pdfUrl) {
  return new Promise((resolve, reject) => {
    const lodop = getLodop()
    if (!lodop) {
      resolve()
      return
    }
    console.log(pdfUrl)
    lodop.PRINT_INIT('报表打印')
    lodop.ADD_PRINT_PDF(0, 0, '100%', '100%', pdfUrl)
    lodop.PREVIEW()
    lodop.On_Return = function (TaskID, Value) {
      switch (Value) {
        case '1':
        case true:
          resolve(Value)
          break
        case '0':
        case false:
          reject(new Error('Print error'))
          break
      }
    }
  })
}

function PrintByLodop ({
                        html,
                        top = '5mm',
                        left = '5mm',
                        width = '90%',
                        height = '80%',
                        extra,
                        preview
                      }) {
  return new Promise((resolve, reject) => {
    const lodop = getLodop()
    if (!lodop) {
      resolve()
      return
    }
    const relHtml =
      `
    <!DOCTYPE html>
       ${hiPrintCss()}
       ${lodopCss()}
       ${html}
    `
    lodop.PRINT_INIT('报表打印')
    lodop.ADD_PRINT_HTM(top, left, width, height, relHtml)

    // 支持一张纸打印多份
    for (let i = 0; i < extra.count; i++) {
      lodop.ADD_PRINT_HTM(extra.tops[i], left, width, height, relHtml)
    }
    if (lodop.CVERSION) {
      lodop.On_Return = function (TaskID, Value) {
        switch (Value) {
          case '1':
          case true:
            resolve(Value)
            break
          case '0':
          case false:
            reject(new Error('Print error'))
            break
        }
      }
      if (preview) {
        lodop.PRINT_DESIGN()
      } else {
        lodop.PRINT()
      }
    }
  })
}
