import * as React from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Table, TableColumnsType, Modal, TablePaginationConfig, Tooltip, Input, Radio, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ArrowDownOutlined, SearchOutlined, BulbOutlined,CloseOutlined,CloudDownloadOutlined } from '@ant-design/icons';
import InfoModal from './components/InfoModal';
import dayjs from 'dayjs';
import { useKnowledgeLibListStore } from './store';
import { Record } from './types';
import './style.less';
import LocalStorage from '@/LocalStorage';

import Step from '@/components/step';

const KnowledgeLibList: React.FC = () => {
    const navigate = useNavigate();
    const {
        listLoading,
        list,
        infoModalId,
        infoModalOpen,
        page,
        name,
        classificationType,
        setListLoading,
        setList,
        setInfoModalId,
        setInfoModalOpen,
        setPage,
        setName,
        setClassificationType,
        fetchExportKnowledgeSliceExport,
        fetchExportDocumentSliceExport,
        fetchExportDocumentExport,
        fetchKnowledgeLibList,
        onCreateKnowledgeLib,
        onModifyKnowledgeLib,
        onDeleteKnowledgeLib,
        onInfoModalOpenChange,
        init,
    } = useKnowledgeLibListStore();

    const [downloadOriginal, setDownloadOriginal] = React.useState<boolean>(); //原文档
    const [downloadMd, setDownloadMd] = React.useState<boolean>(); //MD文档
    const [deleteFlag, setDeleteFlag] = React.useState<boolean>(); // 删除权限
    const [updateFlag, setUpdateFlag] = React.useState<boolean>(); // 编辑权限
    const [listFlag, setListFlag] = React.useState<boolean>(); // 详情权限
    const [userInfoAll, setUserInfoAll] = React.useState<any>({});
    React.useEffect(() => {
        init();
        const downloadOriginal = LocalStorage.getStatusFlag('knowledge:knowledgeLib:downloadOriginal');
        setDownloadOriginal(downloadOriginal);
        const downloadMd = LocalStorage.getStatusFlag('knowledge:knowledgeLib:downloadMd');
        setDownloadMd(downloadMd);
        const dFlag = LocalStorage.getStatusFlag('knowledge:knowledgeLib:del');
        setDeleteFlag(dFlag);
        const tFlag = LocalStorage.getStatusFlag('knowledge:knowledgeLib:edit');
        setUpdateFlag(tFlag);
        const lFlag = LocalStorage.getStatusFlag('knowledge:knowledgeLib:detail');
        setListFlag(lFlag);
        setUserInfoAll(LocalStorage.getUserInfo());

        // 监听面包屑创建知识库事件
        const handleKnowledgeLibCreate = (event: CustomEvent) => {
            if (event.detail.platform === 'deepseek') {
                onClickCreate();
            }
        };

        window.addEventListener('knowledgeLibCreate', handleKnowledgeLibCreate as EventListener);

        return () => {
            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',
            sorter: (a, b) => a.name.localeCompare(b.name),
            render: (text, record) => {
                if (listFlag||userInfoAll.id === record.createBy) {
                    return (
                        <p
                            className='text-primary cursor-pointer'
                            style={{ fontWeight: 600 }} 
                            onClick={() => {
                                navigate(`/knowledge/knowledgeLib/${record.knowledgeId}/${record.createBy}`);
                            }}
                        >
                            {text}
                        </p>
                    )
                } else {
                    return (
                        <>
                            {text}
                        </>
                    )
                }
            }
        },
        {
            title: '使用空间',
            dataIndex: 'length',
            render: (text) => {
                if (text) {
                    const size = (text / 1024 / 1024).toFixed(2);
                    return `${size}M`;
                } else {
                    return '--'
                }
            }
        },
        {
            title: '字符数量',
            dataIndex: 'wordNum',
            render: (text) => {
                if (text) {
                    return `${text}`;
                } else {
                    return '--';
                }
            }
        },
        {
            title: '文件数量',
            dataIndex: 'documentSize',
            render: (text) => {
                if (text) {
                    return `${text}`;
                } else {
                    return '--';
                }
            }
        },
        {
            title: '是否公开',
            dataIndex: 'visible',
            render: (text) => {
                if (text==='0') {
                    return '公开';
                } else {
                    return '私有';
                }
            }
        },
        {
            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 (
                    <>
                        {
                            (updateFlag || userInfoAll.id === record.createBy) &&
                            <a
                                style={{ marginRight: 16 }}
                                onClick={() => {
                                    onClickModify(record.knowledgeId);
                                }}
                            >
                                <EditOutlined />
                            </a >
                        }
                        {
                            ((downloadOriginal||userInfoAll.id === record.createBy) && record.documentSize>0 &&
                            <a
                                style={{ marginRight: 16 }}
                                onClick={() => {
                                    Modal.confirm({
                                        title: '提示',
                                        content: `确定是否下载原文档？`,
                                        okType: 'primary',
                                        onOk: async () => {
                                            exportKnowledgeFile(record)
                                        }
                                    });
                                }}
                            >
                             <Tooltip title="下载原文档"> <ArrowDownOutlined /></Tooltip>
                            </a>)
                        }
                        {
                             ((downloadMd||userInfoAll.id === record.createBy) && record.documentSize>0)&&<a
                                style={{ marginRight: 16 }}
                                onClick={() => {
                                    Modal.confirm({
                                        title: '提示',
                                        content: `确定是否下载MD文件？`,
                                        okType: 'primary',
                                        onOk: async () => {
                                            exportKnowledgeMarkDown(record)
                                        }
                                    });
                                }}
                            >
                                <Tooltip title="下载MD"> <CloudDownloadOutlined /></Tooltip>
                            </a>
                        }
                        {
                            (deleteFlag || userInfoAll.id === record.createBy) &&
                            <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.pageNum,
        pageSize: page.pageSize,
        total: page.total,
        onChange: async (page, pageSize) => {
            await onChangePagination(page, pageSize);
        },
    };
    const steps = [
        {
            title: '创建知识库',
            description: '按特定场景/领域管理知识库，当前仅创建空的知识库集合。',
            number: 1,
        },
        {
            title: '上传文档',
            description: 'Word, Pdf, Excel等多种文档格式，支持图片 OCR；',
            number: 2,
        },
        {
            title: '高质量切片工具',
            description: '等待文档自动解析完成，既能直接使用默认结果，又能再次进行人工干预。',
            number: 3,
        }
    ]
    const [showGuide, setShowGuide] = React.useState<boolean>(() => localStorage.getItem('knowledgeGuideHidden') !== 'true');
    const hideGuide = () => { localStorage.setItem('knowledgeGuideHidden', 'true'); setShowGuide(false); };
    return (
        <div className='knowledgeLibList'>
            {/* 创建按钮已移至面包屑组件 */}
            <div className='knowledgeLibList-table'>
                {showGuide && <> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                    <div style={{ fontSize: 13, color: '#333', display: 'flex', alignItems: 'center', gap: 6 }}>
                        <BulbOutlined style={{ color: '#faad14' }} />
                        提示: 如何创建并管理自己的知识库？
                    </div>
                    <CloseOutlined onClick={hideGuide} style={{ color: '#999', cursor: 'pointer' }} />
                </div>
                <Step steps={steps} className='mb-3' /></>}
                <div className='knowledgeLibList-filter mb-3'>
                    <Radio.Group onChange={(e) => {
                        handleModeChange(e.target.value)
                    }} value={classificationType} style={{ marginBottom: 8 }}>
                        <Radio.Button value="0">全部</Radio.Button>
                        <Radio.Button value="1">我创建的</Radio.Button>
                    </Radio.Group>
                    <Space.Compact style={{ width: '300px' }}>
                        <Input
                            placeholder='请输入知识库名称进行搜索'
                            value={name}
                            onChange={(e) => handleNameChange(e.target.value)}
                        />
                        <Button type="primary" onClick={() => { init() }}><SearchOutlined /></Button>
                    </Space.Compact>
                </div>
                <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>
    );
};

// 设置组件名称，帮助 React Fast Refresh 识别组件
KnowledgeLibList.displayName = 'KnowledgeLibList';

export default KnowledgeLibList;