import * as React from 'react';
import { Link } from 'react-router-dom';
import { observer } from 'mobx-react';
import { Button, Table, TableColumnsType, Modal, TablePaginationConfig } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import InfoModal from './components/InfoModal';
import dayjs from 'dayjs';
import store from './store';
import { Record } from './types';
import './style.less';

const KnowledgeLibList: React.FC = () => {
    const {
        state,
        onChangePagination,
        onClickCreate,
        onClickModify,
        infoModalOnClickConfirm,
        infoModalOnClickCancel,
        onClickDelete,
        init,
        reset
    } = store;
    const {
        listLoading,
        list,
        infoModalId,
        infoModalOpen,
        page
    } = state;

    React.useEffect(() => {
        init();
        
        // 监听面包屑创建知识库事件
        const handleKnowledgeLibCreate = (event: CustomEvent) => {
            if (event.detail.platform === 'zhipu') {
                onClickCreate();
            }
        };
        
        window.addEventListener('knowledgeLibCreate', handleKnowledgeLibCreate as EventListener);
        
        return () => {
            reset();
            window.removeEventListener('knowledgeLibCreate', handleKnowledgeLibCreate as EventListener);
        };
    }, []);

    const columns: TableColumnsType<Record> = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            render: (text, record, index) => {
                return index + 1;
            }
        },
        {
            title: '知识库名称',
            dataIndex: 'name',
            render: (text, record) => {
                return (
                                            <Link to={{ pathname: `/zhipu/knowledgeLib/${record.knowledgeId}` }} >
                        {text}
                    </Link>
                )
            }
        },
        {
            title: '使用空间',
            dataIndex: 'length',
            render: (text) => {
                const size = (text / 1024).toFixed(2);
                return `${size}M`;
            }
        },
        {
            title: '字符数量',
            dataIndex: 'wordNum',
            render: (text) => {
                return `${text}字`;
            }
        },
        {
            title: '文件数量',
            dataIndex: 'documentSize',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: 200,
            render: (text) => {
                if (text) {
                    return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    return '--';
                }
            }
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            width: 200,
            render: (text) => {
                if (text) {
                    return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    return '--';
                }
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 150,
            fixed: 'right',
            render: (text, record) => {
                return (
                    <>
                        <a
                            style={{ marginRight: 16 }}
                            onClick={() => {
                                onClickModify(record.knowledgeId);
                            }}
                        >
                            <EditOutlined />
                        </a >
                        <a
                            className='text-error'
                            onClick={() => {
                                Modal.confirm({
                                    title: '删除',
                                    content: `确定删除知识库名称${record.name}吗？`,
                                    okType: 'danger',
                                    onOk: async () => {
                                        await onClickDelete(record.knowledgeId);
                                    }
                                });
                            }}
                        >
                            <DeleteOutlined />
                        </a>
                    </>
                )
            }
        }
    ];

    const paginationConfig: TablePaginationConfig = {
        // 显示数据总量
        showTotal: (total: number) => {
            return `共 ${total} 条`;
        },
        // 展示分页条数切换
        showSizeChanger: true,
        // 指定每页显示条数
        pageSizeOptions: ['10', '20', '50', '100'],
        // 快速跳转至某页
        showQuickJumper: true,
        current: page.pageNumber,
        pageSize: page.pageSize,
        total: page.total,
        onChange: async (page, pageSize) => {
            await onChangePagination(page, pageSize);
        },
    };

    return (
        <div className='knowledgeLibList'>
            {/* 创建按钮已移至面包屑组件 */}
            <div className='knowledgeLibList-table'>
                <Table
                    scroll={{ x: 'max-content' }}
                    rowKey={(record) => record.knowledgeId}
                    loading={listLoading}
                    columns={columns}
                    dataSource={list}
                    pagination={paginationConfig}
                />
            </div>
            {
                infoModalOpen &&
                <InfoModal
                    id={infoModalId}
                    open={infoModalOpen}
                    onClickConfirm={infoModalOnClickConfirm}
                    onClickCancel={infoModalOnClickCancel}
                />
            }
        </div>
    );
};

export default observer(KnowledgeLibList);