import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import { queryCardFansList } from '@services/card'
import { queryItemFansList } from '@services/item'

import FansItem from './item'
import ListView from '@components/ListView'
import { savePoint, updatePoint } from '@services/common'
let pageIndex = 1
export default class Index extends Component {
  config = {
    navigationBarTitleText: '粉丝访问记录'
  }
  state = {
    list: [],
    hasMore: true,
    isEmpty: false,
    recordId:null,
    pageIndex:1
  }
  componentDidMount() {
    // App.zhuge.track('查看粉丝页面')
  }

  loadList(pageNumber) {
    const {
      // id = '369b7d7e5bc6e6b91f2e8f5e775035e2',
      id,
      type = 'card'
    } = this.$router.params

    const payload = { pageSize: 10, pageNumber }
    if(type === "card"){
      // 埋点
      savePoint({
        event: 'fans',
        eventType: 'card',
        propertyName: '粉丝访问记录',
        data:'{}'
      }).then(res => {
        this.setState({
          recordId:res.recordId
        })
        console.log('粉丝访问记录')
      })

    }else{
      // 埋点
      savePoint({
        event: 'person',
        eventType: 'building',
        propertyName: '项目详情围观人数',
        data:'{}'
      }).then(res => {
        this.setState({
          recordId:res.recordId
        })
        console.log('项目详情围观人数')
      })
    }
    return type === "card" ? queryCardFansList(id, payload) : queryItemFansList(id, payload)
  }
  componentWillUnmount(){
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }
  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++
    console.log(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 { hasMore, isEmpty, list } = this.state
    return (
      <ListView
        needInit
        isEmpty={isEmpty}
        emptyText="暂无更多粉丝哦~"
        hasMore={hasMore}
        style={{ height: '100vh' }}
        onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
        onScrollToLower={fn => this.onScrollToLower(fn)}
      >
        {list.map(item => <FansItem key={item.uvId} data={item} />)}
      </ListView>
    );
  }
}