import { Component } from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtIcon } from "taro-ui";
import "./index.less";
import ProductList from "../../../components/index/ProductList";
import { getSearchProductList } from "../../../service";
export default class Index extends Component {
  state = {
    productList: [],
    page: 1,
    totalPages: 1,
    loading: false,
    keyword: "",
    isHasData: true,
  };
  componentDidMount() {
    const { keyword }  = Taro.getCurrentInstance().router.params||"";
    this.setState({ keyword }, () => {
      this.getSearchProductList(true);
    });
  }
  // 获取商品列表
  getSearchProductList = async (isAdd = false) => {
    const { page } = this.state;
    this.setState({ loading: true });

    const res = await getSearchProductList({
      search_name: this.state.keyword,
      page,
      page_size: 10,
    });

    this.setState((prevState) => ({
      productList: isAdd
        ? res.goods_list
        : [...prevState.productList, ...res.goods_list],
      totalPages: res.total_pages,
      loading: false,
    }),()=>{
      this.setState({
        isHasData: res.goods_list.length > 0,
      });
    });
  };
  // 页面上拉触底
  onReachBottom = () => {
    const { page, totalPages, loading } = this.state;
    if (page < totalPages && !loading) {
      this.setState(
        (prevState) => ({ page: prevState.page + 1 }),
        () => this.getSearchProductList()
      );
    }
  };
  render() {
    return (
      <View className="index">
        {/* 搜索列表 */}
        {this.state.isHasData ? (
          <ProductList
            productList={this.state.productList}
            loading={this.state.loading}
          ></ProductList>
        ) : (
          <View className="no-data">
            <AtIcon value="search" size="30" color="#999"></AtIcon>
            <View className="no-data-text">暂无数据</View>
          </View>
        )}
      </View>
    );
  }
}
