var api = require("../../utils/api.js");
import { API_SCAN } from '../../const/apiurl'
import { ACTION_GOODS } from '../../const/actioncmd'
import { ACTION_GO_BALANCE } from '../../const/actioncmd'
import { ACTION_REQUEST_GOOD_INFO } from '../../const/actioncmd'


Page({
  data: {
    //是否正在用券
    couponUseing: false,
    //0代表弹窗关闭 1代表手动输入条码弹窗 2代表会员 3.收款 4.退款 
    scene: 0,
    //总数量
    totalQuantity: 0,
    //折后价格
    totalPrice: 0.00,
    //折扣
    totalDisc:0.00,
    goods: [
    ]
  },
  onLoad() { },

  onShow() {
    //开启后屏监听
    let context = this;
    my.ix.onBuddyMessage({
      success: (res) => {

        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);
        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,
            })
          }
        }
      }
    });
  },

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

  //把所有的商品数据发送到后屏
  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(barcode) {

    this.onKeyBordClose();
 
    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 })
  },

  //清空商品信息
  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()
  },

  //跳转到支付结果页面
  goPay(e) {
    var commonRequest = {
      action: ACTION_GO_BALANCE,
      data: ""
    };
    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: () => {
          },
        });
      }
    })

  },

  //用券返回
  couponBack(e) {
    this.setData({ couponUseing: false })
  },
  //使用券
  useCoupon(e) {
    this.setData({ couponUseing: true })
  }






});
