index.js 9.96 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';

@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();
        });
    }

    componentWillReceiveProps(nextProps) {
      let { destroy, page } = this.state;
      if (!destroy) {
        if (page.length > 0) {
          Object.keys(page).filter((key) => {
            page[key] = 0
          });
        }
        this.setState({
          page: page        
        });
        this.getProductData(nextProps.filterMenu);
      }
    }

    componentDidShow() {
      this.getProductData();
    }

    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('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;
        }

        // 系列,品牌,品类
        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 (isSearch) {
                    this.setState({
                        productList: {[type]: [...list] }
                    });
                } else {
                    if (list.length === 0) {
                        this.setState({
                            stopLoading: Object.assign(stopLoading, { [type]: true })
                        });
                    } else {
                      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');
        console.log(latelySearch);
        let { searchList, onSearchSaveType } = this.props;
        if (latelySearch) {
            searchList = latelySearch || []
        }
        if (e.detail.value === '') {
            return;
        }
        if (searchList.length >= 10) {
          searchList.pop();
        }
        searchList.unshift({search_word: e.detail.value});
        try {
          Taro.setStorageSync('latelySearch', searchList);
        } catch (error) {
          console.log(error);
        }
    }
    
    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;

        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={this.$router.params} > </FilterMenu>
                < /View>
                <ProductList list={productList[type]}></ProductList>
                
                <Image className="goYohoBuy" onClick={this.goYohoBuyMinApp.bind(this)} src={goYohoBuy} mode="aspectFill" />           
            </ScrollView>
        )
    }
}