index.js 9.79 KB
import Taro, { Component } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components';
import arrowRightIcon from '../../static/images/arrow-right-2.png';
import avatar from '../../static/images/avatar.png';
import yinVip from '../../static/images/yin-vip@2x.png';
import jinVip from '../../static/images/jin-vip@2x.png';
import baiJinVip from '../../static/images/baijin-vip@2x.png';
import { connect } from '@tarojs/redux';
import { bindActionCreators } from 'redux';
import * as globalData from '../../actions/globalData';
import user from '../../utils/user';
import { login as loginModel, personal as personalModel } from '../../models';
import './index.scss';
import event from '../../utils/event.js';
import { getImgUrl } from '../../utils/index.js'
import router from '../../router/index.js'
import Yas from '../../utils/yas';

let yas;

@connect(({ globalData }) => ({
  globalData
}), (dispatch) => {
  return bindActionCreators({ ...globalData }, dispatch);
})
export default class UserCenter extends Component {
  constructor(props) {
    super(...arguments);

    this.state = {
      list: [
        {
          text: '购买',
          num: 0,
          page: 'orderList',
        },
        {
          text: '收藏',
          num: 0,
          page: 'collection'
        },
        {
          text: '我的收入',
          page: 'myassets'
        },
        {
          text: '优惠券',
          page: 'myCoupon',
          num: 0
        },
        {
          text: '客服与帮助',
          mt: true,
          page: 'webview',
          url: 'https://activity.yoho.cn/feature/3185.html?title=%E5%B8%AE%E5%8A%A9%E4%B8%8E%E5%AE%A2%E6%9C%8D'
        }
      ],
      hasUnionID: '',
      isLogin: false,
      userInfo: {},
      uid: '',
      infoNum: {},
      orderSummary: {},
      avatar: '../../static/images/avatar.png'
    };
  }

  config = {
    navigationBarTitleText: '我的'
  }

  componentWillMount(){
    yas = new Yas(this.$scope);
  }

  componentDidShow() {
    let { globalData } = this.props;
    console.log('进入个人中心页面')
    console.log(globalData)
    this.setState({
      hasUnionID: globalData.wxUnionId !== null && globalData.wxUnionId !== '' && globalData.wxUnionId !== undefined ? true : false,
      isLogin: globalData.userInfo.uid > 0 ? true : false
    });

    this.showUserInfo();

    yas.pageOpenReport();
    yas.report('YB_MAIN_TAB_C', {TAB_ID: 4});
  }

  getWechatThirdSession() {
    let value = this.props.globalData.WXThird_session;

    return !value ? user.getYHStorageSync('WXThird_session', 'app') : value;
  }

  /**
   * 新的授权方式
   */
  async getUserInfo(e) {
    console.log('getUserInfo')
    console.log(e)
    console.log(this.props.globalData.WXThirdSession)
    if (e.detail.errMsg === 'getUserInfo:ok') {
      let response = await this.props.decodeUnionId(this.props.globalData.WXThirdSession, e);
      console.log('getUserInfo decodeUnionId')
      console.log(response)
      if (response.isHaveUnionID) {
        this.setState({
          hasUnionID: true
        });
      }
    } else {
      let response = await this.props.loginAndRegisterTapped();

      if (response && response.isHaveUnionID) {
        this.setState({
          hasUnionID: true
        })
      }
    }
  }

  async getPhoneNumber(e) {
    console.log('getPhoneNumber')
    console.log(e)

    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      let result = await this.props.decodePhoneNumber(e.detail.iv, e.detail.encryptedData, '');

      console.log('====getPhoneNumber result', result)
      result = result || {};

      if (result.code != 200) {
        Taro.showToast({
          title: result.message,
          duration: 1000,
          success: async () => {
            let ret = await this.props.loginAndRegisterTapped();
            console.log('getPhoneNumber ret', ret)
            if (ret && ret.succeed === true) {
              this.showUserInfo();
              this.getInfoNum();
            }
          }
        });
      } else {
        if (result.is_register) {
          cosnole.log('getPhoneNumber is_register')
          console.log(this.props)
          Taro.showToast({
            title: '欢迎加入Yoho!Family!新人礼包已发放到个人中心-优惠券,请注意查收',
            duration: 1500,
            success() {
              let uid = this.props.globalData.userInfo.uid > 0 ? this.props.globalData.userInfo.uid : 0;
              this.props.setUserInfo({ ...this.props.globalData.userInfo, uid: uid });

              this.setState({ uid: uid });
              this.showUserInfo();
            }
          });
        } else {
          let uid = this.props.globalData.userInfo.uid > 0 ? this.props.globalData.userInfo.uid : 0;

          this.props.setUserInfo({ ...this.props.globalData.userInfo, uid: uid });
          this.setState({ uid: uid });
          this.showUserInfo();
        }
      }
    } else {
      Taro.navigateTo({
        url: '/pages/login/index',
      });
    }
  }

  showUserInfo() {
    this.props.reloadSessionkey();
    this.props.reloadUserInfo();
    // let uid = this.props.globalData.userInfo.uid;
    let uid = wx.getStorageSync('userInfo').uid;
    let globalData = this.props.globalData
    if (uid) {
      let userInfo = globalData.testUser;
      if (!(globalData.testUser && globalData.testUser.avatarUrl)) {
        loginModel.profile({
          uid: uid
        }).then((ret) => {
          console.log('showUserInfo ret', ret);
          if (ret && ret.code === 200) {
            let img = '';
            let curLevel = ret.data.vip_info.cur_level;

            if (curLevel === 1) {
              img = yinVip;
            } else if (curLevel === 2) {
              img = jinVip;
            } else if (curLevel === 3) {
              img = baiJinVip;
            }

            userInfo = Object.assign(...this.props.globalData.userInfo, {
              nickName: ret.data.nickname,
              avatarUrl: !ret.data.head_ico ? avatar : ret.data.head_ico,
              vipImg: img
            })
            this.setState({
              userInfo: userInfo,
              isLogin: true
            });

            globalData.testUser = userInfo;

            let storUserInfo = wx.getStorageSync('userInfo');
            storUserInfo = Object.assign(storUserInfo, userInfo);
            wx.setStorageSync('userInfo', storUserInfo);

            // globalData.userInfo = userInfo;
          } else {
            this.setState({
              isLogin: false
            });
          }
        });
      } else {
        this.setState({
          userInfo: userInfo,
          isLogin: true
        });
      }

      personalModel.getUFO_OrderSummary().then(ret => {
        if (ret && ret.code === 200 && ret.data) {
          let list = this.state.list;
          const orderSummary = {};
          ret.data.forEach((item, index) => {
            orderSummary[item.actor] = item.sum;
          });
          let number = orderSummary['buy'];
          list[0].num = number;
          this.setState({
            list
          })
        }
      }).catch(error => {});
      personalModel.getUFO_FavoriteNumber().then(ret => {
        if (ret && ret.code === 200 && ret.data) {
          let list = this.state.list;
          let num = ret.data.product_favorite_total;
          list[1].num = num;
          this.setState({
            list
          });
        }
      }).catch(error => {});
      personalModel.getUFOTotalCoupons().then(ret => {
        if (ret && ret.code === 200 && ret.data) {
          let list = this.state.list;
          let num = ret.data;
          list[3].num = num;
          this.setState({
            list
          });
        }
      }).catch(error => {});
    } else {
      this.setState({
        userInfo: this.props.globalData.userInfo,
        isLogin: false
      });
    }
  }

  login() {
    event.emit('user-is-login', this.isLoginCallback, this.loginSuccess);
  }

  isLoginCallback() {
    console.log('已经登录');
  }

  loginSuccess() {
    console.log('登录成功');
  }

  naviagteToPage(item) {
    event.emit('user-is-login', this.navigateIsLogin.bind(this, item), this.navigateLoginSuccess.bind(this, item));
  }

  navigateIsLogin(item) {
    this.jumpWithItem(item);
  }

  navigateLoginSuccess(item) {
    this.jumpWithItem(item);
  }

  jumpWithItem(item) {
    router.go(item.page, item, item.routerAction);
  }

  getInfoNum() {
    // let myUid = this.props.globalData.userInfo.uid;

    loginModel.getInfoNum().then(ret => {
      if (ret && ret.code === 200) {
        this.setData({
          infoNum: ret.data
        });
      }
    });
  }

  render() {
    let { list, hasUnionID, isLogin, userInfo, vipImg } = this.state;
    let headerIco = isLogin ? getImgUrl(userInfo.avatarUrl) : avatar;
    if (!headerIco) {
      headerIco = '../../static/images/avatar.png'
    }
    return (
      <View className= "user-center-page" >
        <View className="header" >
          <Image src={headerIco} className = "avatar-img" > </Image>
          {
            !isLogin &&
              <Button
                className="user-name"
                onClick = { this.login } > 点击登录 < /Button>
          }
          {
            isLogin &&
              <View className="user-name" > { userInfo.nickName } < /View>
          }
        </View>
        {
          list.map(item => {
            return (
              <View className= { item.mt ? 'entry-item mt' : 'entry-item' } key={ item.text} onClick={this.naviagteToPage.bind(this, item)} >
                <View className="label" > { item.text } < /View>
                <View className="num">
                  <Text className="num-text">{isLogin ? item.num : ''}</Text>
                  <Image src={ arrowRightIcon } className="arrow-right-icon"> </Image>
                </View >
              </View>
            )
          })
        }
      </View>
		)
	}
}