// pages/frontScreenlogin/frontScreenlogin.js
let app = getApp();
Page({
  /**
	 * 页面的初始数据
	 */
  data: {
    bulletShow: false,
    money: '',
    host: "",
    uniacid: "",
    wx_token: "",
    session: "",
    dispatch_type_id: '',
    goods_id: '',
    store_id: '',
    wait_adverts: [],
    checkLogin: false,
    CodePayBol: true
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    wx.setNavigationBarColor({
      backgroundColor: '#24ab35',
      frontColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    });
    wxfaceapp.launchMp({
      appId: app.data.front_accept_message_id,
      hostAppId: app.data.front_mini_programs_id,
      miniappType: 2, //小程序版本类型
      launchPage: "packageC/frogpro/backScreenlogin/backScreenlogin",
      needLogin: 0, //是否需要登录态
      success(res) {},
      fail(res) {

      }
    });
    let that = this;
    //接受另一端屏幕上的小程序发来的消息
    wxfaceapp.onRemoteMessage(function(res) {
      if (res.content) {
        // wx.showModal({
        // 	title: '提示',
        // 	content: res.content,
        // 	showCancel: false,
        // 	success(res_1) {}
        // })
        let content = JSON.parse(res.content);
        if (content.moneyBol) {
          if (content.bolshow) {
            that.setData({
              bulletShow: true,
              money: content.money
            });
            wx.setNavigationBarColor({
              backgroundColor: '#fff',
              frontColor: '#000000',
              animation: {
                duration: 400,
                timingFunc: 'easeIn'
              }
            });
          } else {
            that.setData({
              bulletShow: false
            });
            wx.setNavigationBarColor({
              backgroundColor: '#24ab35',
              frontColor: '#000000',
              animation: {
                duration: 400,
                timingFunc: 'easeIn'
              }
            });
          }
        }
        if (content.showBol) {
          wxfaceapp.launchMp({
            appId: app.data.front_accept_message_id,
            hostAppId: app.data.front_mini_programs_id,
            miniappType: 2, //小程序版本类型
            launchPage: "packageC/frogpro/backScreenlogin/backScreenlogin",
            needLogin: 0, //是否需要登录态
            success(res) {},
            fail(res) {

            }
          });
        }
        if (content.wx_token) {
          that.setData({
            session: content.session,
            wx_token: content.wx_token,
            store_id: content.store_id,
            dispatch_type_id: content.dispatch_type_id,
            goods_id: content.goods_id,
            host: content.host,
            uniacid: content.uniacid
          });
          // that.uploadRecords()
        }
      }
    });
    wxfaceapp.listenCodePayment({
      success(res) {
        //注册事件
        wxfaceapp.onCodePayEvent(function(res) {
          if (that.data.bulletShow) {
            if (that.data.CodePayBol) {
              let replyCode = res.code;
              let number = replyCode.slice(0, 2);
              if (number >= 10 && number <= 15) {
                that.paybtn(replyCode, 'Wechat');
              } else if (number >= 25 && number <= 30) {
                that.paybtn(replyCode, 'walipay');
              }
            } else {
              wx.showToast({
                title: '正在支付中,请勿重复扫码',
                icon: 'none',
                duration: 3000
              });
            }
          } else {
            wx.showToast({
              title: '等待输入金额',
              icon: 'none',
              duration: 3000
            });
          }
        });
      }
    });
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  getNetAddresss: function(action) {
    var url = this.data.host + '/addons/yun_shop/api.php?i=' + this.data.uniacid + '&session_id=' + this.data.wx_token +
			'&type=12&route=' + action;
    return url;
  },
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {

  },
  paybtn(faceCode, type) {
    let that = this;
    let url = '';
    let money = '';
    if (type == 'Wechat') {
      url = 'plugin.store-cashier.frontend.pos.merge-pay.wechat-scan-pay';
      money = (that.data.money ? (that.data.money * 100) : 0);
    } else if (type == 'walipay') {
      // 后台没有这个接口
      url = 'plugin.store-cashier.frontend.pos.merge-pay.walipay-scan-pay';
      money = (that.data.money ? that.data.money : 0);
    }
    if (faceCode) {
      that.setData({
        CodePayBol: false
      });
      wx.showLoading({
        title: '正在支付中...',
      });
      wx.request({
        url: that.getNetAddresss(url),
        data: {
          auth_code: faceCode,
          amount: money,
          store_id: that.data.store_id,
          dispatch_type_id: that.data.dispatch_type_id,
          goods: JSON.stringify([{
            goods_id: that.data.goods_id,
            total: 1
          }])
        },
        header: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Cookie': 'PHPSESSID=' + that.data.wx_token
        },
        method: "post",
        success: function(resdata) {
          var res = resdata.data;
          console.log(res,"res");
          if (res.result == 1) {
            that.setData({
              bulletShow: false
            });
            wx.setNavigationBarColor({
              backgroundColor: '#24ab35',
              frontColor: '#000000',
              animation: {
                duration: 400,
                timingFunc: 'easeIn'
              }
            });
            // setTimeout(function() {
            wxfaceapp.launchMp({
              appId: app.data.front_accept_message_id,
              hostAppId: app.data.front_mini_programs_id,
              miniappType: 2, //小程序版本类型
              launchPage: "packageC/frogpro/succeededPayment/succeededPayment",
              needLogin: 0, //是否需要登录态
              success(res) {
                wxfaceapp.postMsg({
                  targetAppid: app.data.front_accept_message_id,
                  content: JSON.stringify({
                    money: (that.data.money?that.data.money:''),
                    redirectType: 'succeededPayment'
                  }),
                  success(res) {},
                  fail(res) {

                  }
                });
              },
              fail(res) {
                wx.showModal({
                  title: '提示',
                  content: res,
                  showCancel: false,
                  success(res_1) {}
                });
              }
            });
            // }, 2000)
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          } else if (res.result == 0 && res.msg === '请登录') {
            // setTimeout(function() {
            wxfaceapp.launchMp({
              appId: app.data.front_accept_message_id,
              hostAppId: app.data.front_mini_programs_id,
              miniappType: 2, //小程序版本类型
              launchPage: "packageC/frogpro/backScreenlogin/backScreenlogin",
              needLogin: 0, //是否需要登录态
              success(res) {
                wxfaceapp.postMsg({
                  targetAppid: app.data.front_accept_message_id,
                  content: JSON.stringify({
                    redirectType: 'login'
                  }),
                  success(res) {},
                  fail(res) {

                  }
                });
              },
              fail(res) {
                wx.showModal({
                  title: '提示',
                  content: res,
                  showCancel: false,
                  success(res_1) {}
                });
              }
            });
            // }, 3000)
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          } else {
            // setTimeout(function() {
            wxfaceapp.launchMp({
              appId: app.data.front_accept_message_id,
              hostAppId: app.data.front_mini_programs_id,
              miniappType: 2, //小程序版本类型
              launchPage: "packageC/frogpro/lose/lose",
              needLogin: 0, //是否需要登录态
              success(res) {
                wxfaceapp.postMsg({
                  targetAppid: app.data.front_accept_message_id,
                  content: JSON.stringify({
                    money: (that.data.money?that.data.money:''),
                    redirectType: 'lose'
                  }),
                  success(res) {},
                  fail(res) {

                  }
                });
              },
              fail(res) {
                wx.showModal({
                  title: '提示',
                  content: res,
                  showCancel: false,
                  success(res_1) {}
                });
              }
            });
            // }, 3000)
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          }
          wx.hideLoading();
          that.setData({
            CodePayBol: true
          });
        },
        fail: function(res) {
          wx.showToast({
            title: res,
            icon: 'none',
            duration: 1500
          });
          that.setData({
            CodePayBol: true
          });
        }
      });
    }
  },
  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {

  },
  facePayment() {
    let that = this;
    wxfaceapp.facePay({
      requireFaceCode: true,
      success(res) {
        wxfaceapp.onFacePayPassEvent(function(res) {
          let faceCode = res.faceCode;
          if (faceCode) {
            wx.request({
              url: that.getNetAddresss('plugin.store-cashier.frontend.pos.merge-pay.wechat-scan-face-pay'),
              data: {
                auth_code: faceCode,
                amount: that.data.money ? (that.data.money * 100) : 0,
                store_id: that.data.store_id,
                dispatch_type_id: that.data.dispatch_type_id,
                goods: JSON.stringify([{
                  goods_id: that.data.goods_id,
                  total: 1
                }])
              },
              header: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Cookie': 'PHPSESSID=' + that.data.wx_token
              },
              method: "post",
              success: function(resdata) {
                var res = resdata.data;
                if (res.result == 1) {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 1500
                  });
                } else if (res.result == 0 && res.msg === '请登录') {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 1500
                  });
                  that.data.checkLogin = true;
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 1500
                  });
                }
              },
              fail: function(res) {
                wx.showToast({
                  title: res,
                  icon: 'none',
                  duration: 1500
                });
              }
            });
          }else {
            wx.showToast({
              title: res,
              icon: 'none',
              duration: 3000
            });
          }
        });
        wxfaceapp.onQueryPaymentSucEvent(function(res) {
          that.setData({
            bulletShow: false
          });
          wx.setNavigationBarColor({
            backgroundColor: '#24ab35',
            frontColor: '#000000',
            animation: {
              duration: 400,
              timingFunc: 'easeIn'
            }
          });
          wxfaceapp.launchMp({
            appId: app.data.front_accept_message_id,
            hostAppId: app.data.front_mini_programs_id,
            miniappType: 2, //小程序版本类型
            launchPage: "packageC/frogpro/storeManagement/storeManagement",
            needLogin: 0, //是否需要登录态
            success(res) {
              wxfaceapp.postMsg({
                targetAppid: app.data.front_accept_message_id,
                content: JSON.stringify({
                  money: (that.data.money?that.data.money:''),
                  redirectType: 'succeededPayment'
                }),
                success(res) {},
                fail(res) {

                }
              });
            },
            fail(res) {

            }
          });
        });
        wxfaceapp.onQueryPaymentFailedEvent(function(res) {
          that.setData({
            bulletShow: false
          });
          wx.setNavigationBarColor({
            backgroundColor: '#24ab35',
            frontColor: '#000000',
            animation: {
              duration: 400,
              timingFunc: 'easeIn'
            }
          });
          if (that.data.checkLogin) {
            wx.showToast({
              title: '等待后屏小程序登录',
              icon: 'none',
              duration: 2000
            });
            wxfaceapp.launchMp({
              appId: app.data.front_accept_message_id,
              hostAppId: app.data.front_mini_programs_id,
              miniappType: 2, //小程序版本类型
              launchPage: "packageC/frogpro/backScreenlogin/backScreenlogin",
              needLogin: 0, //是否需要登录态
              success(res) {
                wxfaceapp.postMsg({
                  targetAppid: app.data.front_accept_message_id,
                  content: JSON.stringify({
                    redirectType: 'login'
                  }),
                  success(res) {},
                  fail(res) {

                  }
                });
              },
              fail(res) {

              }
            });
            that.data.checkLogin = false;
          } else {
            wxfaceapp.launchMp({
              appId: app.data.front_accept_message_id,
              hostAppId: app.data.front_mini_programs_id,
              miniappType: 2, //小程序版本类型
              launchPage: "packageC/frogpro/storeManagement/storeManagement",
              needLogin: 0, //是否需要登录态
              success(res) {
                wxfaceapp.postMsg({
                  targetAppid: app.data.front_accept_message_id,
                  content: JSON.stringify({
                    money: (that.data.money?that.data.money:''),
                    redirectType: 'lose'
                  }),
                  success(res) {},
                  fail(res) {

                  }
                });
              },
              fail(res) {
                wx.showToast({
                  title: res.reply,
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          }
        });
      },
      fail(res) {
        wx.showToast({
          title: res.reply,
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
  //设置广告轮播图信息
  getQAdvertising() {
    let that = this;
    wx.request({
      url: that.getNetAddresss('plugin.advert-market.api.advert.getPutAdverts'),
      data: {
        store_id: {
          id: that.data.store_id
        }
      },
      header: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Cookie': 'PHPSESSID=' + that.data.wx_token
      },
      method: "post",
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            wait_adverts: res.data.wait_adverts
          });
        } else {
          wx.showToast({
            title: res,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function(res) {
        wx.showToast({
          title: res,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  //记录广告图信息
  recordBtn(e) {
    let that = this;
    let index = e.detail.current;
    let viewLog = [];
    try {
      var value = wx.getStorageSync('viewLog');
      if (value) {
        viewLog = value;
      }
    } catch (e) {
      console.log(e);
    }
    if (that.data.wait_adverts.lenght > 0) {
      let advert_id = that.data.wait_adverts[index].id;
      // let advert_code = that.data.wait_adverts[index].advert_code;
      let await_amount = that.data.wait_adverts[index].await_amount;
      let view_count = 1;
      if (that.data.wait_adverts[index].view_count) {
        that.setData({
          ['wait_adverts[' + index + '].view_count']: that.data.wait_adverts[index].view_count + 1
        });
        view_count = that.data.wait_adverts[index].view_count + 1;
      } else {
        that.setData({
          ['wait_adverts[' + index + '].view_count']: 1
        });
        view_count = 1;
      }
      viewLog[index] = [{
        advert_id: advert_id,
        view_count: view_count,
        advert_unit: await_amount
      }];
      try {
        wx.setStorageSync('viewLog', viewLog);
      } catch (e) {
        console.log(e);
      }
    }
  },
  //上传记录
  uploadRecords() {
    let that = this;
    let viewLog = [];
    try {
      var value = wx.getStorageSync('viewLog');
      if (value) {
        viewLog = value;
      }
    } catch (e) {
      console.log(e);
    }
    if (viewLog.length > 0) {
      for (let i = 0; i < viewLog.length; i++) {
        wx.request({
          url: that.getNetAddresss('plugin.advert-market.api.advert.getPutAdverts'),
          data: {
            viewLog: {
              store_id: that.data.store_id,
              advert_id: viewLog[i].advert_id,
              advert_code: 1,
              view_count: viewLog[i].view_count,
              unit_code: 2,
              advert_unit: advert_unit
            }
          },
          header: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Cookie': 'PHPSESSID=' + that.data.wx_token
          },
          method: "post",
          success: function(resdata) {
            var res = resdata.data;
            if (res.result == 0) {
              wx.showToast({
                title: res,
                icon: 'none',
                duration: 1500
              });
            }
          },
          fail: function(res) {
            wx.showToast({
              title: res,
              icon: 'none',
              duration: 1500
            });
          }
        });
      }
      try {
        wx.setStorageSync('viewLog', []);
      } catch (e) {
        console.log(e);
      }
      that.getQAdvertising();
    } else {
      that.getQAdvertising();
    }
  }
});
