import Taro, { Component } from '@tarojs/taro';
import ListView from '@components/ListView'
import ReportItem from './item'
import './index.scss'
import { queryReportList } from '@services/report'
import { connect } from '@tarojs/redux'
let pageIndex = 1

@connect(state => state.user)
export default class Index extends Component {

  config = {
    navigationBarTitleText: '报备客户'
  }

  state = {
    list: [],
    hasMore: true,
    isEmpty: false,
    recordId: null,
    pageIndex:1
  }

  loadList(pageNumber) {
    const { userInfo: { person: { personId } } } = this.props
    const payload = { pageSize: 10, pageNumber,personId }
    return queryReportList(payload)
  }

  handleItemClick = (item) => {

    Taro.navigateTo({
      url: '/pages/report/detail/index?id=' + item.reportId
    })
  }

  onPullDownRefresh = async (rest) => {
    const { records: list, total } = await this.loadList(1);
    this.setState({
      list,
      isEmpty: total == 0,
      hasMore: list.length >= total ? false : true,
      pageIndex:1
    })
    rest && rest()
  }

  onScrollToLower = async (fn) => {
    const { list } = this.state;
    pageIndex++
    const { records, total } = await this.loadList(this.state.pageIndex+1);
    const reportList = list.concat(records)
    this.setState({
      list: reportList,
      hasMore: reportList.length >= total ? false : true,
      pageIndex:this.state.pageIndex+1
    });
    fn && fn();
  }

  render() {
    const { isEmpty, hasMore, list } = this.state

    return (
      <View className="page">
        <ListView
          needInit
          isEmpty={isEmpty}
          emptyText="暂无报备客户~"
          hasMore={hasMore}
          className="list"
          onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
          onScrollToLower={fn => this.onScrollToLower(fn)}
        >
          {list.map(item => (
            <ReportItem
              key={item.reportId}
              data={item}
              onClick={this.handleItemClick}
            ></ReportItem>
          ))}
        </ListView>

      </View>
    );
  }
}