index.js 5.8 KB
import Taro, {Component} from '@tarojs/taro';
import {View, Image} from '@tarojs/components';
import contentCode from '../../utils/content-code';
import { Resources, ProductList, FilterMenu, SearchBar } from '../../components';
import searchImg from '../../static/images/search.png';
import goYohoBuy from '../../assets/images/goYohoBuy@3x.png';
import {common as commonModel} from '../../models';
import './index.scss';
import { connect } from '@tarojs/redux';
import { loginAction, decodeUnionId, wechatUserIsBind } from '../../libs/login/login.js'
import getPrivateKey from '../../libs/request/getPrivateKey.js'
import router from '../../router/index.js'


@connect(({ filterMenu }) => ({
    filterMenu
}))

export default class Index extends Component {
	constructor() {
		super(...arguments)

		this.state = {
			tabs: [
				{
					text: '推荐',
					type: 0
				},
				{
					text: '热销',
					type: 1
				},
				{
					text: '即将发售',
					type: 2
				}
			],
			page: {},
			productList: {},
      stopLoading: {},
      floors: []
		}
	}

	config = {
    navigationBarTitleText: '飞碟好物',
    enablePullDownRefresh: true,
    backgroundTextStyle: "dark",
    onReachBottomDistance: 50
  };
  
  onPullDownRefresh() {
    let filterMenu = this.props.filterMenu;
    this.getProductData(filterMenu).then(isFinish => {
      this.getResource().then(() => {
        Taro.stopPullDownRefresh();
      }).catch(error => {
        Taro.stopPullDownRefresh();
      })
    }).catch(error => {
      Taro.stopPullDownRefresh();
    });
    
  }

  async getResource() {
    const pk = await getPrivateKey();
    Taro.setStorage({ key: 'verifyKey', data: pk });
    console.log(contentCode.index);
    return commonModel.resource(contentCode.index).then(res => {
			if (res && res.code === 200) {
				this.setState({
					floors: res.data
				});
			}
		});
  }

  onReachBottom() {
    let { filterMenu } = this.props;
    let { page } = this.state;
    let type = filterMenu.indexType;

    console.log('onReachBottom: ', type);

    if (!this.state.stopLoading[type]) {
      this.setState({ page: Object.assign(page, { [type]: page[type] + 1 }) }, () => {
        this.getProductData();
      });
    }
  }

  componentDidMount() {
    let obj = {
      page: {},
      productList: {},
      stopLoading: {}
    };

    // 初始化数据
    this.state.tabs.map(item => {
      let type = item.type;

      obj.page[type] = 1;
      obj.productList[type] = [];
      obj.stopLoading[type] = false;
    });

    this.setState(obj, () => {
      this.getProductData();
      this.getResource();
    });
  }

  componentWillReceiveProps(nextProps, oldProps) {
    let curType = nextProps.filterMenu.indexType;
    let oldCurType = oldProps && oldProps.filterMenu && oldProps.filterMenu.indexType;
    let { productList } = this.state;

    if (curType !== oldCurType) {
      if (productList[curType].length === 0) {
        this.getProductData(nextProps.filterMenu);
      }
    }
  }

  async getProductData(obj) {
    let { filterMenu } = this.props;
    let { page, productList, stopLoading } = this.state;
    obj = obj || filterMenu;
    let type = obj.indexType;
    console.log(type);
    
    const pk = await getPrivateKey();
    Taro.setStorage({ key: 'verifyKey', data: pk });
    commonModel.search({
      limit: 10,
      type: type,
      page: page[type]
    }).then(ret => {
      if (ret && ret.code === 200) {
        let list = ret.data && ret.data.product_list || [];
        
        if (list.length === 0) {
          this.setState({
            stopLoading: Object.assign(stopLoading, { [type]: true })
          });
        } else {
          this.setState({
            productList: Object.assign(productList, { [type]: [...productList[type], ...list] })
          });
        }
      }
      return true;
    }).catch(error => {
      return false;
    });
  }

  onScrollToLower() {
    let { filterMenu } = this.props;
    let { page } = this.state;
    let type = filterMenu.indexType;

    console.log('onScrollToLower: ', type);

    if (!this.state.stopLoading[type]) {
      this.setState({ page: Object.assign(page, { [type]: page[type] + 1 }) }, () => {
        this.getProductData();
      });
    }
  }

  

	// gotoNative() {
	// 	Taro.navigateTo({
	// 		url: '/pages/nativeTest/nativeTest'
	// 	})
	// }

  // login(e) {
  //   loginAction((error, loginData) => {
  //     if (error) return;
  //     decodeUnionId(loginData.srd_session, e).then(data => {
  //       console.log(data);
  //       wechatUserIsBind(data.union_id, data.userInfo).then(message => {
  //         console.log(message);
  //       });
  //     });
  //   })
	// }
  // <Text onClick={this.gotoNative}>跳转原生页面</Text>
  // <Button openType="getUserInfo" onGetUserInfo = { this.login } > 登录 < /Button>
  
  goToSearch() {
    router.go('search');
  }

  goYohoBuyMinApp() {
    wx.navigateToMiniProgram({
      appId: 'wx084ab813d88c594b',
      success(res) {

      }
    })
  }

	render() {
		let {tabs, productList, isRefresh, floors} = this.state;
		let {filterMenu} = this.props;
		let list = productList[filterMenu.indexType] || [];

		return (
      <View>
      <View className="header-nav" onClick={this.goToSearch}>
        <SearchBar disabled={true}></SearchBar>
			</View>
			<View
				className='index-page'
				scrollY
				scrollWithAnimation
				scrollTop='0'
				lowerThreshold='20'
				onScrollToLower={this.onScrollToLower}>

				
      <Resources isRefresh={ isRefresh } floors = { floors } code={ contentCode.index}></Resources>
				<FilterMenu filterMenu={filterMenu} tabs={tabs} tabClass="border" fromPage="index"></FilterMenu>
				{
					list &&
					<ProductList list={list}></ProductList>
        }
        
        <Image className="goYohoBuy" onClick={this.goYohoBuyMinApp.bind(this)} src={goYohoBuy} mode="aspectFill" />
			</View>
      </View>
		)
	}
}