import React, { Component } from 'react';

import { Tabs, WhiteSpace } from 'antd-mobile';
import Cards from './Cards'

import {graphqls} from '../../api/graphql_request'
import {getProductByProps} from '../../api/graphql/product'


const query=getProductByProps
let variables={}

//获取所有商品
function getGoods(){
  return graphqls(query,variables).then((data)=>{
    //console.log("data",data.productbyprops)
    let products=data.productbyprops

    let arr=products.map((item)=>{
      return item.category
    })

    arr = Array.from(new Set(arr))

    let tabs=arr.map((item)=>{
      return {title:item}
    })

    return {tabs,products}
  })
}


class TabBarTop extends Component {
    constructor(props){
      super(props)
      this.state={
        tabs:[],
        product_s:[],
        products:[],
        select:'所有果品'
      }
    }


    componentDidMount () {
      //console.log('tets')
      getGoods().then((data)=>{
        this.setState({
          tabs:[{title: '所有果品'},...data.tabs],
          products:data.products,
          select:'所有果品'
        })
        sessionStorage.setItem("products",JSON.stringify(data.products))
      })
    }
    tabChange(e){

      let category=e.title,
          products = JSON.parse(sessionStorage.getItem("products"));
      if(category==='所有果品'){
        this.setState({
          products:products
        })
      }else{
        let arr =products.filter((item)=>{
          return item.category===category
        })
  
        this.setState({
          products:arr
        })
      } 
    }
    
    render() {
      //console.log('this.state.products',this.state.products)
      return (
        <div>
          <WhiteSpace />
            <Tabs onChange={this.tabChange.bind(this)} tabs={this.state.tabs} renderTabBar={props => <Tabs.DefaultTabBar {...props} page={4} />}>
            </Tabs>
          <WhiteSpace />
          <Cards products={this.state.products ?this.state.products:[]}/>
        </div>
      );
    }
  }

  export default TabBarTop

