var api = require("../../utils/api.js");
import { throttle } from 'throttle-debounce';
import { Page } from '../../utils/scan';
//API
import { API_USE_COUPON } from '../../const/apiurl'
import { API_REFUND } from '../../const/apiurl'
//ACTION
import {
  ACTION_GO_SCAN, ACTION_GET_CUR_AD, ACTION_SEND_SEL_AD,
  ACTION_DIRECT_PAYMENT, ACTION_CONVERT_COUPON,
  ACTION_GO_HOME, ACTION_REFUND, ACTION_REFUND_FAILED,
  ACTION_REFUND_SUCCESS, ACTION_PRINT_LAST_ORDER,
  ACTION_SYSTEM_SETTING, ACTION_VERIFY, ACTION_VERIFY_SUCCESS,
  ACTION_VERIFY_FAILED, ACTION_DAY_CHECK, ACTION_PICK_UP_GOODS,
  ACTION_QUIT,
} from '../../const/actioncmd'


Page({
  data: {
    //显示弹窗，>1为显示，2loading 3 result success 4 result failed
    scanDialogDisplay: 0,
    dialogShowType: "",//弹窗类型：如refund coupon verify pickgoods
    dialogRemindText: "请扫描兑换码",
    dialogLoadingText: "识别中",
    dialogResultSuccessRemind: "兑换码已识别",
    dialogResultSuccessText: "恭喜您！兑换成功",
    dialogResultFailureRemind: "兑换码未识别",
    dialogResultFailureText: "兑换失败，请稍后重试！",
    adUrl: "/images/img_ad1.png",
    toSetting: false,
    //提货
    pickGoodsState: 0,
    pickGoodsMsg: "录入失败！无效的提货码",
    pickGoods: [],
  },

  onLoad() {

    let pickgoodsTemp = []
    for (var i = 0; i < 3; i++) {
      var good = {};
      good.name = "SK-II R.N.A.超肌能紧致弹力精华"
      good.price = "1098"
      good.quantity = 1
      pickgoodsTemp.push(good)
    }
    this.setData({ pickGoods: pickgoodsTemp })

  },

  onShow() {
    let context = this;
    my.ix.onBuddyMessage({
      success: (res) => {
        console.info(`onBuddyMessage success: ${JSON.stringify(res)}`);
        if (res.action == ACTION_GO_SCAN) {
          if (res.data.printEnabled != null) {
            my.setStorageSync({
              key: 'printEnabled',
              data: { enabled: res.data.printEnabled }
            });
          }

          my.ix.sendBuddyMessage({
            // 填入目标小程序的 AppID
            target: getApp().globalData.backScreenAppId,
            data: {
              action: ACTION_GO_SCAN,
              data: null
            },
            success: (res) => {
              console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
              //跳转到扫码页面
              my.reLaunch({
                url: "/pages/scan/scan",
              });
            },
            fail: (res) => {
              console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
            }
          });
        } else if (res.action == ACTION_DIRECT_PAYMENT) {
          //判断金额，不允许0元支付
          if (res.data == null) {
            my.showToast({
              content: "数据错误"
            });
          } else {
            var miyapayUtils = require("../../utils/miyapay4.js");
            var priceFen = miyapayUtils.yuan2Fen(res.data);
            if (priceFen == 0) {
              my.showToast({
                content: "不允许0元支付"
              });
              return;
            }
            //直接收款
            my.reLaunch({
              url: "/pages/balance/balance?totalPrice=" + res.data + "&totalQuantity=0&totalDisc=0&type=direct",
            });
          }
        } else if (res.action == ACTION_CONVERT_COUPON) {
          //兑换券 
          context.setData({
            scanDialogDisplay: res.data,
            dialogShowType: "coupon",//弹窗类型：如refund coupon
            dialogRemindText: "请扫描兑换码",
            dialogLoadingText: "识别中",
            dialogResultSuccessRemind: "兑换码已识别",
            dialogResultSuccessText: "恭喜您！兑换成功",
            dialogResultFailureRemind: "兑换码未识别",
            dialogResultFailureText: "兑换失败，请稍后重试！",
          });
          if (res.data != 0) {
            var speechContent = "请扫描兑换码";
            my.ix.speech({
              text: speechContent,
              speak: true,
              success: (r) => {
              }
            });
          }
        } else if (res.action == ACTION_REFUND) {
          //显示弹窗
          context.setData({
            scanDialogDisplay: 1,
            dialogShowType: "refund",
            dialogRemindText: "请扫描订单编码",
            dialogLoadingText: "识别中",
            dialogResultSuccessRemind: "退款成功",
            dialogResultSuccessText: "退款完成！会在1~2个工作日 返还到您的付款账户",
            dialogResultFailureRemind: "退款失败",
            dialogResultFailureText: "退款失败！无效的订单码",
          });
          console.log("ACTION_REFUND");
          var speechContent = "请扫描订单编码";
          my.ix.speech({
            text: speechContent,
            speak: true,
            success: (r) => { }
          });
        } else if (res.action == ACTION_GO_HOME) {
          //home界面收到，则返回界面上
          context.setData({
            scanDialogDisplay: 0,
            dialogShowType: "",//重置类型
          })
        } else if (res.action == ACTION_PRINT_LAST_ORDER) {
          console.log("收到打印上一单指令");
          //打印上一单
          //商品列表
          var printLastOrder_goodsList = my.getStorageSync({ key: 'paySuccessGoodsList' }).data;
          var printLastOrder_paySuccessResp = my.getStorageSync({ key: 'paySuccessResponse' }).data;
          if (printLastOrder_paySuccessResp == null) {
            //本地没有上一单信息
            my.ix.sendBuddyMessage({
              // 填入目标小程序的 AppID
              target: getApp().globalData.backScreenAppId,
              data: {
                action: ACTION_PRINT_LAST_ORDER,
                data: {
                  code: -1,
                  data: "本地没有上一单信息"
                }
              },
              success: (res) => {
                console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
              },
              fail: (res) => {
                console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
              }
            });
            return;
          }
          //去打印
          context.printLastOrder(printLastOrder_goodsList, printLastOrder_paySuccessResp);
        } else if (res.action == ACTION_GET_CUR_AD) {
          //返回当前选中广告
          context.returnCurShowAd();
        } else if (res.action == ACTION_SEND_SEL_AD) {
          var selectAdUrl = res.data;
          //改变当前的广告显示
          context.setData({
            adUrl: selectAdUrl
          });
        } else if (res.action == ACTION_SYSTEM_SETTING) {
          console.log("启动系统设置");
          my.ix.startApp({
            appName: 'settings',
            success: (res) => {
              console.log("启动系统设置成功 success==>" + JSON.stringify(res));

            }, fail: (res) => {
              console.log("启动系统设置失败 failed==>" + JSON.stringify(res));
            }
          });
          context.setData({
            toSetting: true,
          })
        } else if (res.action == ACTION_PICK_UP_GOODS) {
          //提货
          context.setData({
            scanDialogDisplay: res.data,
            dialogShowType: "pickgoods",//弹窗类型：如refund coupon pickgoods
            dialogRemindText: "请扫描提货码",
            dialogLoadingText: "识别中",
            dialogResultSuccessRemind: "提货码已识别",
            dialogResultSuccessText: "恭喜您！提货成功",
            dialogResultFailureRemind: "提货失败",
            dialogResultFailureText: "提货失败！无效的提货码！",
          });
          if (res.data != 0) {
            var speechContent = "请扫描提货码";
            my.ix.speech({
              text: speechContent,
              speak: true,
              success: (r) => {
              }
            });
          }

          //隐藏提货页面
          if (res.data == 0) {
            context.setData({
              pickGoodsState: 0,
              pickGoods: []
            })
          }
        } else if (res.action == ACTION_DAY_CHECK) {
          //本地先写死数据
          console.log("收到日结指令");
          context.printDayCheck();
        } else if (res.action == ACTION_VERIFY) {
          console.log("核验事件");
          //显示弹窗
          context.setData({
            scanDialogDisplay: 1,
            dialogShowType: "verify",
            dialogRemindText: "请扫描订单编码核销",
            dialogLoadingText: "识别中",
            dialogResultSuccessRemind: "核验通过",
            dialogResultSuccessText: "核验通过！可以离场",
            dialogResultFailureRemind: "核验未通过",
            dialogResultFailureText: "核验未通过！无效的核验码",
          });
          var speechContent = "请扫描订单编码核销";
          my.ix.speech({
            text: speechContent,
            speak: true,
            success: (r) => { }
          });
        } else if (res.action == ACTION_QUIT) {
          console.log("退出事件")
          my.removeStorageSync({
            key: 'localAccountInfo',
          });
          my.removeStorageSync({
            key: 'localLoginInfo',
          })
          my.reLaunch({
            url: "/pages/login/login",
          });

          getApp().globalData.isLoginOk = false

        }
      }
    });

    if (context.data.toSetting == true) {
      context.setData({
        toSetting: false,
      });
      //让后屏回到首页上
      my.ix.sendBuddyMessage({
        // 填入目标小程序的 AppID
        target: getApp().globalData.backScreenAppId,
        data: {
          action: ACTION_GO_HOME,
          data: null
        },
        success: (res) => {
          console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
        },
        fail: (res) => {
          console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
        }
      });
    }
  },

  /**
   * 打印
   */
  printDayCheck() {
    var printer = require("../../utils/printer.js");
    var cmds = [
      printer.setAlign(printer.ALIGN_CENTER),
      printer.printText('日结订单'),
      printer.printText(getApp().globalData.localAccountInfo.storeName),
      printer.setAlign(printer.ALIGN_LEFT),
      //打印日期
      printer.printNowDate(),
      //门店号
      printer.printText("门店号：" + getApp().globalData.localAccountInfo.storeName),
      //收款总额
      printer.printText('收款总额：10.00元'),
      printer.feedPaper(),
      printer.feedPaper(),
      printer.feedPaper(),
      printer.feedPaper(),
    ];
    printer.print({
      isCheckStatus: getApp().globalData.containerVersionCode > 20,
      cmds: cmds,
      callback: (res) => {
        //发送给后屏，告知打印结果
        my.ix.sendBuddyMessage({
          // 填入目标小程序的 AppID
          target: getApp().globalData.backScreenAppId,
          data: {
            action: ACTION_DAY_CHECK,
            data: res
          },
          success: (res) => {
            console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
          },
          fail: (res) => {
            console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
          }
        });
      }
    });
  },

  /**返回当前选中广告 */
  returnCurShowAd() {
    let context = this;
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.backScreenAppId,
      data: {
        action: ACTION_GET_CUR_AD,
        data: context.data.adUrl
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },

  /**打印上一单 */
  printLastOrder(printLastOrder_goodsList, printLastOrder_paySuccessResp) {
    var printLastOrder_orderPriceFen = printLastOrder_paySuccessResp.tradeAmount;
    var printLastOrder_couponPriceFen = printLastOrder_paySuccessResp.mdiscount + printLastOrder_paySuccessResp.discount;
    var printLastOrder_payPriceFen = printLastOrder_paySuccessResp.tradeAmount - (printLastOrder_paySuccessResp.mdiscount + printLastOrder_paySuccessResp.discount);
    var printLastOrder_totalCount = this.caculateTotalCountFromGoodsList(printLastOrder_goodsList);
    //分转元
    var miyapay = require("../../utils/miyapay4.js");
    var printLastOrder_orderPriceYuan = miyapay.fen2Yuan(printLastOrder_orderPriceFen);
    var printLastOrder_couponPriceYuan = miyapay.fen2Yuan(printLastOrder_couponPriceFen);
    var printLastOrder_payPriceYuan = miyapay.fen2Yuan(printLastOrder_payPriceFen);
    //支付渠道 
    var payChannel = "未知";
    if (printLastOrder_paySuccessResp.channel == 1) {
      payChannel = "微信";
    } else if (printLastOrder_paySuccessResp.channel == 3) {
      payChannel = "支付宝";
    }

    var printer = require("../../utils/printer.js");
    var cmds = [
      printer.setAlign(printer.ALIGN_CENTER),
      printer.printText(getApp().globalData.localAccountInfo.storeName),
      printer.setAlign(printer.ALIGN_LEFT),
      printer.printDivide("-"),
      printer.printText("门店号：" + printLastOrder_paySuccessResp.storeId),
      printer.printText("收银员账号：" + printLastOrder_paySuccessResp.operatorId),
      printer.printText("订单号：" + printLastOrder_paySuccessResp.tradeNo),
      printer.printNowDate(),
    ];
    if (null != printLastOrder_goodsList && printLastOrder_goodsList.length > 0) {
      cmds.push(printer.printDivide("-")),
        cmds.push(printer.printText("活动商品")),
        cmds.push(printer.printText("商品名称    " + "    编码    " + "    数量"))
      for (var i = 0; i < printLastOrder_goodsList.length; i++) {
        //循环取出商品数据
        cmds.push(printer.setAlign(printer.ALIGN_LEFT));
        cmds.push(printer.printText(printLastOrder_goodsList[i].name));
        cmds.push(printer.printTwoText(printLastOrder_goodsList[i].barcode, printLastOrder_goodsList[i].quantity + ""));
      }
    }

    cmds.push(printer.setAlign(printer.ALIGN_LEFT));
    cmds.push(printer.printDivide("-"));
    cmds.push(printer.printText("应收金额:" + printLastOrder_orderPriceYuan));
    cmds.push(printer.printText(payChannel + ":" + printLastOrder_payPriceYuan));
    for (var i = 0; i < 4; i++) {
      cmds.push(printer.feedPaper());
    }
    printer.print({
      isCheckStatus: getApp().globalData.containerVersionCode > 20,
      cmds: cmds,
      callback: (res) => {
        //发送给后屏，告知打印结果
        my.ix.sendBuddyMessage({
          // 填入目标小程序的 AppID
          target: getApp().globalData.backScreenAppId,
          data: {
            action: ACTION_PRINT_LAST_ORDER,
            data: res
          },
          success: (res) => {
            console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
          },
          fail: (res) => {
            console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
          }
        });
      }
    });
  },

  //计算件数
  caculateTotalCountFromGoodsList(goodsList) {
    if (goodsList == null || goodsList.length == 0) {
      return 0;
    }
    var totalCount = 0;
    for (var i = 0; i < goodsList.length; i++) {
      totalCount = totalCount + goodsList[i].quantity;
    }
    return totalCount;
  },

  //外接扫码枪事件
  onKeyPress(r) {
    console.log("scan onKeyPress==>" + r);
    if (this.data.scanDialogDisplay != 0) {
      if (this.data.dialogShowType == "refund") {
        //退款
        this.refund(r);
      } else if (this.data.dialogShowType == "coupon") {
        // 兑换券
        this.verifyCoupon(r);
      } else if (this.data.dialogShowType == "pickgoods") {
        // 提货
        this.pickGoods(r);
      } else if (this.data.dialogShowType == "verify") {
        this.verify(r);
      }
    }
  },

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


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

  //核销券
  verifyCoupon(code) {


    this.setData({ scanDialogDisplay: 2 })
    var commonRequest = {};
    commonRequest.state = 2
    this.sendConvertCouponToBack(commonRequest)
    var couponRequest = api.createCommonRequest();
    couponRequest.couponCode = code;
    console.log("兑换码的请求 ==>" + JSON.stringify(couponRequest));
    let context = this;
    my.request({
      url: getApp().globalData.BASE_URL + API_USE_COUPON,
      method: 'POST',
      dataType: 'json',
      timeout: 30000,
      data: couponRequest,
      success: (res) => {
        console.log("兑换成功 ==>" + JSON.stringify(res));
        if (res.data.success != true) {
          var commonRequest = {};
          commonRequest.state = 4
          commonRequest.msg = res.data.errorMsg
          context.sendConvertCouponToBack(commonRequest)
          this.setData({ scanDialogDisplay: 4 })
          console.log("兑换失败 ==>" + res.data.errorMsg);
        } else {
          //语音提示已识别
          var speechContent = "兑换码已识别";
          my.ix.speech({
            text: speechContent,
            speak: true,
            success: (r) => {
            }
          });
          var commonRequest = {};
          commonRequest.state = 3
          context.sendConvertCouponToBack(commonRequest)
          this.setData({ scanDialogDisplay: 3 })
          console.log("兑换成功 ==>" + JSON.stringify(res));
        }
      },
      fail: (res) => {
        var commonRequest = {};
        commonRequest.state = 4
        commonRequest.msg = "网络异常"
        context.sendConvertCouponToBack(commonRequest)
        this.setData({ scanDialogDisplay: 4 })
        console.log("兑换失败 ==>" + JSON.stringify(res));
        my.showToast({
          type: 'exception',
          content: api.decodeErrorMessage(res.error),
          duration: 2000
        });
      }
    });
  },

  //同步兑换券到后台
  sendConvertCouponToBack(e) {
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.backScreenAppId,
      data: {
        action: ACTION_CONVERT_COUPON,
        data: e
      },
      success: (sres) => {
      },
      fail: (fres) => {
        sendConvertCouponToBack(e)
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },



  //退款 
  refund(barcode) {

    this.setData({ scanDialogDisplay: 2 })
    var request = api.createCommonRequest();
    request.tradeNo = barcode;

    my.request({
      url: getApp().globalData.BASE_URL + API_REFUND,
      method: 'POST',
      dataType: 'json',
      timeout: 30000,
      data: request,
      success: (res) => {
        if (res.data.success != true || res.data.data == null) {
          this.setData({ scanDialogDisplay: 4 })
          console.log("退款失败 ==>" + JSON.stringify(res.data));
          var message = res.data.message;
          if (message == null) {
            message = "退款失败，请检查退款订单号，稍后再试";
          }
          this.refundCallback(ACTION_REFUND_FAILED, message);
        } else {
          var speechContent = "退款成功";
          my.ix.speech({
            text: speechContent,
            speak: true,
            success: (r) => { }
          });

          this.setData({ scanDialogDisplay: 3 })
          console.log("退款成功 ==>" + JSON.stringify(res.data));
          this.refundCallback(ACTION_REFUND_SUCCESS, res.data.data);
        }
      },
      fail: (res) => {
        this.setData({ scanDialogDisplay: 4 })
        console.log("退款失败 ==>" + JSON.stringify(res.data));
        var message = res.data.message;
        if (message == null) {
          message = "退款失败，请检查退款订单号，稍后再试";
        }
        this.refundCallback(ACTION_REFUND_FAILED, message);
      }
    });
  },

  refundCallback(action, data) {
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.backScreenAppId,
      data: {
        action: action,
        data: data
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
        //跳转到扫码页面
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });

  },

  //核验
  verify(result) {
    //目前缺少核验的接口，数据都是自造
    var speechContent = "核验通过";
    my.ix.speech({
      text: speechContent,
      speak: true,
      success: (r) => { }
    });
    this.setData({ scanDialogDisplay: 3 })

    this.onVerifyCallback(ACTION_VERIFY_SUCCESS, null);

  },

  onVerifyCallback(action, result) {
    my.ix.sendBuddyMessage({
      // 填入目标小程序的 AppID
      target: getApp().globalData.backScreenAppId,
      data: {
        action: action,
        data: result
      },
      success: (res) => {
        console.info(`sendBuddyMessage success: ${JSON.stringify(res)}`);
        //跳转到扫码页面
      },
      fail: (res) => {
        console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
      }
    });
  },


  //提货商品
  pickGoods(code) {
    let context = this;
    this.setData({ scanDialogDisplay: 2 })
    setTimeout(() => {
      //模拟提货数据
      let pickgoodsTemp = []
      for (var i = 0; i < 3; i++) {
        var good = {};
        good.name = "SK-II R.N.A.超肌能紧致弹力精华"
        good.price = "1098"
        good.quantity = 1
        pickgoodsTemp.push(good)
      }

      let pickGoodsReq = {}
      pickGoodsReq.pickGoodsState = 3;
      pickGoodsReq.pickGoods = pickgoodsTemp;
      my.ix.sendBuddyMessage({
        target: getApp().globalData.backScreenAppId,
        data: {
          action: ACTION_PICK_UP_GOODS,
          data: pickGoodsReq
        },
        success: (sres) => {
          context.setData({ pickGoods: pickgoodsTemp, pickGoodsState: 3, scanDialogDisplay: 0 })
        },
        fail: (fres) => {
          console.info(`sendBuddyMessage failed: ${JSON.stringify(res)}`);
        }
      });

    }, 700);
  },

});
