index.js 10.3 KB
import Taro, { Component } from '@tarojs/taro';
import { View, Button } from '@tarojs/components';
import { SearchBar, FilterMenu, ProductList, PageTitle } from '../../components';
import { common as commonModel } from '../../models';
import { connect } from '@tarojs/redux';
import { bindActionCreators } from 'redux';
import { clearFilter } from '../../actions/filterData';
import './index.scss';
import goYohoBuy from '../../assets/images/goYohoBuy@3x.png';
import event from '../../utils/event.js';

@connect(({ filterMenu, filterData }) => ({
    filterMenu,
    filterData
}), (dispatch) => {
	return bindActionCreators({
    clearFilter
    }, dispatch);
})

export default class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchBarClass: 'width-list',
            tabs: [
                {
                    text: '推荐',
                    type: 0
                },
                {
                    text: '价格',
                    type: 'price'
                }
            ],
            hasFilter: true,
            fixed: false,
            query: '',
            pageTitle: '',
            page: {},
            productList: {},
            stopLoading: {},
            destroy: false
        };
    }

    componentDidMount() {
        let params = this.$router.params || {};
        console.log(params);
        let tabs = '';
        let obj = {
            page: {},
            productList: {},
            stopLoading: {}
        };
        let type = '';
        tabs = this.state.tabs;
        // 搜索商品
        if (params.query) {
            this.setState({
                query: decodeURI(params.query)
            });
        } else {// 其他【系列|品牌|品类】
            type = params.series ? 5 : type;
            type = params.brand ? 4 : type;
            type = params.sort ? 3 : type;

            this.setState({
                pageTitle: decodeURI(params.name)
            });
            if (params.productListTitle) {
                this.setState({
                    pageTitle: decodeURI(params.productListTitle)
                });
            }
        }


        // 初始化数据
        tabs.map(item => {
            if (item.type === 'price') {
                obj.page['p_desc'] = 1;
                obj.page['p_asc'] = 1;
                obj.stopLoading['p_desc'] = false;
                obj.stopLoading['p_asc'] = false;
                obj.productList['p_asc'] = [];
                obj.productList['p_desc'] = [];
            } else {
                obj.page[item.type] = 1;
                obj.productList[item.type] = [];
                obj.stopLoading[item.type] = false;
            }
        });

        obj.tabs = tabs;

        this.setState(obj, () => {
            this.getProductData();
        });
      event.on('reset-page-loading', this.resetPageAndStopLoading.bind(this));
    }

    componentWillReceiveProps(nextProps) {
      let { destroy, page, stopLoading } = this.state;
      if (!destroy) {
        // this.getProductData(nextProps.filterMenu);
      }
    }

    resetPageAndStopLoading(props) {
      let { page, stopLoading } = this.state;
      if (Object.keys(page).length > 0) {
          Object.keys(page).forEach((key) => {
              page[key] = 1
          });
      }
      if (Object.keys(stopLoading).length > 0) {
          Object.keys(stopLoading).forEach((key) => {
              stopLoading[key] = false
          })
      }
      console.log(page);
      console.log(stopLoading);
      this.setState({
          page: page,
          stopLoading      
      }, () => {
        this.getProductData(props.filterMenu);
      });
    }

    componentWillUnmount() {
      let { clearFilter } = this.props;
      clearFilter();
      this.setState({
        destroy: true
      })
    }

    onScroll(e) {
        if (e.detail.scrollTop > 72 && !this.state.isFixed) {
            this.setState({
                fixed: true
            });
        }
    }

    onScrolltoupper() {
        this.setState({
            fixed: false
        });
    }

    onScrollToLower() {
        let { filterMenu } = this.props;
        let { page } = this.state;
        let type = this.state.pageTitle ? this.state.tabs[0].type : filterMenu.curType;

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

    lowerList(obj) {
      let { filterMenu, filterData } = this.props;
      let { page, productList, stopLoading, query } = this.state;
      console.log('filterMenu: ', filterMenu);

      let order = '';
      obj = obj || filterMenu;
      order = obj.curType && obj.curType.toString().indexOf('p_') > -1 ? obj.curType : '';
      let type = this.state.pageTitle ? this.state.tabs[0].type : obj.curType;
      let params = {
        limit: 10,
        page: page[type] || 1
      };

      if (order) {
        params.order = order;
      } else {
        // params.type = order ? '' : type;
      }

      // 系列,品牌,品类
      if (this.state.pageTitle) {
        let urlParams = this.$router.params;

        delete urlParams.name;
        params = Object.assign(params, urlParams);
      }

      params = Object.assign(params, filterData);

      if (query) {
        params.query = query;
      }

      commonModel.search(params).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] })
            });
          }
        }
      })
    }

    getProductData(obj, isSearch) {
        let { filterMenu, filterData } = this.props;
        let { page, productList, stopLoading, query } = this.state;
        console.log('obj: ', obj);
        console.log('filterMenu: ', filterMenu);
        console.log('filterData: ', filterData);

        let order = '';
        obj = obj || filterMenu;
        order = obj.curType && obj.curType.toString().indexOf('p_') > -1 ? obj.curType : '';
        let type = this.state.pageTitle ? this.state.tabs[0].type : obj.curType;
        let params = {
            limit: 10,
            page: page[type] || 1
        };

        if (order) {
            params.order = order;
        }

        // 系列,品牌,品类
        if (this.state.pageTitle) {
            let urlParams = this.$router.params;

            delete urlParams.name;
            params = Object.assign(params, urlParams);
        }

        params = Object.assign(params, filterData);

        if (query) {
          params.query = query;
        }

        commonModel.search(params).then(ret => {
            if (ret && ret.code === 200) {
                let list = ret.data && ret.data.product_list || [];
                this.setState({
                    productList: {[type]: [...list] }
                });
            }
        })
    }

    onCancel() {
        Taro.navigateBack({
            delta: 1
        });
    }

    onInputAction(e) {
        console.log(e);
    }

    onComplate(e) {
        this.setState({
            query: e.detail.value
        }, () => {
            this.getProductData(null, true);
        })
        this.savaLateSearch(e);
    }

    savaLateSearch(e) {
        let latelySearch = Taro.getStorageSync('latelySearch');
        latelySearch = latelySearch || []
        if (e.detail.value === '') {
            return;
        }
        if (latelySearch.length >= 10) {
            latelySearch.pop();
        }
        let setList = this.removeSameSearch(latelySearch, e.detail.value);
        setList.unshift({ search_word: e.detail.value });
        try {
          Taro.setStorageSync('latelySearch', setList);
        } catch (error) {
          console.log(error);
        }
    }

    removeSameSearch(arr, search_word) {
      let hash = [];
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].search_word !== search_word) {
          hash.push(arr[i]);
        }
      }
      return hash;
    }
    
    goYohoBuyMinApp() {
        wx.navigateToMiniProgram({
          appId: 'wx084ab813d88c594b',
          success(res) {
    
          }
        })
    }

    render() {
        let { filterMenu } = this.props;
        let { pageTitle, productList } = this.state;
        let type = this.state.pageTitle ? this.state.tabs[0].type : filterMenu.curType;
        let isSearchQuery = this.$router.params.query;
        let value = this.state.query;
        let params = {
          ...this.$router.params,
          query: value
        }

        return (
            <ScrollView
                className='search-list-page'
                scrollY
                scrollWithAnimation
                scrollTop='0'
                lowerThreshold='50'
                upperThreshold='72'
                onScrolltoupper={this.onScrolltoupper}
                onScrollToLower={this.onScrollToLower}
                onScroll={this.onScroll}>

                {
                    isSearchQuery &&
                    (
                      <View>
                        <View className="header">
                            <SearchBar classname={this.state.searchBarClass} value={value} onInputAction={this.onInputAction} onComplate={this.onComplate}></SearchBar>
                            <Button plain className="cancel-btn" onClick={this.onCancel}>取消</Button>
                        </View>
                      </View>
                    )
                }

                {
                    pageTitle &&
                    <PageTitle pageTitle={pageTitle} selfClass="pd"></PageTitle>
                }
                <View className={ this.state.fixed ? 'fixed' : '' }>
                  <FilterMenu filterMenu={ filterMenu } tabs = { this.state.tabs } fromPage = "search" hasFilter = { this.state.hasFilter } screen={params} > </FilterMenu>
                < /View>
                <ProductList list={productList[type]}></ProductList>
                
                <Image className="goYohoBuy" onClick={this.goYohoBuyMinApp.bind(this)} src={goYohoBuy} mode="aspectFill" />           
            </ScrollView>
        )
    }
}