import * as React from 'react';
import { observer } from 'mobx-react';
import { generatePath, useLocation, useParams } from 'react-router-dom';
import { Form, Input, Button, message, Upload, UploadProps } from 'antd';
import { apis } from '@/apis';
import router from '@/router';
import { ArrowLeftOutlined } from '@ant-design/icons';
import config, { getHeaders } from '@/apis/config';

const { TextArea } = Input;

const FormItem = Form.Item;

interface TakaiSliceDetailRequest {
    knowledgeId: string,
    sliceId: string,
    sliceText: string,
}

const SliceDetail: React.FC = () => {

    const [form] = Form.useForm();

    const params = useParams();
    const location = useLocation();
    const { text, page } = location.state;
    const [listLoading, setListLoading] = React.useState(false);

    const appApi = {
        fetchList: async () => {
            setListLoading(true);
            try {
                if (!params.sliceId || !params.knowledgeId) {
                    throw new Error('参数错误');
                }
                const res = await apis.fetchTakaiSliceDetail(params.sliceId, params.knowledgeId);
                const info = res.data.data;
                form.setFieldsValue({
                    slice_id: info.slice_id,
                    slice_text: info.slice_text,
                    document_id: info.document_id,
                })
                console.log(res, 'info');
            } catch (error) {
                console.error(error);
            } finally {
                setListLoading(false);
            }
        }
    };

    const init = async () => {
        if (params.sliceId && params.sliceId !== 'new') {
            await appApi.fetchList();
        }
    }

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

    const [cursorEndPosition, setCursorEndPosition] = React.useState<number>(0);

    // 上传图片配置
    const uploadImageConfig: UploadProps = {
        name: 'files',
        action: config.baseURL + `/deepseek/api/uploadSliceImage/${params.knowledgeId}/${params.documentId}`,
        method: 'POST',
        headers: getHeaders(),
        accept: ['.png', '.jpg', '.jpeg'].join(','),
        multiple: true,
        maxCount: 5,
        showUploadList: false,
    };

    return (
        <div>
            <div className='questionAnswerList'>
                <div style={{ overflow: 'hidden' }}>
                    <Form
                        style={{ paddingTop: '20px', height: '100%' }}
                        form={form}
                        layout='vertical'
                    >
                        <FormItem
                            name="slice_text"
                            rules={[{ required: true, message: '切片内容不能为空' }]}>
                            <TextArea
                                style={{
                                    width: '50%',
                                    height: '200px',
                                    overflow: 'auto',
                                    resize: 'both',
                                    boxSizing: 'border-box',

                                }}
                                placeholder=""
                                autoSize={{ minRows: 20, maxRows: 5000 }}
                                onBlur={(e) => {
                                    const target = e.target as HTMLTextAreaElement;
                                    // 更新光标终点位置
                                    setCursorEndPosition(target.selectionEnd);
                                }}
                            />
                        </FormItem>
                        <Upload
                            {...uploadImageConfig}
                            onChange={(info) => {
                                const insertToSliceText = (text: string) => {
                                    const { slice_text } = form.getFieldsValue();

                                    // 获取当前光标位置
                                    const position = cursorEndPosition;

                                    let newValue = '';

                                    if (!slice_text) {
                                        newValue = text;
                                    } else {
                                        newValue = slice_text.slice(0, position) + text + slice_text.slice(position);
                                    }

                                    form.setFieldsValue({ slice_text: newValue });
                                }
                                const file = info.file;
                                if (file.status === 'done') {// 上传成功
                                    const { code, msg, data } = file.response;
                                    if (code === 200) {
                                        const text = data.join('');
                                        insertToSliceText(text);
                                        message.success('上传成功');
                                    } else {
                                        message.error(msg);
                                    }
                                } else if (file.status === 'error') {// 上传失败
                                    message.error('上传失败');
                                }
                            }}
                        >
                            <Button type='primary'>
                                解析图片
                            </Button>
                        </Upload>
                        <Button
                            style={{ margin: '0 16px' }}
                            type='primary'
                            icon={<ArrowLeftOutlined />}
                            onClick={() => {
                                const path = generatePath('/deepseek/knowledgeLib/:knowledgeId/slice/:documentId/:embeddingId', {
                                    knowledgeId: params.knowledgeId as string,
                                    documentId: params.documentId as string,
                                    embeddingId: params.embeddingId as string,
                                });
                                router.navigate({ pathname: path }, { state: { text: text, page } });
                            }}
                        >
                            返回
                        </Button>
                        <Button
                            type='primary'
                            onClick={() => {
                                form.validateFields().then(async (values) => {
                                    // 验证参数是否存在
                                    if (!params.knowledgeId || !params.sliceId) {
                                        message.error('知识库ID或切片ID无效');
                                        return;
                                    }
                                    const data = values;
                                    const info = {
                                        knowledgeId: params.knowledgeId,
                                        sliceId: params.sliceId === null ? '' : params.sliceId,
                                        sliceText: values.slice_text,
                                        documentId: params.documentId,
                                    };
                                    let res = null;
                                    if (params.sliceId && params.sliceId !== 'null' && params.sliceId !== 'new') {
                                        // 编辑应用
                                        res = await apis.modifyTakaiSliceInfo(info as any);
                                    } else {
                                        res = await apis.addTakaiSlice(info as any);
                                    }
                                    if (res.code === 200 && res.data === 1) {
                                        if (params.sliceId && params.sliceId !== 'null' && params.sliceId !== 'new') {
                                            message.success('修改成功');
                                        } else {
                                            message.success('新增成功');
                                        }
                                    } else {
                                        if (params.sliceId && params.sliceId !== 'null' && params.sliceId !== 'new') {
                                            message.error('修改失败');
                                        } else {
                                            message.error('新增失败');
                                        }
                                    }
                                    const path = generatePath('/deepseek/knowledgeLib/:knowledgeId/slice/:documentId/:embeddingId', {
                                        knowledgeId: params.knowledgeId as string,
                                        documentId: params.documentId as string,
                                        embeddingId: params.embeddingId as string,
                                    });
                                    router.navigate({ pathname: path }, { state: { text: text, page } });
                                }).catch((error) => {
                                    console.error(error);
                                });
                            }}
                        >
                            保存
                        </Button>
                    </Form>
                </div>
            </div>
        </div>
    )
};

export default observer(SliceDetail);