index.js 5.94 KB
// index.js
import wx from '../../utils/wx';
import event from '../../common/event';
import {getLoginButtonType} from '../../common/login';
import {parse} from '../../vendors/query-stringify';
import accountModel from '../../models/account/index';
import Promise from '../../vendors/es6-promise';
import config from '../../common/config';
import Yas from '../../common/yas';
import helper from '../../utils/helper';

let app = getApp();
let yas;
let router = global.router;

Page({
  data: {
    loginButtonType: '', // 获取登录button-type
    userInfo: {
      phoneNum: '',
      avatarUrl: '',
      defaultAvatar: false,
      nickName: '',
      wechat: ''
    },
    coinNum: 0,
    isBound: false,
    myQrCodeUrl: 'https://m.yohobuy.com/home/newQrcode?needLogin=1',
    loginText: '点击登录',
    now_test_uid_index: 1,
    containerHeight: '1006rpx',
    h5PageUrl: [
      {
        title: '如何获得限购码?',
        url: 'https://activity.yoho.cn/feature/247.html?nodownload=1'
      }
    ],
    limitCodes: {
      codes: [],
      invalidCodes: []
    },
    isShow: 0,
    referer: '',
    needBind: 1,
  },
  onLoad: function(options) {
    let that = this;

    if (options.referer) {
      console.log('referer:', options.referer);
      let referer = decodeURIComponent(options.referer);

      if (referer.indexOf('/') !== 0) {
        referer = '/' + referer;
      }
      this.setData({
        referer: referer
      });
    }
    if (options.login !== undefined) {
      this.setData({
        needBind: (options.login === '0' || !options.login) ? 0 : true
      });
    }

    yas = new Yas(app); // 实例化埋点
    yas.pageOpenReport();
    event.on('user-login-success', this.showBindUserInfo);
    event.on('user-login-callback', this.loginCallback.bind(this));
    event.on('change-login-status', params => {
      that.setData({
        loginText: params.text || '点击登录'
      });
    });


  },
  onShow: function() {
    setTimeout(() => {
      app = app || getApp();
      this.showBindUserInfo();
    }, app ? 0 : 1000);
  },
  onReady: function() {


  },
  changeLoginStatus: function(params) {
    console.log(params);
  },
  loginCallback: function(res) {
    this.setData({
      loginButtonType: getLoginButtonType()
    });
    this.goReferer(); // 如果不需要绑定手机则返回前一页
  },
  showBindUserInfo: function() {
    let that = this;

    this.setData({
      loginButtonType: getLoginButtonType()
    });

    if (app && app.getUid() && app.getUserInfo().wechat) {
      return Promise.all([
        accountModel.getProfile(),
        accountModel.getCoinTotal(),
        accountModel.getLimitCodes()
      ]).then(res => {
        let defaultAvatar = (app.globalData.userInfo.wechat &&
          app.globalData.userInfo.wechat.avatarUrl) ||
          '../../static/images/icons/default-avatar.png';
        let resUserInfo = res[0].data || {};

        console.log('resUserInfo:', resUserInfo);
        console.log('limitInfo:', res[2]);

        let user = Object.assign({}, this.data.userInfo, app.globalData.userInfo, {
          nickName: resUserInfo.nickname,
          avatarUrl: resUserInfo.head_ico || defaultAvatar,
          phoneNum: resUserInfo.mobile,
          defaultAvatar: (resUserInfo.head_ico || defaultAvatar) === defaultAvatar,
        });

        app.setUserInfo(user);// 把用户信息写入storage

        that.setData({
          isBound: true,
          userInfo: user,
          coinNum: res[1].data && res[1].data.total || 0
        });

        that.setLimitCodeList(res[2]);

        that.goBack(); // 如果有referer则返回前一个页面
      }).catch({});
    }
  },
  outLogin: function() {
    return wx.showModal({
      title: '',
      content: '确认退出?',
      confirmText: '退出',
      confirmColor: '#000'
    }).then(res1 => {
      if (res1.confirm) {
        app.clearUserSession();

        // app._setSync('disableAutoLogin', true);
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    });
  },
  setLimitCodeList: function(res) { // 处理限购码列表的数据
    let that = this;
    let invalidCodes = [];
    let codes = [];

    res.data.invalidLimitCodeProducts.forEach((item, index) => {
      item.defaultUrl = helper.image(item.defaultUrl, 220, 138, 1);
      invalidCodes.push(item);
    });

    res.data.limitCodeProducts.forEach((item, index) => {
      item.defaultUrl = helper.image(item.defaultUrl, 220, 138, 1);
      codes.push(item);
    });

    this.setData({
      limitCodes: {
        invalidCodes: invalidCodes,
        codes: codes
      },
      isShow: 1
    });

    // 通过顶部和底部按钮的高度,计算中间限购码部分的高度
    let sysInfo = wx.getSystemInfoSync();
    let windowHeight = sysInfo.windowHeight;

    let query = wx.createSelectorQuery();

    query.select('.user-info-bar').boundingClientRect();
    query.select('.out-login').boundingClientRect();
    query.exec(result => {
      let topHeight = result[0].height;
      let bottomHeight = result[1].height;
      let containerHeight = (windowHeight - topHeight - bottomHeight - 20 - 30) + 'px';

      that.setData({
        containerHeight: containerHeight
      });
    });
  },
  navigateToh5Page: function(e) {
    console.log(e);
    let type = e.currentTarget.dataset.type || 0;

    let type_obj = this.data.h5PageUrl[type];

    let url = type_obj.url + '&title=' + type_obj.title;

    router.goUrl(url);
  },
  navigateToLimitListPage: function() {
    router.go('home');
  },
  navigateToDetail: function(e) {
    let limitProductCode = e.currentTarget.dataset.code;

    router.go('productDetail', { limitProductCode });
  },
  goReferer: function() { // 无需绑定的获取用户信息后返回
    if (this.data.referer && !this.data.needBind) {
      router.goUrl(`${config.MINI_APP_DOMAIN}${this.data.referer}`);
    }
  },
  goBack: function() {
    if (this.data.referer) {
      router.goUrl(`${config.MINI_APP_DOMAIN}${this.data.referer}`);
    }
  }
});