import * as React from 'react';

import { Table, TableColumnsType, TablePaginationConfig,Drawer } from 'antd';
import { StepForwardOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import store from './store';
import { Record } from './types';
import './style.less';
import LocalStorage from '@/LocalStorage';
import InfoModal from './components/InfoModal';
import PreviewModal from './components/PreviewModal';
import AuditHistory from './components/auditHistory';

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

    const [drawerFlag, setDrawerFlag] = React.useState<boolean>(false);
    const [drawerData, setDrawerData] = React.useState<any>({});
    const [historyOpen, setHistoryOpen] = React.useState<boolean>(false);

    React.useEffect(() => {
        const userInfo = LocalStorage.getUserInfo();
        const userId = (userInfo?.id ?? '').toString();
        init(userId);

         // 监听面包屑创建知识库事件
        const handleKnowledgeLibCreate = (event: CustomEvent) => {
            if (event.detail.platform === 'auditHistory') {
                // onClickCreate();
                setHistoryOpen(true);
            }
        };
        
        window.addEventListener('auditHistory', handleKnowledgeLibCreate as EventListener);




        return () => {
            reset();
            window.removeEventListener('auditHistory', 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) => {
                // const previewUrl = `/preview/${record.url}`; // 根据实际字段构造 URL
                return (
                    <a
                        href={record.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={(e) => {
                            e.stopPropagation(); // 防止 Table 默认事件干扰
                        }}
                    >
                        {text}
                    </a>
                );
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (text) => {
                if (text === '1') {
                    return '待审核';
                }else if(text === '2'){
                    return '审核中';
                }else if(text === '3'){
                    return '审核通过';
                }else if(text === '4'||text === '5'){   
                    return '审核拒绝';
                }
            }
        },
        {
            title: '审核人',
            dataIndex: 'userName',
            render: (text) => {
                return `${text}`;
            }
        },
        {
            title: '审核意见',
            dataIndex: 'comment',
            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: 'operation',
            width: 150,
            fixed: 'right',
            render: (text, record) => {
                return (
                    <>
                        <a
                            style={{ marginRight: 16 }}
                            onClick={() => {
                                // onClickfetchTakaiApplicationDetail(record.appId);
                                setDrawerFlag(true)
                                setDrawerData(record)
                            }}
                            title='审核'
                        >
                            查看
                        </a >
                        <a
                            style={{ marginRight: 16 }}
                            onClick={() => {
                                onClickModify(record.appId);
                            }}
                            title='审核'
                        >
                            <StepForwardOutlined />审核
                        </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);
        },
    };

    return (
        <div className='knowledgeLibList'>
            <div className='knowledgeLibList-table'>
                <Table
                    scroll={{ x: 'max-content' }}
                    rowKey={(record) => record.createTime}
                    loading={listLoading}
                    columns={columns}
                    dataSource={list}
                    pagination={paginationConfig}
                />
            </div>
            {
                infoModalOpen &&
                <InfoModal
                    id={infoModalId}
                    open={infoModalOpen}
                    onClickConfirm={infoModalOnClickConfirm}
                    onClickCancel={infoModalOnClickCancel}
                    onClickClose={infoModalOnClickClose}
                />
            }
            {
                <Drawer
                    title={drawerData.name}
                    closable={{ 'aria-label': 'Close Button' }}
                    onClose={() => { setDrawerFlag(false) }}
                    width="80%"
                    open={drawerFlag}
                >
                    {drawerFlag&&<PreviewModal isComponent={true} AuditAppId={drawerData.appId} />}
                </Drawer> 
            }        
            <AuditHistory open={historyOpen} onClose={() => setHistoryOpen(false)} />     

        </div>
    );
};

export default observer(KnowledgeLibList);