import React, { Component } from 'react'
import { Badge, Button, List, Popover, Spin, Tag } from 'antd'
import { AntIcon, Image, NoticeDetail } from 'components'
import { api } from 'common/api'
import InfiniteScroll from 'react-infinite-scroller'
import moment from 'moment'
import store from 'store'

const { getState, dispatch, subscribe } = store

export default class notice extends Component {
    state = {
        ...getState('notice'),

        loading: false,
        hasMore: true,
    }

    detail = React.createRef()

    constructor(props) {
        super(props)

        this.unsubscribe = subscribe('notice', notice => {
            this.setState({ ...notice })
        })
    }

    async componentDidMount() {
        const { data: count } = await api.sysNoticeUnread()
        dispatch({
            type: 'SET_NOTICE_COUNT',
            count,
        })
    }

    componentWillUnmount() {
        this.unsubscribe()
    }

    finish() {
        this.setState({ loading: false, hasMore: false })
    }

    async onInfiniteOnLoad(pageIndex) {
        this.setState({ loading: true })
        const { list } = this.state
        if (list.length >= 30) {
            return this.finish()
        }

        const {
            data: { items },
        } = await api.sysNoticeReceived({
            pageIndex,
            pageSize: 5,
            sortField: 'publicTime',
            sortOrder: 'descend',
        })
        if (!items.length) {
            return this.finish()
        }

        dispatch({
            type: 'SET_NOTICE_LIST',
            list: [...list, ...items],
        })

        this.setState({
            loading: false,
        })
    }

    renderList() {
        const { list, loading, hasMore } = this.state
        return (
            <InfiniteScroll
                loadMore={pageIndex => this.onInfiniteOnLoad(pageIndex)}
                hasMore={!loading && hasMore}
                useWindow={false}
                threshold={50}
            >
                <List
                    itemLayout="vertical"
                    dataSource={list}
                    renderItem={item => (
                        <List.Item key={item.id}>
                            <List.Item.Meta
                                avatar={<Image id={item.avatar} type="avatar" />}
                                title={
                                    <>
                                        {item.readStatus ? (
                                            <Tag color="#2db7f5">已读</Tag>
                                        ) : (
                                            <Tag color="#f50">未读</Tag>
                                        )}
                                        <a
                                            onClick={() =>
                                                this.detail.current.onOpenDetail(item.id)
                                            }
                                        >
                                            {item.title}
                                        </a>
                                    </>
                                }
                                description={
                                    <span className="text-normal ml-xs">
                                        {moment(item.createdTime || item.publicTime).fromNow()}
                                    </span>
                                }
                            />
                            <div className="ellipsis-2 text-gray">{item.content}</div>
                        </List.Item>
                    )}
                >
                    {loading && hasMore && (
                        <div className="pt-md pb-md text-center">
                            <Spin indicator={<AntIcon type="loading" />} />
                        </div>
                    )}
                </List>
                {!hasMore && (
                    <Button
                        type="text"
                        block
                        onClick={() =>
                            window.openContentWindowByMenuName('sys_notice_mgr_received')
                        }
                    >
                        查看全部
                    </Button>
                )}
            </InfiniteScroll>
        )
    }

    render() {
        const { count } = this.state

        return (
            <Popover
                arrowPointAtCenter={true}
                placement="bottomRight"
                content={this.renderList()}
                overlayInnerStyle={{ width: 300 }}
                overlayStyle={{ zIndex: 999 }}
                overlayClassName="yo-popover-infinite-scroll"
            >
                <span className="header-action">
                    <Badge count={count}>
                        <AntIcon type="message" />
                    </Badge>
                </span>
                <NoticeDetail ref={this.detail} />
            </Popover>
        )
    }
}
