var api = require("../../utils/api.js");
var payUtils = require("../../utils/payUtils.js");
import { ACTION_GO_SCAN, ACTION_GO_HOME } from '../../const/actioncmd'
import { ACTION_ON_PAY_SUCCESS } from '../../const/actioncmd'
import { ACTION_ON_PAY_FAILED } from '../../const/actioncmd'
import { ACTION_BALANCE_BACK_GOODS } from '../../const/actioncmd'

Page({
  data: {
    goodsNum: 0,
    payPrice: 0.00,
    totalPrice: 0.00,
    couponPrice: 0.00,
    qrPayShow: false,
    list: [],
    orderNo: "",
    isPaying: false,
    //记录跳转源，默认是首页home，如果是直接收款则是direct
    from: "home"
  },

  //回退到上一个页面
  events: {
    onBack(e) {
      console.log('onBack触发');
      my.ix.sendBuddyMessage({
        // 填入目标小程序的 AppID
        target: getApp().globalData.backScreenAppId,
        data: {
          action: ACTION_BALANCE_BACK_GOODS,
          data: null
        },
        success: (res) => {
          console.log(`sendBuddyMessage success: ${JSON.stringify(res)}`);
          // e.preventDefault();
          my.navigateBack();
        },
        fail: (res) => {
          console.log(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
        }
      });
    }
  },


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

  onLoad(options) {

    console.log("balance onLoad==>" + JSON.stringify(options));
    var totalQuantity = options.totalQuantity
    var totalPrice = options.totalPrice
    var totalDisc = options.totalDisc
    this.setData({
      list: options.goods,
    });

    if (totalQuantity != null) {
      this.setData({
        goodsNum: totalQuantity,
      })
    }

    if (totalPrice != null) {
      this.setData({
        payPrice: payUtils.fen2Yuan(payUtils.yuan2Fen(totalPrice) - payUtils.yuan2Fen(totalDisc)),
        totalPrice: totalPrice,
        couponPrice: totalDisc,
      })
    }

    //如果是直接收款，则无需获取商品信息
    if (options.type != null && options.type == "direct") {
      console.log("直接收银，无需获取商品数据");
      this.setData({
        from: "direct"
      });
    } else {
      //商品数据
      let context = this;
      my.getStorage({
        key: 'goods',
        success: function (res) {
          console.log("商品信息 ===》  " + JSON.stringify(res));
          context.setData({
            list: res.data
          })
        },
        fail: function (res) {
          console.log("商品信息 ===》  " + JSON.stringify(res));
        }
      });
    }


    var speechContent = this.data.payPrice + "元";
    my.ix.speech({
      text: speechContent,
      speak: true,
      success: (r) => {
        my.ix.speech({
          text: '请刷脸或扫码支付',
          speak: true,
          success: (r) => {
          }
        })
      }
    });

    my.ix.onBuddyMessage({
      success: (res) => {
        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);
        if (res.action == ACTION_GO_SCAN) {//返回扫码页
          //增加跳转回去的内容
          my.navigateBack();
          my.ix.exitApp({ appName: 'cashier' });
        } else if (res.action == ACTION_GO_HOME) {
          //去首页
          my.reLaunch({
            url: "/pages/home/home",
          });
          //取消操作
          my.ix.exitApp({ appName: 'cashier' });
        }
      }
    });

  },

  onShow() {
    console.log("balance onShow");
    //这个界面接受事件是在onLoad，去除监听是在onUnload
  },

  onHide() {

  },

  onUnload() {
    console.log("balance onHide");
    // 页面隐藏
    //关闭后屏监听
    my.ix.offBuddyMessage();
  },

  /**
   * 支付
   */
  startPay() {
    //开始loading

    if (this.data.isPaying == true) {
      return
    }
    my.showLoading({});

    this.setData({
      isPaying: true,
    })
    //获取order
    var payAmount = payUtils.yuan2Fen(this.data.payPrice);
    payUtils.getOrder(payAmount, this.data.list, function (res) {
      if (res != null) {

        console.log("callback调用,res=" + JSON.stringify(res));
        if (res.resultCode == 1) {
          this.setData({
            orderNo: res.data
          });
          this.payWithOpenCashier(res.data);
        } else {
          this.setData({
            isPaying: false
          });
          hideLoading();
        }
      }
    }.bind(this));
  },

  /**
   * 打开收银台，进行扫码收款
   */
  payWithOpenCashier() {
    try {
      console.info("收银台版本" + my.ix.getVersionSync({
        packageName: 'zoloz.phone.android.alipay.com.dragonfly'
      }).versionName);

      //开启收银台监听
      my.ix.startApp({
        appName: "cashier",
        bizNo: this.data.orderNo,
        totalAmount: this.data.payPrice,
        success: (res) => {
          console.log("收银台启动回调 success==>" + JSON.stringify(res));
          if (res.codeType == "F") {
            this.doPay(this.data.orderNo, res.barCode);
          } else {
            this.doPay(this.data.orderNo, res.barCode);
          }
        }, fail: (res) => {
          console.log("收银台启动失败 ==>" + JSON.stringify(res));
          my.hideLoading();
          my.showToast({
            type: 'exception',
            content: api.decodeErrorMessage(res.error),
            duration: 2000
          });
          this.setData({
            isPaying: false
          });
        }
      });
      //收银台回调
      my.ix.onCashierEventReceive((res) => {
        console.log("onCashierEventReceive==>" + JSON.stringify(res));

        if (res.bizType == 'RESULT_CLOSED' || res.status == "RESULT_CLOSE") {
          console.log("收银台关闭");
          //关闭监听
          my.ix.offCashierEventReceive();
          this.setData({
            isPaying: false
          });
        } else if (res.bizType == 'RESULT_BTN_FUNCTION')
          console.log("收银台自定义按钮按下");
        else if (res.bizType == 'RESULT_MEMBER')
          console.log("支付结果页会员开卡");
        else
          console.log('RESULT: ' + res.bizType);
      });
    } catch (err) {
      console.log("收银台启动回调 异常==>" + JSON.stringify(err));
    }

  },


  //调用收款接口
  doPay(orderNo, payCode) {
    console.log("doPay调用");
    this.setData({ isPaying: true });
    //使用barCode来当面付
    var payAmount = payUtils.yuan2Fen(this.data.payPrice);
    payUtils.startPay(orderNo, payCode, payAmount, this.data.list, function (res) {
      my.hideLoading();
      console.log("支付回调  ===>" + JSON.stringify(res));
      this.setData({ isPaying: false });
      if (res == null) {
        return;
      }
      if (res.resultCode == 1) {
        //成功
        console.log("支付回调成功，跳转 ");

        if (res.data.tradeAmount != null) {
          var speechContent = "成功支付" + payUtils.fen2Yuan(res.data.tradeAmount) + "元";
          my.ix.speech({
            text: speechContent,
            speak: true,
            success: (r) => {
            }
          });
        }

        my.ix.offCashierEventReceive();
        this.saveData(this.data.list, res.data);
        //如果是直接收款，则需抹掉本地商品数据信息
        console.log("this.data.from==>" + this.data.from);
        if (this.data.from == "direct") {
          console.log("直接收款，抹掉商品数据");
          my.setStorageSync({
            key: 'paySuccessGoodsList',
            data: null
          });
          my.setStorageSync({
            key: 'goods',
            data: null
          });
        }

        my.reLaunch({
          url: '/pages/paysuccess/paysuccess?totalGoodsNum=' + this.data.goodsNum,
        });

        //发送支付成功到后屏
        my.ix.sendBuddyMessage({
          // 填入目标小程序的 AppID
          target: getApp().globalData.backScreenAppId,
          data: {
            action: ACTION_ON_PAY_SUCCESS,
            data: res.data
          },
          success: (res) => {
            console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
          },
          fail: (res) => {
            console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
          }
        });
      } else {
        console.log("支付回调失败，toast提示  ");
        my.ix.offCashierEventReceive();
        my.showToast({
          type: 'fail',
          content: res.message,
          duration: 2000
        });
        //发送支付失败到后屏
        my.ix.sendBuddyMessage({
          // 填入目标小程序的 AppID
          target: getApp().globalData.backScreenAppId,
          data: {
            action: ACTION_ON_PAY_FAILED,
            data: null
          },
          success: (res) => {
            console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
          },
          fail: (res) => {
            console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
          }
        });
      }
    }.bind(this));
  },


  /**
   * 保存最近支付成功的相关信息，每次支付成功都需刷新
   * @param paySuccessGoodsList 支付成功的商品列表信息
   * @param paySuccessResponse 支付成功响应,即云中台返回响应中的data信息
   */
  saveData(paySuccessGoodsList, paySuccessResponse) {
    my.setStorageSync({
      key: 'paySuccessGoodsList',
      data: paySuccessGoodsList
    });
    my.setStorageSync({
      key: 'paySuccessResponse',
      data: paySuccessResponse
    });
  },


});
