import Taro, { Component } from '@tarojs/taro';
import ListView from '@components/ListView'
import './index.scss'
import { queryHelpList } from '@services/activity'
import AssistanceItem from './assistanceItem'
import { savePoint, updatePoint } from '@services/common'
import { connect } from '@tarojs/redux'

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

  config = {
    navigationBarTitleText: '我的助力'
  }

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

  componentWillMount() {
    // App.zhuge.track('查看活动列表页面')
    savePoint({
      event: 'list',
      eventType: 'activity',
      propertyName: '活动列表',
      data: '{}'
    }).then(res => {
      this.setState({
        recordId: res.recordId
      })
      console.log('活动列表')
    })
  }
  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

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

    const { params: { buildingId, from } } = this.$router
    if (cityId) {
      payload.cityId = cityId
    }
    // 从个人中心过来
    if (from === 'mine') {
      payload.mine = true
    }
    // 从项目详情过来
    if (buildingId) {
      payload.buildingId = buildingId
    }
    return queryHelpList(payload)
  }

  handleItemClick(item) {
    console.log(item, "data")

    Taro.navigateTo({
      url: '/pages/activity/detail/assistance?id=' + item.helpActivityId+'&initiateId='+item.helpRecordInitiateId
    })


  }

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

  onScrollToLower = async (fn) => {
    const { list, pageIndex } = this.state;

    const { records, list: list1, total, current } = await this.loadList(pageIndex + 1);
    const _list = records || list1 || []
    const newList = list.concat(_list)
    this.setState({
      list: newList,
      pageIndex: current,
      hasMore: newList.length >= total ? false : true
    });
    fn && fn();
  }

  render() {
    const { isEmpty, hasMore, list } = this.state
    return (
      <ListView
        className="wrap"
        needInit
        isEmpty={isEmpty}
        emptyText="暂无助力活动~"
        hasMore={hasMore}
        onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
        onScrollToLower={fn => this.onScrollToLower(fn)}
      >
        <View className="list">
          {
            list.map(item => (
              <AssistanceItem
                data={item}
                key={item.dynamicId}
                onClick={this.handleItemClick}>
              </AssistanceItem>
            ))
          }
        </View>
      </ListView>
    );
  }
}