/**
 * 活动信息列表
 * @邠心vbe on 2023/10/24
 */
 import React, { Component } from 'react';
 import { View, Text, FlatList, StyleSheet, RefreshControl, PixelRatio } from 'react-native';
 import apiArticle from '../../api/apiArticle';
 import { MyRefreshProps } from '../../components/ThemesConfig';
 import { PageList } from '../Router';
 import AlertUtil from './AlertUtil';
import ItemCampaign from './ItemCampaign';

export default class ListCampaign extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataList: [],
      refreshing: false
    };
  }

  componentDidMount() {
    this.props.navigation.addListener('focus', () => {
      this.getMessageList();
    });
    setTimeout(() => {
      this.getMessageList();
    }, 500);
  }

  toDetail(item={}) {
    if (item.articleId) {
      startPage(PageList.viewCampaign, {id: item.articleId});
    }
  }

  onRefresh() {
    this.setState({
      refreshing: true
    })
    this.getMessageList();
  }

  getMessageList() {
    apiArticle.getCampaignList().then(res => {
      if (res.data) {
        this.setState({
          dataList: res.data
        })
      }
    }).catch(err => {
      toastShort(err)
    }).finally(() => {
      this.setState({
        refreshing: false
      })
    })
  }

  getMessageListPage() {
    const count = AlertUtil.getNewsCount();
    if (this.state.dataList.length > 0 && this.state.dataList.length < count) {
      const last = this.state.dataList[this.state.dataList.length-1]
      if (last.articleId) {
        apiArticle.getCampaignList(last.articleId).then(res => {
          if (res.data) {
            const list = [
              ...this.state.dataList,
            ]
            list.push(...res.data)
            this.setState({
              dataList: list
            })
          }
        }).catch(err => {
          toastShort(err)
        })
      }
    }
  }

  listItem = (props) => {
    return (
      <ItemCampaign
        {...props}
        onPress={() => this.toDetail(props.item)}
      />
    )
  }

  divideView = (props) => {
    return (<View style={{height: 1.5/PixelRatio.get()}}></View>)
  }

  render() {
    return (
      <FlatList
        style={styles.listView}
        data={this.state.dataList}
        renderItem={this.listItem}
        ItemSeparatorComponent={this.divideView}
        keyExtractor={item => item.articleId}
        onEndReached={() => this.getMessageListPage()}
        onEndReachedThreshold={0.3}
        refreshControl={
          <RefreshControl
            {...MyRefreshProps()}
            refreshing={this.state.refreshing}
            onRefresh={() => this.onRefresh()}
          />
        }
        ListEmptyComponent={<Text style={styles.noData}>{$t('notification.empty')}</Text>}
      />
    );
  }
}

const styles = StyleSheet.create({
  listView: {
    flex: 1
  },
  noData: {
    color: textPlacehoder,
    fontSize: 14,
    padding: 20,
    textAlign: 'center'
  }
})