import Taro, { Component } from '@tarojs/taro';
import ListView from '@components/ListView'
import NewsItem from './item'
import './index.scss'
import { savePoint, updatePoint } from '@services/common'
import { queryNewsList } from '@services/news'
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
  }

  componentWillMount() {
    // App.zhuge.track('查看资讯列表页面')
    savePoint({
      event: 'list',
      eventType: 'news',
      propertyName: '资讯列表',
      data: '{}'
    }).then(res => {
      this.setState({
        recordId: res.recordId
      })
      console.log('资讯列表')
    })
  }

  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }
  componentDidShow(){
    this.onPullDownRefresh()
  }

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

    const { params: { buildingId } } = this.$router

    console.log(payload)

    if (cityId) {
      payload.cityId = cityId
    }

    // 从项目详情过来
    if (buildingId) {
      payload.buildingId = buildingId
    }

    return queryNewsList(payload)
  }

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

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