import * as React from 'react';
import { observer } from 'mobx-react';
import { useParams } from 'react-router-dom';
import { List, Button, Divider, Empty, Modal, Form, Input, message } from 'antd';
import { SettingOutlined, DeleteOutlined, ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons';
import { apis } from '@/apis';
import { PaginationConfig } from 'antd/es/pagination';
import router from '@/router';
import './style.less';

const FormItem = Form.Item;
const SliceList: React.FC = () => {

    const [form] = Form.useForm();

    const params = useParams();

    interface Item {
        slice_id: string,
        document_id: string,
        slice_text: string,
        slice_char_len: number,
    };

    interface PageInfo {
        pageNum: number,
        pageSize: number,
        total: number,
    };

    const [listLoading, setListLoading] = React.useState(false);
    const [list, setList] = React.useState<Item[]>([]);
    const [page, setPage] = React.useState<PageInfo>({
        pageNum: 1,
        pageSize: 10,
        total: 0,
    });

    const appApi = {
        fetchList: async (p0: { searchText: string; }) => {
            setListLoading(true);
            try {
                const res = await apis.fetchTakaiSliceList({
                    knowledge_id: params.knowledgeId || '',
                    document_id: params.documentId || '',
                    text: p0.searchText,
                    pageSize: page.pageSize,
                    pageNum: page.pageNum
                })
                console.log('fetchTakaiSliceList', res);
                const list = res.rows.map((item: any) => {
                    return {
                        slice_id: item.sliceId,
                        document_id: item.documentId,
                        slice_text: item.sliceText,
                        slice_char_len: item.sliceText.length,
                    }
                });
                setList(list);
                setPage({
                    pageNum: page.pageNum,
                    pageSize: page.pageSize,
                    total: res.total,
                });
            } catch (error) {
                console.error(error);
            } finally {
                setListLoading(false);
            }
        },

    };

    const handleClickSearch = () => {
        const values = form.getFieldsValue();
        appApi.fetchList({ searchText: values.text });
    }
    const handleClickReset = () => {
        form.resetFields();
        appApi.fetchList({ searchText: '' });
    }

    const deleteSlice = async (slice_id: string, knowledgeId: string) => {
        try {
            if (!params.knowledgeId || !params.documentId) {
                throw new Error('knowledgeId或documentId未定义，请检查路由参数');
            }
            const res = await apis.deleteTakaiSlice(slice_id, params.knowledgeId, params.documentId);
            if (res.code === 200 && res.data === 1) {
                appApi.fetchList({ searchText: '' });
                message.success('删除切片成功');
            }
        } catch (error) {
            console.error('删除切片失败:', error);
        }
    }

    const init = async () => {
        console.log('params', params.knowledgeId);
        await appApi.fetchList({ searchText: '' });
    }

    React.useEffect(() => {
        init();
    }, [page.pageSize, page.pageNum])

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

    return (
        <div>
            <div className='dataExport-search'>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Form form={form} layout='inline' colon={false}>
                        <FormItem label='切片' name='text'>
                            <Input />
                        </FormItem>
                        <FormItem>
                            <Button
                                style={{ marginRight: 16 }}
                                type='primary'
                                onClick={handleClickSearch}
                            >
                                查询
                            </Button>
                            <Button onClick={handleClickReset}>
                                重置
                            </Button>
                        </FormItem>
                    </Form>

                    <div >
                        <Button style={{ marginRight: 16 }} type='primary' icon={<PlusOutlined />} onClick={() => {
                            router.navigate({
                                pathname: '/deepseek/knowledgeLib/slice/detail/' + null + '/' + params.knowledgeId + '/' + params.documentId + '/'
                                    + params.embeddingId
                            });
                        }}>新增切片</Button>

                        <Button type='primary' icon={<ArrowLeftOutlined />} onClick={() => {
                            router.navigate(-1);
                        }}>返回</Button>
                    </div>
                </div>
            </div>
            {
                list.length
                    ?
                    <div className='questionAnswerList'>

                        <div className='applicationList'>
                            <List style={{ height: 400 }}
                                grid={{
                                    gutter: 16,
                                    xs: 1,
                                    sm: 2,
                                    md: 4,
                                    lg: 4,
                                    xl: 6,
                                    xxl: 2, // 展示的列数
                                }}
                                dataSource={list}
                                renderItem={(item) => (
                                    <List.Item>
                                        <div className='card'>
                                            <div style={{ height: 80, overflow: 'auto' }}>
                                                {
                                                    item.slice_text
                                                }
                                            </div>

                                            <Divider plain></Divider>
                                            <div style={{ display: 'flex', justifyContent: 'space-between', overflow: 'auto' }}>

                                                <div style={{ overflow: 'auto' }}>
                                                    <a style={{ marginRight: 20 }} onClick={() => {
                                                        router.navigate({
                                                            pathname: '/deepseek/knowledgeLib/slice/detail/' + item.slice_id + '/' + params.knowledgeId + '/' + params.documentId + '/'
                                                                + params.embeddingId
                                                        });
                                                    }}>
                                                        <SettingOutlined /> 编辑
                                                    </a>
                                                    <a className='text-error' onClick={() => {
                                                        Modal.confirm({
                                                            title: '删除',
                                                            content: `确定删除切片: ` + item.slice_id + ` 吗？`,
                                                            okType: 'danger',
                                                            onOk: async () => {
                                                                const knowledgeId = params.knowledgeId || ''; // 提供默认值
                                                                await deleteSlice(item.slice_id, knowledgeId);
                                                            }
                                                        });
                                                    }}>
                                                        <DeleteOutlined /> 删除
                                                    </a>
                                                </div>

                                                <div>
                                                    {
                                                        item.slice_char_len
                                                    }
                                                </div>
                                            </div>
                                        </div>
                                    </List.Item>
                                )}
                                pagination={paginationConfig} // 分页 
                            />
                        </div>
                    </div>
                    :
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            }
        </div >
    )
};

export default observer(SliceList);