var api = require("../../utils/api.js");
import {
  ACTION_USE_COUPON, ACTION_GOODS, ACTION_MEMBER,
  ACTION_GO_BALANCE, ACTION_REQUEST_GOOD_INFO, ACTION_PRINT_RESULT,
  ACTION_REPRINT, ACTION_GO_SCAN, ACTION_ON_PAY_SUCCESS,
  ACTION_ON_PAY_FAILED, ACTION_GO_HOME,
  ACTION_DIRECT_PAYMENT, ACTION_CONVERT_COUPON, ACTION_LOGIN_OK,
  ACTION_REFUND, ACTION_REFUND_SUCCESS, ACTION_REFUND_FAILED,
  ACTION_PRINT_LAST_ORDER, ACTION_GET_CUR_AD, ACTION_SEND_SEL_AD,
  ACTION_SYSTEM_SETTING, ACTION_BALANCE_BACK_GOODS, ACTION_DAY_CHECK,
  ACTION_VERIFY, ACTION_VERIFY_SUCCESS, ACTION_VERIFY_FAILED,ACTION_PICK_UP_GOODS
} from '../../const/actioncmd'
import { FLOW_IDLE, FLOW_COLLECTIONS, FLOW_REFUND, FLOW_DIRECT_PAYMENT, FLOW_VERIFY } from '../../const/actioncmd'


Page({
  data: {
    //页面控制相关参数
    pageShow: {
      "home": true,
      "landscan": false,
      "waitoperate": false,
      "payresult": false,
      "operateresult": false,
      "printlastorder": false,
      "poster": false,
      "aboutsystem": false,
      "appsetting": false,
    },
    // 前屏是否完成登录
    isFrontScreenLoginOK: false,
    flowType: "",  //流程类型：用于区分易混淆的流程，以及共同界面使用时用该标识位作为区分

    /**账号信息 */
    storeName: "--",
    storeId: "--",
    userName: "--",
    serialNo: "--",
    containerVersion: "--",
    version: "--",
    printEnabled: true,

    /**支付结果页相关参数 */
    payFailedReason: "xxxxxxxxxxx",
    isPaySuccess: true,
    payPriceYuan: "--.--",
    printResult: "正在打印小票...",
    isPrinting: true,
    isPrintSuccess: false,
    payPriceFen: 0,
    /**商品扫码页相关参数 */

    //提货 0关闭 提货弹窗 1等待扫描提货码 2.提货码录入中 3.提货码录入成功 4.提货码录入失败
    pickGoodsState: 0,
    pickGoodsMsg: "录入失败！无效的提货码",
    pickGoods: [],  

    //优惠券 0关闭 录入券弹窗 1等待录入 2.录入中 3.录入成功 4.录入失败
    discCouponState: 0,
    discCouponMsg: "录入失败！无效的优惠券码",
    discCouponPrice: 0,

    //兑换券 0关闭兑换券弹窗 1等待兑换 2.兑换中 3.兑换成功 4.兑换失败
    convertCouponState: 0,
    convertCouponMsg: "兑换失败！无效的兑换码",

    //0代表弹窗关闭 1代表手动输入条码弹窗 2代表会员 3.收款 4.退款 
    scene: 0,
    //总数量
    totalQuantity: 0,
    //折后价格
    totalPrice: 0.00,
    //折扣
    totalDisc: 0.00,
    goods: [
    ],
    memberPhone: '',
    memberPhoneShown: '',

    //打印上一单页面
    printLastOrderPrintStatusHint: "正在打印上一单...",
    //是否打印成功
    printLastOrderIsPrintSuccess: false,
    printLastOrderIsPrinting: true,

    /** 等待操作页面的参数 */
    //左上角的显示隐藏，左下角的文字提示
    waitOperateRemindText: "等待顾客付款…",
    waitOperateCancelText: "取消收款",
    waitOperateMoneyRemind: "应收款：",
    waitOperateAmount: 0.00,
    waitOperateHideLeft: false,

    /** 操作结果页参数 */
    //在操作中携带的内容，可自定义内容,每次操作的开始和结束应当把该值给重置
    operateContext: {},
    operateSuccess: false,
    operateSuccessRemind: "退款成功",
    operateSuccessDesc: "退款完成！会在1~2个工作日返还到付款账户",
    operateFailedRemind: "退款失败",
    operateFailedDesc: "核销失败！无效的订单码",
    operateReDo: "重新退款",

    /** 重新检查的窗口 */
    recheckBlock: false,//屏蔽取消操作，防止在实际已经进行了接口请求时还能取消，使得流程混乱
    recheckShow: false,
    recheckRemind: "确定要取消此收款订单吗？",

    /**海报页面参数 */
    posterList: [
      { url: "/images/img_ad1.png", selected: true },
      { url: "/images/img_ad2.png", selected: false },
    ],
  },

  /**跳转页面方法 */
  goPage(pageName) {
    var pageShowTemp = { ...this.data.pageShow };
    //遍历pageShow
    for (var key in pageShowTemp) {
      if (key == pageName) {
        pageShowTemp[key] = true;
      } else {
        pageShowTemp[key] = false;
      }
    }
    this.setData({
      pageShow: pageShowTemp
    });
  },


  onLoad(query) {
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
    
  },
  onReady() {
    // 页面加载完成

    //获取基础信息
    let context = this;

    //小程序版本号
    this.setData({
      version: getApp().globalData.version
    })

    my.getStorage({
      key: 'printEnabled',
      success: function (res) {
        if (res == null || res.enabled == null) {
          res = { enabled: true };
        }
        context.setData({
          printEnabled: res.enabled
        })
      },
      fail: function (res) {
        console.log("打印标识位获取失败");
      }
    });

  },
  onShow() {
    // 页面显示
    let context = this;
    //开启后屏监听
    my.ix.onBuddyMessage({
      success: (res) => {
        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);

        if (res.action == ACTION_PRINT_RESULT && context.data.pageShow['payresult'] == true) {
          //获取到打印结果
          var printResultData = res.data;
          if (printResultData.code == 0) {
            //打印成功
            context.setData({
              isPrintSuccess: true,
              isPrinting: false,
              printResult: "打印成功"
            });
          } else {
            //打印失败
            context.setData({
              isPrintSuccess: false,
              isPrinting: false,
              printResult: "打印失败"
            });
          }
        } else if (res.action == ACTION_GO_HOME) {
          //重制打印状态
          this.setData({
            isPrinting: true,
            printResult: "正在打印...",
            payPriceYuan: "--.--",
            payPriceFen: 0,
          });
          //跳首页
          context.goPage('home');
          context.setData({
            flowType: FLOW_IDLE,
            operateContext: {},//重新初始化
          })
        } else if (res.action == ACTION_GOODS) {
          //商品信息同步
          my.hideLoading();
          let viewGoodsInfo = res.data
          if (viewGoodsInfo.goods != null && viewGoodsInfo.goods.length > 0) {
            context.setData({
              goods: viewGoodsInfo.goods,
              totalPrice: viewGoodsInfo.totalPrice,
              totalQuantity: viewGoodsInfo.totalQuantity,
              totalDisc: viewGoodsInfo.totalDisc,
            })
          }
        } else if (res.action == ACTION_GO_SCAN) {
          //跳转到
          context.goPage('landscan');
        } else if (res.action == ACTION_ON_PAY_SUCCESS) {

          //分转元
          var miyapay = require("/utils/miyapay4.js");

          context.setData({
            isPaySuccess: true,
            payPriceFen: res.data.tradeAmount,
            payPriceYuan: miyapay.fen2Yuan(res.data.tradeAmount) + "",
          });
          context.goPage('payresult');
        } else if (res.action == ACTION_ON_PAY_FAILED) {

          context.setData({
            isPaySuccess: false,
          });

          context.goPage('payresult');
        } else if (res.action == ACTION_DIRECT_PAYMENT) {
          //直接收款
          if (res.data != null) {
            context.setData({ waitOperateAmount: res.data })
          }
          context.goPage('waitoperate');
        } else if (res.action == ACTION_CONVERT_COUPON) {
          //兑换券
          context.setData({ convertCouponState: res.data.state })
          if (null != res.data.msg) {
            context.setData({ convertCouponMsg: res.data.msg })
          }
        } else if (res.action == ACTION_LOGIN_OK) {
          //前屏登录完成
          var loginOptions = res.data;
          var sn = loginOptions.sn;
          var account = loginOptions.account;
          var version = loginOptions.containerVersion;
          context.setData({
            isFrontScreenLoginOK: true,
            storeName: account.storeName,
            storeId: account.storeId,
            userName: account.userName,
            serialNo: sn,
            containerVersion: version,
          })
        } else if (res.action == ACTION_REFUND_SUCCESS) {
          //跳转到成功页面
          context.setData({
            operateSuccess: true,
            operateSuccessRemind: "退款成功",
            operateSuccessDesc: "退款完成！会在1~2个工作日返还到付款账户",
          });
          context.goPage('operateresult');
        } else if (res.action == ACTION_REFUND_FAILED) {
          context.setData({
            operateSuccess: false,
            operateFailedRemind: "退款失败",
            operateFailedDesc: res.data,
            operateReDo: "重新退款",
          });
          context.goPage('operateresult');
        } else if (res.action == ACTION_PRINT_LAST_ORDER && context.data.pageShow['printlastorder'] == true) {
          //打印上一单结果返回
          //获取到打印结果
          var printLastOrderResult = res.data;
          context.setData({
            printLastOrderIsPrinting: false
          });
          if (printLastOrderResult.code == 0) {
            //打印成功
            context.setData({
              printLastOrderIsPrintSuccess: true,
              printLastOrderPrintStatusHint: "打印完成"
            });
          } else {
            //打印失败
            context.setData({
              printLastOrderIsPrintSuccess: false,
              printLastOrderPrintStatusHint: "打印失败"
            });
          }
        } else if (res.action == ACTION_GET_CUR_AD) {
          //拿到当前显示的图片url
          var curAdUrl = res.data;
          //重置广告选中数据
          var tempPosterList = { ...context.data.posterList };
          for (var i = 0; i < tempPosterList.length; i++) {
            if (tempPosterList[i].url == curAdUrl) {
              tempPosterList[i].selected = true;
            } else {
              tempPosterList[i].selected = false;
            }
          }
          context.setData({
            posterList: tempPosterList
          });
          //跳转广告页面
          context.goPage('poster');
        } else if (res.action == ACTION_USE_COUPON) {
          //优惠券
          let coupon = res.data
          context.setData({
            discCouponState: coupon.discCouponState,
            discCouponMsg: coupon.discCouponMsg,
            discCouponPrice: coupon.discCouponPrice
          })
        } else if (res.action == ACTION_BALANCE_BACK_GOODS) {
          //结算页面回到扫商品页面
          context.goPage('landscan');
        } else if (res.action == ACTION_DAY_CHECK) {
          //收到日结处理回调
          var printDayCheckResult = res.data;
          if (printDayCheckResult.code == 0) {
            //打印成功
            my.showToast({ content: "打印成功" });
          } else {
            //打印失败
            my.showToast({ content: "打印失败" });
          }
          context.goPage('landscan');
        } else if (res.action == ACTION_VERIFY_SUCCESS) {
          //核验成功
          //跳转到成功页面
          context.setData({
            operateSuccess: true,
            operateSuccessRemind: "核验成功",
            operateSuccessDesc: "核销完成！请提示顾客可以离场",
          });
          context.goPage('operateresult');
        } else if (res.action == ACTION_VERIFY_FAILED) {
          context.setData({
            operateSuccess: true,
            operateSuccessRemind: "核销失败",
            operateSuccessDesc: res.data,
            operateReDo: "重新扫描",
          });
          context.goPage('operateresult');
        }else if(res.action == ACTION_PICK_UP_GOODS){
            //提货
            context.setData({pickGoods:res.data.pickGoods
            ,pickGoodsState:res.data.pickGoodsState})
        }
      }
    });

  },
  onHide() {
    // 页面隐藏
    //关闭后屏监听
    my.ix.offBuddyMessage();
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },


  //回到首页
  goHome() {
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_GO_HOME,
        data: null
      },
      success: (res) => {
        context.goPage('home');
        context.reinitData();

        console.log("通知前屏回到首页 成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("通知前屏回到首页 失败 ===》 " + JSON.stringify(res));
      },
    });
  },

  //重置部分必须重置的内容
  reinitData() {
    this.setData({
      flowType: FLOW_IDLE,
      operateContext: {},//重新初始化
      memberPhone: '',
      memberPhoneShown: '',
      waitOperateHideLeft: false,
    })
  },

  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },

  /**首页相关 */
  /**立即收款 */
  onHomeCashierImmediatelyClicked() {
    this.setData({ scene: 3, flowType: FLOW_DIRECT_PAYMENT })

  },

  /**
   * 兑换
   */
  onHomeExchangeClicked() {
    this.setData({ convertCouponState: 1 })
    this.sendConvertCouponToFront(1)
  },

  /**
   * 海报
   */
  onHomePosterClicked() {
    //发送指令至前屏，获取当前正在显示的广告页面
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_GET_CUR_AD,
        data: null
      },
      success: (res) => {
        console.log("sendBuddyMessage success:" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("sendBuddyMessage fail:" + JSON.stringify(res));
      },
    });
  },

  /**
   * 退款
   */
  onHomeRefundClicked() {
    this.setData({
      flowType: FLOW_REFUND,
      scene: 4
    })
    console.log("scene:" + this.data.scene)
  },

  /**
   * 打印上一单
   */
  onHomePrintLastOrderClicked() {
    if (this.data.printEnabled != true) {
      return;
    }
    //发送指令至前屏
    //通知前屏重新打印
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_PRINT_LAST_ORDER,
        data: null
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
    //跳转至打印上一单页面
    this.goPage('printlastorder');
  },

  /**
   * 核验
   */
  onHomeVerifyClicked() {
    this.setData({
      flowType: FLOW_VERIFY,
    })
    //跳转等待页
    this.goPage('waitoperate');
    this.setData({
      waitOperateRemindText: "请提示顾客核验订单…",
      waitOperateCancelText: "关闭",
      waitOperateHideLeft: true,
    })
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_VERIFY,
        data: null
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },

  /**
   * 提货
   */
  onHomePickUpGoodsClicked() {
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_PICK_UP_GOODS,
        data: 1
      },
      success: (sres) => {
        context.setData({ pickGoodsState: 1 })
        console.log("提货通知前屏 成功 ===》" + JSON.stringify(sres));
      },
      fail: (fres) => {
        console.log("提货通知前屏 失败 ===》 " + JSON.stringify(fres));
      }
    })
  }, 

  /**日结 */
  onHomeDayCheckClicked() {
    //发送打印日结订单到前屏
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_DAY_CHECK,
        data: null
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
        my.showToast({ content: "正在打印中" });
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },

  /**关于系统(实际上是关于应用) */
  onHomeAboutAppClicked() {
    this.goPage("aboutsystem");
  },

  /**
   * 系统设置
   */
  onHomeSysSettingClicked() {
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_SYSTEM_SETTING,
        data: null
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },

  /**
   * 应用设置
   */
  onHomeAppSettingClicked() {
    this.goPage("appsetting");

  },

  /**payresult页面逻辑方法 */
  onReprint() {
    if (this.data.printEnabled != true) {
      return;
    }
    //通知前屏重新打印
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_REPRINT,
        data: null
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },

  onNextPayFromPayResult() {
    //通知前屏跳首页
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_GO_HOME,
        data: null
      },
      success: (res) => {
        context.goPage('home');
        console.log("发送收银事件到前屏小程序 成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("发送收银事件到前屏小程序 失败 ===》 " + JSON.stringify(res));
      },
    });
  },

  //跳转到收银页面
  sendGoToCollections() {

    //首先清除数据
    this.setData({
      totalQuantity: 0,
      //折后价格
      totalPrice: 0.00,
      //折扣
      totalDisc: 0.00,
      goods: [
      ],
      discCouponState: 0,
      discCouponMsg: "",
      discCouponPrice: 0,
      
    })

    var commonRequest = {
      action: ACTION_GO_SCAN,
      data: { printEnabled: this.data.printEnabled }
    };
    var context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: commonRequest,
      success: (res) => {
        context.setData({
          flowType: FLOW_COLLECTIONS
        })

        console.log("发送收银事件到前屏小程序 成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        context.setData({
          flowType: FLOW_IDLE
        })
        console.log("发送收银事件到前屏小程序 失败 ===》 " + JSON.stringify(res));
        //发送失败重试
        // context.sendGoToCollections();
        console.log("发送收银事件到前屏小程序 ===》" + JSON.stringify(res));
      },
    });
  },


  //发生直接收银事件
  sendPaymentToFront(payment) {
    var commonRequest = {
      action: ACTION_DIRECT_PAYMENT,
      data: payment
    };
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: commonRequest,
      success: (res) => {
        console.log("发送直接收款事件到前屏小程序 成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("发送收款事件到前屏小程序 失败 ===》 " + JSON.stringify(res));
        my.showToast({
          type: 'fail',
          content: '操作失败',
          duration: 3000,
          success: () => {
          },
        });
      },
    });
  },

  /**landscan页面逻辑方法 */
  //把所有的商品数据发送到后屏
  sendGoodInfoToFront() {
    let context = this;
    var commonRequest = {
      action: ACTION_GOODS,
      data: this.data
    };
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: commonRequest,
      success: (res) => {
        console.log("发送商品数据到前屏小程序成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("发送商品数据到前屏小程序 失败 ===》 " + JSON.stringify(res));
        //发送失败重试
        context.sendGoodInfoToFront();
      }
    })
  },


  //键盘完成
  onKeyBordFinished(result) {
    if (this.data.scene == 3) {
      this.sendPaymentToFront(result)
    } else if (this.data.scene == 1) {
      this.sendGoodsInfoToFront(result)
    } else if (this.data.scene == 2) {
      if (result.length != 11) {
        return;//键盘不给消失
      }
      this.sendMemberLogin(result);
    } else if (this.data.scene == 4) {
      this.sendRefund(result);
    }
    this.onKeyBordClose();
  },

  //把手输条码发生到前屏
  sendGoodsInfoToFront(barcode) {
    my.showLoading({});
    var commonRequest = {
      action: ACTION_REQUEST_GOOD_INFO,
      data: barcode
    };
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: commonRequest,
      success: (res) => {
        console.log("发送商品条码到前屏小程序成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("发送商品条码到前屏小程序 失败 ===》 " + JSON.stringify(res));
        my.hideLoading();
        my.showToast({
          type: 'fail',
          content: '操作失败',
          duration: 3000,
          success: () => {
          },
        });
      }
    })
  },



  //  键盘关闭
  onKeyBordClose() {
    this.setData({ scene: 0 })
  },

  // 手动输入码
  manualBarcode(e) {
    this.setData({ scene: 1 })
  },

  onMemberTap() {
    this.setData({ scene: 2 })
  },

  //清空商品信息
  clearGood(e) {
    this.setData({ goods: [] })
    this.calculation([]);
  },

  //删除商品
  deleteGood(e) {
    let barcode = e.target.id;
    let lastgoods = this.data.goods;
    let newGoods = []
    lastgoods.forEach(function (item, index, array) {
      if (barcode != item.barcode) {
        newGoods.push(item);
      }
    })
    this.setData({ goods: newGoods })
    this.calculation(newGoods);

  },
  //减少商品
  decreaseGood(e) {

    let barcode = e.target.id;
    let lastgoods = this.data.goods;
    let newGoods = []
    lastgoods.forEach(function (item, index, array) {
      if (barcode == item.barcode) {
        if (item.quantity != 1) {
          let quantitytemp = item.quantity
          item.quantity = quantitytemp - 1
          newGoods.push(item);

        }
      } else {
        newGoods.push(item);
      }
    })
    this.setData({ goods: newGoods })
    this.calculation(newGoods);

  },
  //增加商品
  increaseGood(e) {
    console.log(e);
    let barcode = e.target.id;
    let lastgoods = this.data.goods;
    let newGoods = []
    lastgoods.forEach(function (item, index, array) {
      if (barcode == item.barcode) {
        let quantitytemp = item.quantity
        item.quantity = quantitytemp + 1
        newGoods.push(item);
      } else {
        newGoods.push(item);
      }
    })
    this.setData({ goods: newGoods })
    this.calculation(newGoods);
  },


  //计算总价格  总数量  总优惠
  calculation(goods) {
    let quantitytemp = 0;
    let pricetemp = 0;
    goods.forEach(function (item, index, array) {
      quantitytemp = quantitytemp + item.quantity
      pricetemp = pricetemp + item.price * item.quantity
    })
    this.setData({ totalQuantity: quantitytemp, totalPrice: pricetemp })
    //数据同步到前屏
    this.sendGoodInfoToFront()
  },


  sendMemberLogin(result) {

    this.setData({
      memberPhone: result
    })

    var phoneShown = this.data.memberPhone.substr(0, 3) + "****" + this.data.memberPhone.substr(7);
    this.setData({
      memberPhoneShown: phoneShown
    })
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_MEMBER,
        data: result
      },
      success: (res) => {
        console.log("通知前屏会员登录 成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("通知前屏会员登录 失败 ===》 " + JSON.stringify(res));
      }
    })
  },

  //跳转到结算等待页
  goPay(e) {
    //购物车不能为空 
    if (this.data.goods.length == 0) {
      my.showToast({
        type: 'fail',
        content: '等待收银员录入商品',
        duration: 3000,
        success: () => {
        },
      });
      return
    }

    //发送指令，前屏跳转
    var commonRequest = {
      action: ACTION_GO_BALANCE,
      data: ""
    };
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: commonRequest,
      success: (res) => {
        context.goPage('waitoperate');
        console.log("通知前屏跳转到结算页面 成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("通知前屏跳转到结算页面 失败 ===》 " + JSON.stringify(res));
        my.showToast({
          type: 'fail',
          content: '结算失败',
          duration: 3000,
          success: () => {
          },
        });
      }
    });

    //后屏跳转
    this.goPage('waitoperate');
    var amount = this.data.totalPrice - this.data.discCouponPrice;
    this.setData({
      waitOperateAmount: amount,
    });
  },

  waitOperateBack() {
    //直接返回到扫码页面，并且通知前屏返回
    if (this.data.flowType == FLOW_REFUND) {
      this.operateResultClose();
    } else if (this.data.flowType == FLOW_COLLECTIONS) {
      this.goPage('landscan');
      my.ix.sendBuddyMessage({
        target: getApp().globalData.frontScreenAppId,
        data: {
          action: ACTION_GO_SCAN,
          data: this.data
        },
        success: (res) => {
          console.log("通知前屏跳转到结算页面 成功 ===》" + JSON.stringify(res));
        },
        fail: (res) => {
          console.log("通知前屏跳转到结算页面 失败 ===》 " + JSON.stringify(res));
          my.showToast({
            type: 'fail',
            content: '结算失败',
            duration: 3000,
            success: () => {
            },
          });
        }
      })
    } else if (this.data.flowType == FLOW_DIRECT_PAYMENT) {
      this.goHome();
    }
  },

  //等待操作页，取消付款/收款等按钮
  waitOperateCancel() {
    //todo 是否需要加上当接口在请求时，则屏蔽取消按钮的操作？
    console.log("取消操作等待页");

    if (this.data.flowType == FLOW_COLLECTIONS) {
      this.setData({
        recheckRemind: "确定要取消此收款订单吗？",
        recheckShow: true,
      });
    } else if (this.data.flowType == FLOW_REFUND) {
      this.setData({
        recheckRemind: "确定要取消此退款订单吗？",
        recheckShow: true,
      });
    } else if (this.data.flowType == FLOW_DIRECT_PAYMENT) {
      this.setData({
        recheckRemind: "确定要取消此支付订单吗？",
        recheckShow: true,
      });
    } else if (this.data.flowType == FLOW_VERIFY) {
      //直接退出到home
      this.goHome();
    }
  },

  //提货关闭
  pickGoodsClose(e) {
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_PICK_UP_GOODS,
        data: 0
      },
      success: (sres) => {
        context.setData({ pickGoodsState: 0 })
        console.log("关闭提货通知前屏 成功 ===》" + JSON.stringify(sres));
      },
      fail: (fres) => {
        console.log("关闭提货通知前屏 失败 ===》 " + JSON.stringify(fres));
      }
    })
  },
  //兑换券界面关闭
  convertCouponClose(e) {
    this.setData({ convertCouponState: 0 })
    this.sendConvertCouponToFront(0)
  },


  //发送优惠券到前屏
  sendDiscCouponToFront(res) {
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_USE_COUPON,
        data: res
      },
      success: (sres) => {
        console.log("优惠通知前屏 成功 ===》" + JSON.stringify(sres));
      },
      fail: (fres) => {
        console.log("优惠券通知前屏 失败 ===》 " + JSON.stringify(fres));
        context.sendDiscCouponToFront(res)
      }
    })
  },

  //发生兑换券到前屏
  sendConvertCouponToFront(res) {
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_CONVERT_COUPON,
        data: res
      },
      success: (sres) => {
        console.log("兑换券通知前屏 成功 ===》" + JSON.stringify(sres));
      },
      fail: (fres) => {
        console.log("兑换券通知前屏 失败 ===》 " + JSON.stringify(fres));
      }
    })
  },

  //用券返回
  couponBack(e) {
    this.setData({ discCouponState: 0 })
    this.sendDiscCouponToFront(0)
  },
  //使用券
  useCoupon(e) {
    this.setData({ discCouponState: 1 })
    var request = {};
    request.discCouponState = 1;
    request.discCouponPrice = this.data.discCouponPrice
    this.sendDiscCouponToFront(request)
  },

  //发送退款金额.以分为单位
  sendRefund(amount) {
    var object = this.data.operateContext;
    if (amount == null) {
      if (object != null && object.refundAmount != null) {
        amount = object.refundAmount;
      } else {
        console.log("refund failed");
        return;
      }
    } else {
      object.refundAmount = amount;
    }

    this.goPage('waitoperate');
    this.setData({
      waitOperateMoneyRemind: "应退款：",
      waitOperateRemindText: "等待顾客扫描订单条码…",
      waitOperateCancelText: "取消退款",
      waitOperateAmount: amount,
    })

    //todo 修改等待操作界面的内容

    var miyapay = require("/utils/miyapay4.js");
    var refundAmount = miyapay.yuan2Fen(amount);
    console.log("amount" + refundAmount);
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_REFUND,
        data: refundAmount
      },
      success: (res) => {
        //成功发送则
        console.log("发送退款金额到前屏小程序成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        my.showToast({
          type: 'fail',
          content: '发送退款金额到前屏失败',
          duration: 3000,
          success: () => {
          },
        });
      }
    })
  },


  /**
   * 打印上一单页面
   */
  onPrintLastOrderCancelClicked() {
    //回首页
    this.setData({
      printLastOrderIsPrintSuccess: false,
      printLastOrderIsPrinting: true,
      printLastOrderPrintStatusHint: "正在打印上一单"
    });
    this.goPage('home');
  },

  onPrintLastOrderConfirmClicked() {
    //回首页
    this.setData({
      printLastOrderIsPrintSuccess: false,
      printLastOrderIsPrinting: true,
      printLastOrderPrintStatusHint: "正在打印上一单"
    });
    this.goPage('home');
  },

  onPrintLastOrderRePrintClicked() {
    //发送重新打印指令

  },

  onPrintLastOrderBackClicked() {
    //回首页
    this.setData({
      printLastOrderIsPrintSuccess: false,
      printLastOrderIsPrinting: true,
      printLastOrderPrintStatusHint: "正在打印上一单"
    });
    this.goPage('home');
  },

  //结果页面关闭
  operateResultClose() {
    this.goPage('home');
    this.setData({
      flowType: FLOW_IDLE,
    })
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_GO_HOME,
        data: null
      },
      success: (res) => {
        //成功发送则
        console.log("发送退款金额到前屏小程序成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        my.showToast({
          type: 'fail',
          content: '发送关闭前屏操作结果页失败',
          duration: 3000,
          success: () => {
          },
        });
      }
    })
  },

  //操作没成功，重新操作
  operateResultReOperate() {
    if (this.data.flowType == FLOW_REFUND) {
      //重新进行退款操作，后屏重新进入
      this.sendRefund(null);
    } else if (this.data.flowType == FLOW_VERIFY) {
      this.onHomeVerifyClicked();
    }
  },

  //重检查提示点击确定
  recheckConfirm() {
    this.setData({
      recheckShow: false,
    });
    this.goHome();
  },

  recheckCancel() {
    this.setData({
      recheckShow: false,
    });
  },

  /**
   * 海报页面逻辑
   */
  onPosterItemClicked(event) {
    console.log("event==>" + JSON.stringify(event));
    //获取点击的index
    var index = event.target.dataset.index;
    var tempList = { ...this.data.posterList };
    //遍历改变posterList状态
    for (var i = 0; i < tempList.length; i++) {
      if (i == index) {
        tempList[i].selected = true;
      } else {
        tempList[i].selected = false;
      }
    }
    var selAdUrl = tempList[index].url;
    console.log(selAdUrl);
    let context = this;
    //发送指令至前屏
    my.ix.sendBuddyMessage({
      target: getApp().globalData.frontScreenAppId,
      data: {
        action: ACTION_SEND_SEL_AD,
        data: selAdUrl
      },
      success: (res) => {
        my.showToast({
          content: "设置成功"
        });
        context.setData({
          posterList: tempList
        });
        console.log("sendBuddyMessage success:" + JSON.stringify(res));
      },
      fail: (res) => {
        my.showToast({
          content: "设置失败"
        });
        console.log("sendBuddyMessage fail:" + JSON.stringify(res));
      },
    });
  },

  // 海报返回按钮 
  onPosterPageBack(event) {
    console.log("event==>" + JSON.stringify(event));
    //回首页
    this.goPage('home');
  },

  //打印标识位
  onPrintEnabledSwitch(e) {
    this.setData({
      printEnabled: e.detail.value
    })
    console.log("checked changed，printEnabled：" + e.detail.value)

    my.setStorage({
      key: 'printEnabled',
      data: { enabled: e.detail.value },
      success: function () {
        console.log("本地数据设置完毕，printEnabled：" + e.detail.value)
      }
    });
  },

});

