import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Upload, message, UploadProps } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { apis } from '@/apis';
import { downloadFile } from '@/utils/index';
import { getHeaders } from '@/apis/config';
const { TextArea } = Input;
const { Option } = Select;
const { Dragger } = Upload;

interface Props {
    openDataManagementMode: boolean;
    onCancel: () => void;
    onSubmit?: (values: any) => void;
    reviewRagdata?: any;
}
const dataManagementMode: React.FC<Props> = ({ openDataManagementMode, onCancel, onSubmit,reviewRagdata }) => {
    const [form] = Form.useForm();
    const [fileOssList, setFileOssList] = React.useState<any>([]); // 选中的列表OSS信息
    const [knowledgeList, setKnowledgeList] = React.useState<Array<{ label: string; value: string }>>([]);// 知识库列表
    useEffect(() => {
        if (!openDataManagementMode) {
            form.resetFields();
            setFileOssList([]);
        }
        if(openDataManagementMode){
            fetchGetApplicationList();
        }
    }, [openDataManagementMode, form]);
    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            console.log(values, 'values---');
            // values.files = fileOssList;
            // if (onSubmit) onSubmit(values);
            // message.success('创建任务成功');
            const res: any = await apis.createDatasetApi({
                name: values.name,
                appId: values.appId,
                description: values.description,
                ossId: fileOssList[0]?.ossId,
                url: fileOssList[0]?.url,
            });
            if (res.code === 200) {
                message.success('创建数据集成功');
                onSubmit && onSubmit(res.data);
            } else {
                message.error(res.msg || '创建数据集失败');
            }
            onCancel();
        } catch (err) {
            // 校验失败，表单将显示错误
        }
    };
    const fetchGetApplicationList = async (typeId?: string | null, name?: string) => {
        try {
            const data = {
                pageSize: 500,
                pageNum: 1,
                userId: '1',
                isCollect: null,
                typeId: null
                // name: name,
            }
            const res: any = await apis.fetchTakaiAppList({...data});
            // 解析返回并设置状态
            if (res && res.rows) {
                setKnowledgeList(res.rows.map((item: any) => ({ label: item.name, value: item.appId })));
                form.setFieldsValue({ appId: reviewRagdata });
            }

        } catch (error) {
            console.error('Failed to fetch app list:', error);
        } finally {
        }
    }
    // 批量删除oss文件
    const onDeleteOssFileApi = async (ossIds: string) => {
        try {
            const res: any = await apis.deleteOssFileApi(ossIds);
            if (res.code !== 200) {
                message.error('删除oss文件失败');
            }
        } catch (error) {
            console.error('删除oss文件失败:', error);
        }
    };
    const [oldFileList, setOldFileList] = React.useState<any>([]); // 选中的本地文件列表
    const [oldfileName, setOldfileName] = React.useState<any>(''); // 选中的本地文件的信息
    const uploadProps: UploadProps = {
        name: 'file',
        // 根据选择的分类决定是否允许多选与最大数量：分类为 '3' 时只允许单文件，其余允许最多 5 个
        multiple: false,
        maxCount: 1,
        action: '/api/resource/oss/upload',
        headers: getHeaders(),
        // 使用受控 fileList，便于自定义已上传文件列表的展示和管理
        fileList: oldFileList,
        beforeUpload(file, fileList) {
            const maxCount = 1
            const currentCount = (oldFileList || []).length;
            const incomingCount = fileList?.length || 1;
            if (currentCount + incomingCount > maxCount) {
                message.error(`最多只能上传 ${maxCount} 个文件`);
                return Upload.LIST_IGNORE;
            }
            const allowedExtensions = ['xlsx', 'xls', 'json'];
            // const allowedExtensions = ['*']; // 允许所有格式上传 不限制文件类型
            // const allowedExtensions = ['xlsx','xls','csv']; // 允许所有格式上传

            // 检查文件类型
            for (const file of fileList) {
                const fileExt = file.name.split('.').pop()?.toLowerCase();
                if (!fileExt || !allowedExtensions.includes(fileExt)) {
                    message.error(`不支持 ${fileExt} 格式的文件上传`);
                    return Upload.LIST_IGNORE;
                }
            }

            // 检查文件大小
            let totalSize = 0;
            for (const file of fileList) {
                const fileExt = file.name.split('.').pop()?.toLowerCase();
                const fileSizeMB = file.size / 1024 / 1024;

                if (fileSizeMB > 100) {
                    message.error('单个文件不能大于100M');
                    return Upload.LIST_IGNORE;
                }
                totalSize += fileSizeMB;
            }

            if (totalSize > 150) {
                message.error('文件总大小超过150M');
                return Upload.LIST_IGNORE;
            }
        },
        onChange(info) {
            const { status, response } = info.file;
            console.log(info, 'info.file----');

            // 使用 Upload 提供的 fileList 更新受控状态
            const nextFileList = info.fileList || [];
            setOldFileList(nextFileList as any);
            // 同步到 Form 中的 `data` 字段，确保 Form 校验可以感知文件变化
            form.setFieldsValue({ data: nextFileList });
            // 尝试触发单字段校验，及时展示上传必填提示
            form.validateFields(['data']).catch(() => { });

            // 当单个文件上传完成且后端返回成功时，更新 OSS 列表中对应项
            if (status === 'done') {
                if (response?.code === 200) {
                    message.success(`${info.file.name} 上传成功`);
                    // 从 fileList 中抽取有 response.data 的条目作为 OSS 列表
                    const ossItems = nextFileList
                        .map((f: any) => {
                            return {
                                name: f.name.split('.')[0],
                                ...f.response?.data
                            }
                        })
                        .filter((d: any) => !!d);

                    console.log(ossItems, 'ossItems---');
                    setFileOssList(ossItems as any);

                    setOldfileName(info.file.name);
                } else {
                    message.error(response?.msg || '上传失败');
                }
            } else if (status === 'error') {
                message.error(`${info.file.name} 上传失败`);
            }
        },
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
        onRemove(file) {
            // 先从本地受控 fileList 中移除
            setOldFileList((prev: any[]) => (prev || []).filter((f) => f.uid !== file.uid));
            // 如果该文件已上传并携带后端返回数据，则尝试删除 OSS 记录
            const resFile = file?.response?.data;
            if (resFile?.ossId) {
                onDeleteOssFileApi(`${resFile.ossId}`);
                setFileOssList((pre: any[]) => (pre || []).filter((item: any) => item.ossId !== resFile.ossId));
            }
            return true;
        }

    };

    return (
        <Modal
            open={openDataManagementMode}
            title="创建数据集"
            onCancel={onCancel}
            onOk={handleOk}
            okText="提交"
            cancelText="取消"
        >
            <Form form={form} layout="vertical">
                <Form.Item
                    name="name"
                    label="数据集名称"
                    rules={[{ required: true, message: '请输入数据集名称' }]}
                >
                    <Input placeholder="输入数据集名称" />
                </Form.Item>
                <Form.Item
                    name="appId"
                    label="选择应用"
                    rules={[{ required: true, message: '请选择应用' }]}
                >
                    <Select
                        disabled={reviewRagdata?true:false}
                        showSearch={true}
                        filterOption={(input, option) => (option?.children as unknown as string)?.toLowerCase()?.includes(input.toLowerCase())}
                        className='form-element-select'
                        placeholder='请选择需要引用的应用'
                    >
                        {
                            knowledgeList.map((item, index) => {
                                return <Option value={item.value} key={index}>
                                    {item.label}
                                </Option>
                            })
                        }
                    </Select>
                </Form.Item>

                <Form.Item name="description" label="数据集描述">
                    <TextArea rows={4} placeholder="请输入数据集描述（可选）" />
                </Form.Item>
                <Form.Item
                    name="data"
                    label="上传数据"
                    rules={[
                        {
                            required: true,
                            validator: (_rule, value) => {
                                const list = value || oldFileList || [];
                                return list && list.length > 0
                                    ? Promise.resolve()
                                    : Promise.reject(new Error('请至少上传一个文件'));
                            },
                        },
                    ]}
                >
                    <div>
                        <p className='pb-[10px]'>
                            需上传已标注的文本数据集，如不清楚上传格式，可 <a href="#" onClick={async () => {
                                const blob: any = await apis.datasetExportApi({});
                                downloadFile(blob, '数据集上传模版');
                            }} >下载模版</a>
                        </p>
                        <Dragger {...uploadProps}>
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p className="ant-upload-text">点击或拖拽文件到此处上传</p>
                            <p className="ant-upload-hint"> 目前仅支持上传：xlsx，json文件类型，最多上传1个文件 </p>
                            <p className='ant-upload-hint'>限制：100M文件大小、10万行数据</p>
                        </Dragger>
                    </div>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default dataManagementMode;