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

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

    const [createFlag, setCreateFlag] = React.useState<boolean>();
    const [deleteFlag, setDeleteFlag] = React.useState<boolean>();
    const [updateFlag, setUpdateFlag] = React.useState<boolean>();
    const [listFlag, setListFlag] = React.useState<boolean>();
    const [userInfoAll, setUserInfoAll] = React.useState<any>({});
    // 新手引导（知识库）整体可见性（持久化到 localStorage）
    const [showGuide, setShowGuide] = React.useState<boolean>(() => localStorage.getItem('knowledgeGuideHidden') !== 'true');
    const hideGuide = () => { localStorage.setItem('knowledgeGuideHidden', 'true'); setShowGuide(false); };
    React.useEffect(() => {
        init();
        const cFlag = LocalStorage.getStatusFlag('deepseek:knowledge:create');
        setCreateFlag(cFlag);
        const dFlag = LocalStorage.getStatusFlag('deepseek:knowledge:delete');
        setDeleteFlag(dFlag);
        const tFlag = LocalStorage.getStatusFlag('deepseek:knowledge:update');
        setUpdateFlag(tFlag);
        const lFlag = LocalStorage.getStatusFlag('deepseek:knowledge:list');
        setListFlag(lFlag);
        setUserInfoAll(LocalStorage.getUserInfo());
        
        // 监听面包屑创建知识库事件
        const handleKnowledgeLibCreate = (event: CustomEvent) => {
            if (event.detail.platform === 'deepseek') {
                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',
            sorter: (a, b) => a.name.localeCompare(b.name), 
            render: (text, record) => {
                if (createFlag) {
                    return (
                        <a href=""
                            onClick={()=>{
                                router.navigate({ pathname: `/deepseek/knowledgeLib/${record.knowledgeId}/${record.createBy}`,
                                 },
                                      );
                            }}
                        >
                            {text}
                        </a>
                        // <Link to={{ pathname: `/deepseek/knowledgeLib/${record.knowledgeId}`}} >
                        //     {text}
                        // </Link>
                    )
                } 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: '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 >
                        }

                        {
                            (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.pageNumber,
        pageSize: page.pageSize,
        total: page.total,
        onChange: async (page, pageSize) => {
            await onChangePagination(page, pageSize);
        },
    };

    return (
        <div className='knowledgeLibList'>
            {/* {
                createFlag &&
                <div className='knowledgeLibList-operation'>

                    <Button
                        type='primary'
                        icon={<PlusOutlined />}
                        onClick={onClickCreate}
                    >
                        创建知识库
                    </Button>

                </div>
            } */}
            {/* 创建按钮已移至面包屑组件 */}

            {/* 新手使用提示区块（知识库） */}
            {showGuide && (
                <div style={{ padding: '12px 20px 12px 20px', background: '#fff' }}>
                    <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>
                    <Row gutter={12}>
                        <Col xs={24} sm={24} md={12} lg={8}>
                            <Card
                                size="small"
                                bordered={false}
                                style={{
                                    background: 'linear-gradient(90deg, #e6f4ff 0%, #f0f7ff 100%)',
                                    boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
                                    borderRadius: 8,
                                    height: '100%'
                                }}
                                bodyStyle={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 80 }}
                                title={<span style={{ fontWeight: 600 }}>创建知识库</span>}
                            >
                                <div style={{ color: '#666', fontSize: 12 }}>点击右上角“创建知识库”，按需填写名称与描述，当前仅创建空的知识库集合。</div>
                                <div style={{ textAlign: 'right', color: '#1677ff', fontWeight: 600 }}>step 1</div>
                            </Card>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={8}>
                            <Card
                                size="small"
                                bordered={false}
                                style={{
                                    background: 'linear-gradient(90deg, #e6fffb 0%, #f0fffe 100%)',
                                    boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
                                    borderRadius: 8,
                                    height: '100%'
                                }}
                                bodyStyle={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 80 }}
                                title={<span style={{ fontWeight: 600 }}>上传文档与管理知识片段</span>}
                            >
                                <div style={{ color: '#666', fontSize: 12 }}>上传Word, Pdf等多种文档格式，支持图片 OCR，查看切片与索引状态，按需更新或删除，保持知识内容最新。</div>
                                <div style={{ textAlign: 'right', color: '#1677ff', fontWeight: 600 }}>step 2</div>
                            </Card>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={8}>
                            <Card
                                size="small"
                                bordered={false}
                                style={{
                                    background: 'linear-gradient(90deg, #fff7e6 0%, #fffaf0 100%)',
                                    boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
                                    borderRadius: 8,
                                    height: '100%'
                                }}
                                bodyStyle={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 80 }}
                                title={<span style={{ fontWeight: 600 }}>创建RAG应用时引用知识库</span>}
                            >
                                <div style={{ color: '#666', fontSize: 12 }}>在RAG应用配置中选择此知识库参与检索问答。</div>
                                <div style={{ textAlign: 'right', color: '#1677ff', fontWeight: 600 }}>step 3</div>
                            </Card>
                        </Col>
                    </Row>
                </div>
            )}
            <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);