import confirm from 'ant-design-vue/es/modal/confirm'
import { Modal } from 'ant-design-vue'
import notification from 'ant-design-vue/es/notification'
import store from '@/store'
import { getLodop } from '@/libs/LodopFuncs'
import moment from 'moment'
// 打印页签,支持批量打印
export const JGPrintTag = function (width, height, data) {
  const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
  if (!LODOP) {
    confirm({
      title: '提示?',
      content: h => <div>打印控件未安装，请先下载并安装。安装完成后，刷新页面即可打印。</div>,
      okText: '立即下载',
      okType: 'danger',
      cancelText: '暂不打印',
      zIndex: 100000,
      onOk () {
        var agent = navigator.userAgent.toLowerCase();
        if (agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0) {
            window.open('https://iscm.360arrow.com/electron/CLodop.exe')
        }else if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) {
            window.open('https://iscm.360arrow.com/electron/CLodop.exe')
        }
      }
    })
    return
  }
  LODOP.PRINT_INITA("0mm","0mm",width,height,"标签");
  LODOP.SET_SHOW_MODE('HIDE_PAPER_BOARD', 1) //  隐藏底图上有模拟走纸板的条纹线
  LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true) // 可使输出以纸张边缘为基点
  const top = data.dealerName.length > 12 ? '5mm' : '7mm';
  const top1 = data.dealerName.length > 12 ? '17mm' : '15mm';
  const top2 = data.dealerName.length > 12 ? '29mm' : '27mm';
  // 经销商名称
  LODOP.SET_PRINT_STYLE("TextNeatRow",true);
  LODOP.SET_PRINT_STYLE("FontSize",11);
  LODOP.ADD_PRINT_TEXT(top,"5mm","50mm","10mm",data.dealerName);
  LODOP.SET_PRINT_STYLEA(0,"Alignment",2);
  LODOP.SET_PRINT_STYLEA(0,"Horient",2);
  // 货位号
  LODOP.SET_PRINT_STYLE("TextNeatRow",true);
  LODOP.SET_PRINT_STYLE("FontSize",32);
  LODOP.ADD_PRINT_TEXT(top1,"50%","28mm","15mm",data.shelfPlaceCode);
  // 产品编码
  LODOP.SET_PRINT_STYLE("TextNeatRow",true);
  LODOP.SET_PRINT_STYLE("FontSize",11);
  LODOP.ADD_PRINT_TEXT(top2,"50%","30mm","15mm",data.productCode);
  // 二维码
  LODOP.ADD_PRINT_BARCODE(top1,'7mm',90,90,"QRCode",data.qrCodeContent)
  LODOP.SET_PRINT_STYLE("QRCodeVersion",5)
  // LODOP.SET_PRINT_STYLE("QRCodeErrorLevel",'H')
  LODOP.SET_PRINT_COPIES(data.printQty)// 指定份数
  LODOP.SET_PRINT_PAGESIZE(1, width, height)
  // LODOP.PREVIEW()
  LODOP.PRINT()
}
 
export const demoGetBASE64 = function (dataArray) {
  var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  var strData = ''
  for (var i = 0, ii = dataArray.length; i < ii; i += 3) {
    if (isNaN(dataArray[i])) break
    var b1 = dataArray[i] & 0xFF; var b2 = dataArray[i + 1] & 0xFF; var b3 = dataArray[i + 2] & 0xFF
    var d1 = b1 >> 2; var d2 = ((b1 & 3) << 4) | (b2 >> 4)
    var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64
    var d4 = i + 2 < ii ? (b3 & 0x3F) : 64
    strData += digits.substring(d1, d1 + 1) + digits.substring(d2, d2 + 1) + digits.substring(d3, d3 + 1) + digits.substring(d4, d4 + 1)
  }
  return strData
}

// 导出下载excel
export const downloadExcel = function (data, fileName) {
  if (!data) { return }
  const a = moment().format('YYYYMMDDHHmmss')
  const fname = fileName + a
  const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fname + '.xlsx')
  } else {
    const link = document.createElement('a')
    link.style.display = 'none'
    var href = URL.createObjectURL(blob)
    link.href = href
    link.setAttribute('download', fname + '.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
}

/*
  *printerType: 打印机类型
  *type: 打印预览，打印，导出
  *url: 数据请求接口
  *params: 请求参数
  *fileName: 导出文件名称
  *callback: 回调函数
*/
export const hdPrint = function (printerType, type, url, params, fileName, callback) {
  // 打印时需要传打印机类型
  if (type !== 'export') {
    params.type = printerType
  }
  url(params).then(res => {
    console.log(res, type, printerType)
    if (res.type == 'application/json') {
      var reader = new FileReader()
      reader.addEventListener('loadend', function () {
        const obj = JSON.parse(reader.result)
        notification.error({
          message: '提示',
          description: obj.message
        })
      })
      reader.readAsText(res)
    } else {
      if (type == 'export') { //  导出
        downloadExcel(res, fileName)
      } else { // 打印
        const taskName = fileName+'-'+(params.sn||params.checkWarehouseSn||params.settleClientSn)+'-'
        jGPrint(res, type, printerType, taskName)
      }
    }
    callback()
  })
}

// pdf blob 转 base64
export const blobToBaseByPdf = function(data,callback){
  const reader = new FileReader()
  reader.readAsDataURL(new Blob([data], { type: 'application/pdf' }))
  reader.addEventListener('load', () => {
    callback(reader.result)
  })
}
// lodop 打印预览
export const lodopPrintView = function(data){
  const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
  LODOP.SET_SHOW_MODE('HIDE_PAPER_BOARD', 1) //  隐藏底图上有模拟走纸板的条纹线
  // LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true) // 可使输出以纸张边缘为基点
  // 预览
  const dlen = data.length
  LODOP.PRINT_INIT('')
  if(dlen > 1){
    LODOP.SET_SHOW_MODE("HIDE_PBUTTIN_PREVIEW",1);//隐藏打印按钮
  }
  LODOP.SET_PRINTER_INDEX(store.state.app.printDefNeedle)
  LODOP.ADD_PRINT_PDF(0, 0, '100%', '100%', data[0])
  LODOP.SET_PRINT_PAGESIZE(3,2090,dlen>1?0:50,"");
  LODOP.PREVIEW()
}
// 获取打印机列表
export const getPrintList = function(){
  const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
  const printCount = LODOP.GET_PRINTER_COUNT()
  const printList = []
  for(let i=0;i<printCount;i++){
    const pname = LODOP.GET_PRINTER_NAME(i)
    if(pname.indexOf('Microsoft')<0&&pname.indexOf('OneNote')<0&&pname.indexOf('Fax')<0&&pname.indexOf('导出')<0){
      printList.push({name:pname,value:i})
    }
  }
  // store.state.app.printDefNeedle = LODOP.GET_PRINTER_NAME(-1)
  return printList
}
// 获取打印机状态
export const getStatusValue = function (ValueType,ValueIndex,callback){
		const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
		if (LODOP.CVERSION) {
      LODOP.On_Return=function(TaskID,Value){
        callback(Value)
      };
    }
		var strResult=LODOP.GET_VALUE(ValueType,ValueIndex);
		if (!LODOP.CVERSION) return callback(strResult); else return callback('');
	}
// pdf 直接打印
export const pdfPrint = function (data,index){
  const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
  LODOP.SET_SHOW_MODE('HIDE_PAPER_BOARD', 1) //  隐藏底图上有模拟走纸板的条纹线
  // LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true) // 可使输出以纸张边缘为基点
  // 开始打印
  const dlen = data.length
  // 打印进入队列开始
  store.commit('SET_printLoading',true)
  LODOP.PRINT_INIT(store.state.app.printTaskName + (dlen>1 ? ('第'+(index+1)+'页') : ''))
  //这个语句设置网络共享打印机连接不通时是否提示一下
  LODOP.SET_PRINT_MODE("TRYLINKPRINTER_NOALERT",true);
  //执行该语句之后，PRINT指令不再返回那个所谓“打印成功”，才能获取到打印状态
  LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS",true);
  //TaskID:任务id，Value：job代码
  LODOP.On_Return=function(TaskID,Value){
     console.log(TaskID,Value)
     store.commit('SET_printTaskID',Value)
     if(index+1 < dlen){
       pdfPrint(data,index+1)
     }else{
       // 打印进入队列结束
       store.commit('SET_printLoading',false)
     }
  };
  console.log(store.state.app.printDefNeedle)
  // 指定打印机
  LODOP.SET_PRINTER_INDEX(store.state.app.printDefNeedle)
  LODOP.ADD_PRINT_PDF(0, 0, '100%', '100%', data[index])
  LODOP.SET_PRINT_PAGESIZE(3, 2090, (index==dlen-1)?50:0, '')
  LODOP.PRINT()
}
// 判断当前单据是否已存在打印任务列表中
 export const hasExitTaskByName = function(noCallback){
   const printTaskID = store.state.app.printTaskID
   const printLoading = store.state.app.printLoading
   if(printLoading){
     Modal.info({
       title: '提示',
       content: '打印机正在打印中...',
       okText: '知道了',
       okType: 'danger',
       centered: true,
       zIndex: 100000
     })
   }else{
     noCallback()
     // if(printTaskID){
     //   getStatusValue('PRINT_STATUS_BUSY',printTaskID,function(isExist){
     //     console.log(isExist)
     //     if(isExist.length){
     //       if(isExist != '0'){
     //         confirm({
     //           title: '提示',
     //           content: h => <div style='font-size:14px;'><div>打印机正在打印中或有未完成的打印任务</div><div>是否继续添加打印任务?</div></div>,
     //           okText: '继续打印',
     //           okType: 'danger',
     //           cancelText: '取消',
     //           centered: true,
     //           zIndex: 100000,
     //           onOk () {
     //             noCallback()
     //           }
     //         })
     //       }else{
     //         noCallback()
     //       }
     //     }
     //   })
     // }else{
     //   noCallback()
     // }
   }
 }
// 打印控件
export const jGPrint = function (data, type, printerType, taskName) {
  console.log(data,taskName)
  if (!data) {
    return
  }
  // 针式打印
  if (printerType == 'NEEDLE') {
    const LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'))
    if (!LODOP) {
      confirm({
        title: '提示?',
        content: h => <div>打印控件未安装，请先下载并安装。安装完成后，刷新页面即可打印。</div>,
        okText: '立即下载',
        okType: 'danger',
        cancelText: '暂不打印',
        onOk () {
          var agent = navigator.userAgent.toLowerCase();
          if (agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0) {
              window.open('https://iscm.360arrow.com/electron/CLodop.exe')
          }else if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) {
              window.open('https://iscm.360arrow.com/electron/CLodop.exe')
          }
        }
      })
      return
    }
    // pdf 打印预览
    if (type == 'preview') { 
      store.commit('SET_pdfPrintList', data.data)
      store.commit('SET_showPdfPrint', data.data)
      store.commit('SET_printTaskName', taskName)
    } else if (type == 'print') { //  pdf 打印
      // 选择打印机
      const printDefNeedle = store.state.app.printDefNeedle
      const hasPrint = getPrintList().find(item => item.name == printDefNeedle)
      console.log(printDefNeedle,hasPrint)
      // 已经设置默认打印机
      if(hasPrint){
        hasExitTaskByName(function () {
          pdfPrint(data.data, 0)
        })
      }else{
        // 没有设置默认打印机时，请选择打印机
        store.commit('SET_pdfPrintList', data.data)
        store.commit('SET_printTaskName', taskName)
        store.commit('SET_printUseing', 1)
        store.commit('SET_showSelectPrint', true)
      }
    }
  } else {
    // 喷墨打印
    const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
    document.getElementById('print').innerHTML = '<iframe id="printfsqd" name="printfsqd" src="' + url + '" hidden></iframe>'
    if (type == 'preview') { //  预览
      window.open(url)
    } else if (type == 'print') { //  打印
      window.frames['printfsqd'].focus()
      window.frames['printfsqd'].print()
    }
  }
}