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

const { Dragger } = Upload;



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

    const params = useParams();

    const props: UploadProps = {
        name: 'file',
        multiple: true,
        action: '/api/bigmodel/api/uploadDocument/' + params.knowledgeId,
        onChange(info) {
            const { status } = info.file;
            if (status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                message.success(`${info.file.name} file uploaded successfully.`);
                init(params.knowledgeId);
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
    };

    React.useEffect(() => {
        init(params.knowledgeId);
        return () => reset();
    }, []);

    const columns: TableColumnsType<Record> = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 80,
            render: (text, record, index) => {
                return index + 1;
            }
        },
        {
            title: '文件名',
            dataIndex: 'name',
            render: (text, record) => {
                return (
                    `${text}`
                )
            }
        },
        {
            title: '文件大小',
            dataIndex: 'length',
            render: (text) => {
                if(text){
                    const size = (text / 1024 / 1024).toFixed(2);
                    return `${size}M`;
                }
            }
        },
        {
            title: '字符数量',
            dataIndex: 'word_num',
            render: (text) => {
                return `${text}`;
            }
        },
        {
            title: '分段',
            dataIndex: 'custom_separator',
            width: 200,
            render: (text) => {
                return `${text}`;
            }
        },
        {
            title: '上传时间',
            dataIndex: 'create_time',
            width: 200,
            render: (text) => {
                if (text) {
                    return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    return '--';
                }
            }
        },
        {
            title: '更新时间',
            dataIndex: 'update_time',
            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.id);
                            }}
                        >
                            <EditOutlined />
                        </a >
                        <a
                            className='text-error'
                            onClick={() => {
                                Modal.confirm({
                                    title: '删除',
                                    content: `确定删除知识文件:${record.name}吗？`,
                                    okType: 'danger',
                                    onOk: async () => {
                                        await onClickDelete(record.id);
                                    }
                                });
                            }}
                        >
                            <DeleteOutlined />
                        </a>
                    </>
                )
            }
        }
    ];

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

    return (
        <div className='knowledgeLibInfo'>
            <div className='knowledgeLibList-operation'>
                {
                    page.total === 0 &&
                    <>
                        {/* <Button
                            type='primary'
                            icon={<FileOutlined />}
                            onClick={() => {
                                onClickDocumentDetail(params.knowledgeId)
                            }}
                        >
                            文档
                        </Button> */}
                        <div style={{ marginTop: 20, width: '100%', height: '200px' }}>
                            <Dragger {...props}>
                                <p className="ant-upload-drag-icon">
                                    <InboxOutlined />
                                </p>
                                <p >
                                    点击上传,或拖放文件到此处
                                </p >
                                <p className="ant-upload-hint">
                                    仅支持上传pdf文档,文档大小不超过50M.
                                </p>
                            </Dragger>
                        </div>
                    </>

                }
            </div>
            {
                page.total > 0 &&
                <>
                    <div style={{ justifyContent: 'space-between', alignItems: 'center', display: 'flex' }}>
                        <div>

                        </div>
                        <div>
                            <Upload {...props}>
                                <Button type='primary' icon={<PlusOutlined />}>上传知识文件</Button>
                            </Upload>
                        </div>
                    </div>


                    <Table
                        scroll={{ x: 'max-content' }}
                        rowKey={(record) => record.id}
                        loading={listLoading}
                        columns={columns}
                        dataSource={list}
                        pagination={paginationConfig}
                    />
                    {
                        infoModalOpen &&
                        <InfoModal
                            id={infoModalId}
                            open={infoModalOpen}
                            onClickConfirm={infoModalOnClickConfirm}
                            onClickCancel={infoModalOnClickCancel}
                        />
                    }
                </>
            }
        </div>
    );
};

export default observer(KnowledgeLibInfo);