/**
 * 通知信息列表
 * @邠心vbe on 2023/08/17
 */
import React, { Component } from 'react';
import { Text, View, FlatList, StyleSheet, RefreshControl, PixelRatio } from 'react-native';
import apiNotification from '../../api/apiNotification';
import Button from '../../components/Button';
import Dialog from '../../components/Dialog';
import { MyRefreshProps } from '../../components/ThemesConfig';
import { PageList } from '../Router';
import AlertUtil from './AlertUtil';
import ItemView from './ItemAlert';
import TextView from '../../components/TextView';

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

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

  toDetail(item={}) {
    if (item.notificationId) {
      startPage(PageList.viewMessage, {id: item.notificationId});
    }
  }

  toDelete(item={}) {
    if (item.notificationId) {
      Dialog.showDialog({
        title: $t("notification.deleteMessage"),
        message: $t("notification.confirmDelete"),
        ok: $t("nav.confirm"),
        callback: (btn) => {
          if (btn == Dialog.BUTTON_OK) {
            this.deleteMessage(item.notificationId);
          }
        }
      })
    }
  }

  deleteMessage(id) {
    this.setState({
      refreshing: true
    })
    apiNotification.deleteMessage(id).then(res => {
      toastShort($t("common.deleteSuccess"))
      this.getMessageList();
    }).catch(err => {
      toastShort(err)
      this.setState({
        refreshing: false
      })
    })
  }

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

  getMessageList() {
    apiNotification.getNotificationList("").then(res => {
      if (res.data) {
        this.setState({
          dataList: res.data,
          unreadTotal: AlertUtil.getUnreadAlert(),
          showReadAll: res.data?.length > 0 && AlertUtil.getUnreadAlert() > 0
        })
      }
    }).catch(err => {
      toastShort(err)
    }).finally(() => {
      this.setState({
        refreshing: false
      })
    })
  }

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

  onClickReadAll() {
    Dialog.showProgressDialog();
    setTimeout(() => {
      this.readAllMessage();
    }, 1000);
  }

  readAllMessage() {
    Dialog.dismissLoading();
    apiNotification.readAll().then(res => {
      AlertUtil.requestRefresh();
      this.onRefresh();
    }).catch(err => {
      toastShort(err)
    })
  }

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

  topView = (props) => {
    if (this.props.showUnread && this.state.unreadTotal > 0) {
      return (
        <View style={styles.topView2}>
          <TextView style={styles.unreadText}>Unread: {this.state.unreadTotal}</TextView>
          <Button
            style={styles.topButton}
            viewStyle={styles.topButtonView}
            textStyle={styles.topButtonText}
            text={$t("notification.btnReadAll")}
            onClick={() => this.onClickReadAll()}/>
        </View>
      )
    } else if (this.state.showReadAll) {
      return (
        <View style={styles.topView}>
          <Button
            style={styles.topButton}
            viewStyle={styles.topButtonView}
            textStyle={styles.topButtonText}
            text={$t("notification.btnReadAll")}
            onClick={() => this.onClickReadAll()}/>
        </View>
      )
    } else {
      return null;
    }
  }

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

  render() {
    return (
      <FlatList
        style={styles.listView}
        data={this.state.dataList}
        renderItem={this.listItem}
        ListHeaderComponent={this.topView}
        ItemSeparatorComponent={this.divideView}
        keyExtractor={item => item.notificationId}
        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'
  },
  topView: {
    padding: 8,
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  topView2: {
    padding: 8,
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  unreadText: {
    color: textSecondary,
    fontSize: 14,
    paddingLeft: 6
  },
  topButton: {
    marginRight: 4,
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: textCancel,
    borderWidth: 1,
    borderStyle: 'solid'
  },
  topButtonView: {
    ...$padding(6, 16),
    alignItems: 'center'
  },
  topButtonText: {
    color: textPrimary,
    fontSize: 12
  }
})