//居左打印
var ALIGN_LEFT = "LEFT";
//居中打印
var ALIGN_CENTER = "CENTER";
//居右打印
var ALIGN_RIGHT = "RIGHT";

/**
 * 打印
 * @param isCheckStatus 是否检测状态
 * @param cmds 打印指令
 * @param callback 打印回调
 */
function print({ isCheckStatus, cmds, callback }) {
  var targetId = null;
  my.ix.queryPrinter({
    success: (res) => {
      console.log("查询打印机成功：" + JSON.stringify(res));
      if (res.usb != null && res.usb.length != 0) {
        targetId = res.usb[0].id;
        if (isCheckStatus == true) {
          //先检测下状态
          my.ix.printerStatus({
            success: (r) => {
              console.log("printStatus success==>" + JSON.stringify(r));
              //滚去打印
              my.ix.printer({
                target: targetId,
                cmds: cmds,
                success: (res) => {
                  console.log("打印成功：" + JSON.stringify(res));
                  if (callback != null) {
                    var result = { code: 0, data: "打印成功" };
                    callback(result);
                  }
                },
                fail: (res) => {
                  console.log("打印失败：" + JSON.stringify(res));
                  if (callback != null) {
                    var result = { code: -1, data: "" + res.errorMessage };
                    callback(result);
                  }
                }
              });
            },
            fail: (r) => {
              console.log("printStatus fail==>" + JSON.stringify(r));
              if (callback != null) {
                var result = { code: -1, data: "" + r.errorMessage };
                callback(result);
              }
            }
          });
        } else {
          //滚去打印
          my.ix.printer({
            target: targetId,
            cmds: cmds,
            success: (res) => {
              console.log("打印成功：" + JSON.stringify(res));
              if (callback != null) {
                var result = { code: 0, data: "打印成功" };
                callback(result);
              }
            },
            fail: (res) => {
              console.log("打印失败：" + JSON.stringify(res));
              if (callback != null) {
                var result = { code: -1, data: "" + res.errorMessage };
                callback(result);
              }
            }
          });
        }

      } else {
        if (callback != null) {
          var result = { code: -1, data: "未连接打印机" };
          callback(result);
        }
      }
    },
    fail: (res) => {
      console.log("查询打印机失败：" + JSON.stringify(res));
      if (callback != null) {
        var result = { code: -1, data: "查询打印机失败" };
        callback(result);
      }
    }
  });
}

/**
 * 设置对齐模式
 */
function setAlign(align) {
  if (align != ALIGN_LEFT && align != ALIGN_CENTER && align != ALIGN_RIGHT) {
    //传入参数不正确，提供默认居左打印默认值
    align = ALIGN_LEFT;
  }
  return { 'cmd': 'addSelectJustification', 'args': ['' + align] };
}

/**
 * 走纸换行
 */
function feedPaper() {
  return { 'cmd': 'addPrintAndLineFeed', 'args': [] };
}

/**
 * 打印文字，内部会走纸一行
 */
function printText(text) {
  return { 'cmd': 'addText', 'args': ['' + text + "\n"] };
}

/**
 * 一行打印两文字
 */
function printTwoText(leftText, rightText) {
  console.info(`leftText: ${JSON.stringify(leftText)}` + ";rightText:" + JSON.stringify(rightText));
  var text = leftText;
  for (var i = 0; i < 38 - rightText.length - leftText.length; i++) {
    text = text + " ";
  }
  text = text + rightText;
  console.info(`text: ${JSON.stringify(text)}`);
  return { 'cmd': 'addText', 'args': ['' + text + "\n"] };
}

/**
 * 打印分割线
 */
function printDivide(divideStr) {
  var text = "";
  if (divideStr == null) {
    //给个默认的分割线
    divideStr = "=";
  }
  for (var i = 0; i < 32; i++) {
    text = text + divideStr;
  }
  return printText(text);
}

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份 
    "d+": this.getDate(),                    //日 
    "h+": this.getHours(),                   //小时 
    "m+": this.getMinutes(),                 //分 
    "s+": this.getSeconds(),                 //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds()             //毫秒 
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

/**
 * 打印当前日期，格式：yyyy-MM-dd hh:mm:ss
 */
function printNowDate() {
  return printText("日期时间：" + new Date().format("yyyy-MM-dd hh:mm:ss"));
}

module.exports.ALIGN_LEFT = ALIGN_LEFT;
module.exports.ALIGN_CENTER = ALIGN_CENTER;
module.exports.ALIGN_RIGHT = ALIGN_RIGHT;
module.exports.print = print;
module.exports.setAlign = setAlign;
module.exports.feedPaper = feedPaper;
module.exports.printText = printText;
module.exports.printDivide = printDivide;
module.exports.printNowDate = printNowDate;
module.exports.printTwoText = printTwoText;