import { ACTION_PRINT_RESULT } from '../../const/actioncmd'
import { ACTION_REPRINT } from '../../const/actioncmd'
import { ACTION_GO_HOME } from '../../const/actioncmd'
import { ACTION_PAYSUCCESS_PAGE_BACK } from '../../const/actioncmd'

Page({

  data: {
    orderPriceYuan: "--.--",
    orderPriceFen: 0,
    couponPriceYuan: "--.--",
    couponPriceFen: 0,
    payPriceYuan: "--.--",
    payPriceFen: 0,
    totalCount: 0,
    printerStatus: "小票打印中",
    couponPriceYuan: "--.--",
    couponHint: "xxxxxx",
    couponName: "xxxxxxxx",
    couponDateDuration: "xxxx.xx.xx-xxxx.xx.xx",
    isShowCoupon: false,
    isShowPrinting: true,
    goodsList: [],
    payChannel: "未知",
    paySuccessResponse: null
  },


  onReady() {
    if (my.canIUse('hideBackHome')) {
      my.hideBackHome();
    }
  },

  onLoad(query) {
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
    //从本地获取相关数据
    this.data.goodsList = my.getStorageSync({ key: 'paySuccessGoodsList' }).data;
    console.info(`paySuccessGoodsList: ${JSON.stringify(this.data.goodsList)}`);
    this.data.paySuccessResponse = my.getStorageSync({ key: 'paySuccessResponse' }).data;
    console.info(`paySuccessResponse: ${JSON.stringify(this.data.paySuccessResponse)}`);
    //单位转换&赋值
    this.data.orderPriceFen = this.data.paySuccessResponse.tradeAmount;
    this.data.couponPriceFen = this.data.paySuccessResponse.mdiscount + this.data.paySuccessResponse.discount;
    this.data.payPriceFen = this.data.paySuccessResponse.tradeAmount - (this.data.paySuccessResponse.mdiscount + this.data.paySuccessResponse.discount);
    this.data.totalCount = query.totalGoodsNum;

    var miyapay = require("../../utils/miyapay4.js");
    this.data.orderPriceYuan = miyapay.fen2Yuan(this.data.orderPriceFen);
    this.data.couponPriceYuan = miyapay.fen2Yuan(this.data.couponPriceFen);
    this.data.payPriceYuan = miyapay.fen2Yuan(this.data.payPriceFen);

    //支付渠道 
    if (this.data.paySuccessResponse.channel == 1) {
      this.data.payChannel = "微信";
    } else if (this.data.paySuccessResponse.channel == 3) {
      this.data.payChannel = "支付宝";
    }
  },

  print() {
    //发起打印
    var printer = require("../../utils/printer.js");
    var printCallbackTemp = this.printCallback.bind(this);
    var cmds = [
      printer.setAlign(printer.ALIGN_CENTER),
      printer.printText(getApp().globalData.localAccountInfo.storeName),
      printer.setAlign(printer.ALIGN_LEFT),
      printer.printDivide("-"),
      printer.printText("门店号：" + this.data.paySuccessResponse.storeId),
      printer.printText("收银员账号：" + this.data.paySuccessResponse.operatorId),
      printer.printText("订单号：" + this.data.paySuccessResponse.tradeNo),
      printer.printNowDate(),
  
    ];

     if(null != this.data.goodsList && this.data.goodsList.length > 0){
        cmds.push(printer.printDivide("-"))  ,
        cmds.push(  printer.printText("活动商品")),
        cmds.push( printer.printText("商品名称    " + "    编码    " + "    数量"))
       for (var i = 0; i < this.data.goodsList.length; i++) {
         //循环取出商品数据
         cmds.push(printer.setAlign(printer.ALIGN_LEFT));
         cmds.push(printer.printText(this.data.goodsList[i].name));
         cmds.push(printer.printTwoText(this.data.goodsList[i].barcode, this.data.goodsList[i].quantity + ""));
       }
      }
  
    cmds.push(printer.setAlign(printer.ALIGN_LEFT));
    cmds.push(printer.printDivide("-"));
    cmds.push(printer.printText("应收金额:" + this.data.orderPriceYuan));
    cmds.push(printer.printText(this.data.payChannel + ":" + this.data.payPriceYuan));
    for (var i = 0; i < 4; i++) {
      cmds.push(printer.feedPaper());
    }
    printer.print({
      isCheckStatus: getApp().globalData.containerVersionCode > 20,
      cmds: cmds,
      callback: printCallbackTemp
    });
  },


  printCallback(res) {
    //通知后屏打印结果
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.backScreenAppId,
      data: {
        action: ACTION_PRINT_RESULT,
        data: res
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
    this.setData({
      isShowPrinting: false
    });
    if (res.code == -1) {
      //打印失败
      this.setData({
        printerStatus: "打印失败!"
      });
    } else {
      //打印成功
      this.setData({
        printerStatus: "打印完成!"
      });
    }
  },

  onShow() {
    var printEnabledLocal = my.getStorageSync({ key: 'printEnabled' }).data.enabled;
    if (printEnabledLocal == null) {
      printEnabledLocal = true;
    }

    //如果不打印小票，界面将有所变化
    if (printEnabledLocal == false) {
      this.setData({
        isShowPrinting: false,
        printerStatus: "小票打印未开启"
      });
    }

    //开启后屏监听
    my.ix.onBuddyMessage({
      success: (res) => {
        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);
        if (res.action == ACTION_REPRINT) {
          //重新打印 
          if (printEnabledLocal == true) {
            this.print();
          }
        } else if (res.action == ACTION_GO_HOME) {
          //去首页
          my.reLaunch({
            url: "/pages/home/home",
          });
        }
      }
    });
    if (printEnabledLocal == true) {
      this.print();
    }
  },

  onHide() {
    //关闭后屏监听
    my.ix.offBuddyMessage();
  },

 onUnload(){
    //清理支付数据
   my.removeStorageSync({
     key: 'paySuccessGoodsList',
   });

   my.removeStorage({
     key: 'goods',
     success: function () {
     }
   });
    
 }


});
