import * as React from 'react';
import { observer } from 'mobx-react';
import { generatePath, useLocation, 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';
import LocalStorage from '@/LocalStorage';
import { makeAutoObservable } from 'mobx';

const FormItem = Form.Item;

const page = makeAutoObservable({
    pageNum: 1,
    pageSize: 10,
    total: 0,
});

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,
    };

    const location = useLocation();
    const [listLoading, setListLoading] = React.useState(false);
    const [list, setList] = React.useState<Item[]>([]);


    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 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
                })
                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);
                page.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 () => {
        if (location.state) {
            const { text, page: currentPage } = location.state;
            if (text) {
                form.setFieldsValue({
                    text: text,
                });
            }
            if (currentPage && currentPage.pageNum && currentPage.pageSize) {
                page.pageNum = currentPage.pageNum;
                page.pageSize = currentPage.pageSize;
                page.total = currentPage.total;
            }
        }

        const values = form.getFieldsValue();

        const searchText = values.text ? values.text : '';

        await appApi.fetchList({ searchText: searchText });
    }

    React.useEffect(() => {
        init();
        const cFlag = LocalStorage.getStatusFlag('deepseek:slice:create');
        setCreateFlag(cFlag);
        const dFlag = LocalStorage.getStatusFlag('deepseek:slice:delete');
        setDeleteFlag(dFlag);
        const tFlag = LocalStorage.getStatusFlag('deepseek:slice:update');
        setUpdateFlag(tFlag);
        const lFlag = LocalStorage.getStatusFlag('deepseek:slice:list');
        setListFlag(lFlag);
        return () => {
            page.pageNum = 1;
            page.pageSize = 10;
            page.total = 0;
        };
    }, [])

    const paginationConfig: PaginationConfig = {
        // 显示数据总量
        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 (pageNum, pageSize) => {
            page.pageNum = pageNum;
            page.pageSize = pageSize;
            const values = form.getFieldsValue();
            const searchText = values.text ? values.text : '';
            await appApi.fetchList({ searchText: searchText });
        },
    };

    return (
        <div>
            <div className='slice-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>
                        {
                            createFlag &&
                            <Button
                                style={{ marginRight: 16 }}
                                type='primary'
                                icon={<PlusOutlined />}
                                onClick={() => {
                                    const path = generatePath('/deepseek/knowledgeLib/:knowledgeId/slice/:documentId/:embeddingId/:sliceId', {
                                        knowledgeId: params.knowledgeId as string,
                                        documentId: params.documentId as string,
                                        embeddingId: params.embeddingId as string,
                                        sliceId: 'new',
                                    });
                                    const { text } = form.getFieldsValue();
                                    router.navigate({ pathname: path }, { state: { text: text, page: { pageNum: page.pageNum, pageSize: page.pageSize, total: page.total } } });
                                }}>
                                新增切片
                            </Button>
                        }
                        <Button type='primary' icon={<ArrowLeftOutlined />} onClick={() => {
                            const path = generatePath('/deepseek/knowledgeLib/:knowledgeId', {
                                knowledgeId: params.knowledgeId as string,
                            });
                            router.navigate({ pathname: path });
                        }}>
                            返回
                        </Button>
                    </div>
                </div>
            </div>
            {
                list.length
                    ?
                    <div className='questionAnswerList'>

                        <div className='applicationList'>
                            <List
                                style={{ height: 400 }}
                                loading={listLoading}
                                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' }}>
                                                    {
                                                        updateFlag &&
                                                        <a
                                                            style={{ marginRight: 20 }}
                                                            onClick={() => {
                                                                const path = generatePath('/deepseek/knowledgeLib/:knowledgeId/slice/:documentId/:embeddingId/:sliceId', {
                                                                    knowledgeId: params.knowledgeId as string,
                                                                    documentId: params.documentId as string,
                                                                    embeddingId: params.embeddingId as string,
                                                                    sliceId: item.slice_id,
                                                                });
                                                                const { text } = form.getFieldsValue();
                                                                router.navigate({ pathname: path }, { state: { text: text, page: { pageNum: page.pageNum, pageSize: page.pageSize, total: page.total } } });
                                                            }}>
                                                            <SettingOutlined /> 编辑
                                                        </a>
                                                    }

                                                    {
                                                        deleteFlag &&
                                                        <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);