import Taro, { Component } from '@tarojs/taro';
import ListView from '@components/ListView'
import PolicyItem from './item'
import './index.scss'
import { savePoint, updatePoint } from '@services/common'
import { queryPolicyList } from '@services/policy'
import { connect } from '@tarojs/redux'
let pageIndex = 1

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

  config = {
    navigationBarTitleText: '购房百科列表'
  }

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


  loadList(pageNumber) {
    const { curCity } = this.props
    const payload = { pageSize: 10, pageNumber, cityId: curCity.id }
    return queryPolicyList(payload)
  }

  handleItemClick = (item) => {
    Taro.navigateTo({
      url: '/pages/policy/detail/index?id=' + item.policyId
    })
  }

  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 policyList = list.concat(records)
    this.setState({
      list: policyList,
      hasMore: policyList.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 => (
            <PolicyItem
              key={item.policyId}
              data={item}
              onClick={this.handleItemClick}
            ></PolicyItem>
          ))}
        </ListView>
      </View>
    );
  }
}