var api = require("../../utils/api.js");
var payUtils = require("../../utils/payUtils.js");
import { Page } from '../../utils/scan';
import { API_SCAN } from '../../const/apiurl'
import { API_USE_COUPON } from '../../const/apiurl'
import { ACTION_GOODS } from '../../const/actioncmd'
import { ACTION_MEMBER } from '../../const/actioncmd'
import { ACTION_REQUEST_GOOD_INFO } from '../../const/actioncmd'
import { ACTION_GO_BALANCE } from '../../const/actioncmd'
import { ACTION_GO_HOME } from '../../const/actioncmd'
import { ACTION_USE_COUPON } from '../../const/actioncmd'

Page({
  data: {
    goods: [],
    //单位是元
    totalPrice: 0.00,
    totalQuantity: 0,
    totalDisc: 0.00,
    memberPhone: '',
    showMemberPhone: '',
    memberPoint: 0,
    //显示弹窗，>1为显示，2loading 3 result success 4 result failed
    scanDialogDisplay: 0,
    dialogShowType: "",//弹窗类型：如refund coupon disccoupon
    dialogRemindText: "请扫描优惠券码",
    dialogLoadingText: "识别中",
    dialogResultSuccessRemind: "优惠券码已识别",
    dialogResultSuccessText: "恭喜您！录入成功",
    dialogResultFailureRemind: "优惠券码未识别",
    dialogResultFailureText: "录入失败，请稍后重试！",
  },

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

  onLoad: function (options) {
    var barcode = options.barcode
    if (barcode != null) {
      console.log("首页传递过来的商品条码是 " + barcode);
      this.getGoodInfoByBarcode(barcode)
    }
  },

  onShow() {
    //开启后屏监听
    let context = this;
    my.ix.onBuddyMessage({
      success: (res) => {
        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);
        if (res.action == ACTION_GOODS) {
          //商品信息同步
          let viewGoodsInfo = res.data
          context.setData({
            goods: viewGoodsInfo.goods,
            totalPrice: viewGoodsInfo.totalPrice,
            totalQuantity: viewGoodsInfo.totalQuantity,
            totalDisc: viewGoodsInfo.discCouponPrice,
          })

        } else if (res.action == ACTION_MEMBER) {
          let showPhone = res.data.substring(0, 3) + "****" + res.data.substring(7, 11)
          context.setData({
            memberPhone: res.data,
            showMemberPhone: showPhone,
            memberPoint: 2130
          })
        }
        else if (res.action == ACTION_GO_BALANCE) {
          //去结算页面
          context.goBalance();
        } else if (res.action == ACTION_REQUEST_GOOD_INFO) {
          //去结算页面
          context.getGoodInfoByBarcode(res.data);
        } else if (res.action == ACTION_GO_HOME) {
          //去首页
          my.reLaunch({
            url: "/pages/home/home",
          });
        } else if (res.action == ACTION_USE_COUPON) {
          //优惠券 
          context.setData({
            scanDialogDisplay: res.data.discCouponState,
            totalDisc: res.data.discCouponPrice
          });

          if (res.data.discCouponState == 1) {
            var speechContent = "请扫描优惠券码";
            my.ix.speech({
              text: speechContent,
              speak: true,
              success: (r) => {
              }
            });
          }

        }

      }
    });
  },

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

  //外接扫码枪事件
  onKeyPress(r) {
    if (this.data.scanDialogDisplay != 0) {
      this.useCoupon(r);
      return
    }
    console.log("scan onKeyPress==>" + r);
    this.getGoodInfoByBarcode(r);
  },

  //使用优惠券
  useCoupon(code) {
    this.setData({ scanDialogDisplay: 2 })
    setTimeout(() => {

      let totalDiscTemp = this.data.totalDisc + Math.round(Math.random() * 4) + 1;
      //超额
      if (totalDiscTemp > this.data.totalPrice) {
        let req = {}
        req.discCouponMsg = "超额优惠券"
        req.discCouponState = 4;
        req.discCouponPrice = this.data.totalDisc
        this.useCouponCallback(ACTION_USE_COUPON, req)
        return
      }

      let req = {}
      req.discCouponPrice = totalDiscTemp;
      req.discCouponState = 3;
      this.useCouponCallback(ACTION_USE_COUPON, req)

    }, 700);
  },

  //用券回调
  useCouponCallback(action, result) {
    let context = this;
    my.ix.sendBuddyMessage({
      target: getApp().globalData.backScreenAppId,
      data: {
        action: action,
        data: result
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
        //用券成功
        if (result.discCouponState == 3) {
          //模拟数据 1 - 5 随机整数
          context.setData({ scanDialogDisplay: 0, totalDisc: result.discCouponPrice })
          my.showToast({
            type: 'success',
            content: '优惠已录入',
            duration: 3000,
            success: () => {

            },
          });
          //用券失败
        } else if (result.discCouponState == 4) {
          context.setData({ scanDialogDisplay: 4 })
        }
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
        context.useCouponCallback(action, result)
      }
    });
  },

  //获取商品信息
  getGoodInfoByBarcode(barcode) {
    ////根据条形码查询商品接口
    my.showLoading({});
    var scanGoodRequest = api.createCommonRequest();
    scanGoodRequest.goodsId = barcode;
    //管理员需要额外传一个storeid 但是目前这个设备是没有
    console.log("扫商品的请求 ==>" + JSON.stringify(scanGoodRequest));
    my.request({
      url: getApp().globalData.BASE_URL + API_SCAN,
      method: 'POST',
      dataType: 'json',
      timeout: 30000,
      data: scanGoodRequest,
      success: (res) => {
        my.hideLoading();
        console.log("扫描商品成功 ==>" + JSON.stringify(res));
        if (res.data.success != true) {
          my.showToast({
            type: 'fail',
            content: res.data.message,
            duration: 2000
          });
        } else {
          var arr = Object.keys(res.data.data);
          if (arr.length == 0) {
            my.showToast({
              type: 'fail',
              content: "该商品没有对应的活动",
              duration: 2000
            });
          } else {
            //识别商品成功
            this.parseGoodInfo(res.data.data);
            console.log("识别商品信息成功");
          }
        }
      },
      fail: (res) => {
        my.hideLoading();
        console.log("扫商品的请求 ==>" + JSON.stringify(res));
        my.showToast({
          type: 'exception',
          content: api.decodeErrorMessage(res.error),
          duration: 2000
        });
      }
    });
  },


  //转化商品信息
  parseGoodInfo(goodinfo) {

    //价格 分转元
    goodinfo.quantity = 1;
    goodinfo.price = goodinfo.price
    goodinfo.salePrice = goodinfo.salePrice
    goodinfo.discnt = goodinfo.discnt

    //总数量
    let totalQuantityTemp = 0
    //总价格
    let totalPriceTemp = 0.00

    //数量+1 
    let isHasSame = false;
    let lastgoods = this.data.goods;
    let goodstemp = []
    let goodtemp
    lastgoods.forEach(function (item, index, array) {
      if (item.barcode == goodinfo.barcode) {
        let quantitytemp = item.quantity
        item.quantity = quantitytemp + 1
        isHasSame = true
        goodtemp = item
      } else {
        totalQuantityTemp = totalQuantityTemp + item.quantity
        totalPriceTemp = totalPriceTemp + item.price * item.quantity
        goodstemp.push(item)
      }

    })
    if (isHasSame) {
      totalQuantityTemp = totalQuantityTemp + goodtemp.quantity
      totalPriceTemp = totalPriceTemp + goodtemp.price * goodtemp.quantity

      let nowgoods = []
      nowgoods.push(goodtemp);
      var newgoods = nowgoods.concat(goodstemp)
      this.setData({ goods: newgoods })
    } else {
      totalQuantityTemp = totalQuantityTemp + 1
      totalPriceTemp = totalPriceTemp + goodinfo.price
      let nowgoods = []
      nowgoods.push(goodinfo);
      var newgoods = nowgoods.concat(lastgoods)
      this.setData({ goods: newgoods })
    }

    //汇总
    totalPriceTemp = payUtils.fen2Yuan(totalPriceTemp)
    this.setData({
      totalQuantity: totalQuantityTemp,
      totalPrice: totalPriceTemp,
    })

    //同步信息到后端
    this.sendGoodInfoToBack();
  },

  //把所有的商品数据发送到后屏
  sendGoodInfoToBack() {
    let context = this;
    var commonRequest = {
      action: ACTION_GOODS,
      data: this.data
    };

    my.ix.sendBuddyMessage({
      target: getApp().globalData.backScreenAppId,
      data: commonRequest,
      success: (res) => {
        console.log("发送商品数据到后屏小程序成功 ===》" + JSON.stringify(res));
      },
      fail: (res) => {
        console.log("发送商品数据到后屏小程序 失败 ===》 " + JSON.stringify(res));
        //发送失败重试
        context.sendGoodInfoToBack();
      }
    })
  },

  //跳转结算页面 
  goBalance() {
    my.navigateTo({
      url: "/pages/balance/balance?totalPrice=" + this.data.totalPrice + "&totalQuantity=" + this.data.totalQuantity + "&totalDisc=" + this.data.totalDisc,
    });
    // 存商品信息数据
    my.setStorage({
      key: 'goods',
      data: this.data.goods,
      success: function () {
        console.log("商品数据写入成功");
      }
    });
  },


  //核销券
  verifyCoupon(code) {
    my.showLoading({});
    var couponRequest = api.createCommonRequest();
    couponRequest.couponCode = barcode;
    console.log("核销券的请求 ==>" + JSON.stringify(couponRequest));
    my.request({
      url: getApp().globalData.BASE_URL + API_USE_COUPON,
      method: 'POST',
      dataType: 'json',
      timeout: 30000,
      data: couponRequest,
      success: (res) => {
        my.hideLoading();
        console.log("核销券成功 ==>" + JSON.stringify(res));
        if (res.data.success != true) {
          my.showToast({
            type: 'fail',
            content: res.data.message,
            duration: 2000
          });
        } else {
          console.log("核销券成功");
        }
      },
      fail: (res) => {
        my.hideLoading();
        console.log("核销券失败 ==>" + JSON.stringify(res));
        my.showToast({
          type: 'exception',
          content: api.decodeErrorMessage(res.error),
          duration: 2000
        });
      }
    });
  },







});