import * as React from 'react';
import { Modal, Spin, Form, Input, Select, Switch, message } from 'antd';
import { apis, CreateOrModifyKnowledgeLibApiParams } from '@/apis';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

interface Props {
    id: string,
    open: boolean,
    onClickConfirm: (id: string, data: CreateOrModifyKnowledgeLibApiParams) => Promise<any>,
    onClickCancel: () => void,
};

const InfoModal: React.FC<Props> = (props: Props) => {
    const {
        id,
        open,
        onClickConfirm,
        onClickCancel
    } = props;

    const [form] = Form.useForm();

    const [loading, setLoading] = React.useState<boolean>(false);
    const [confirmLoading, setConfirmLoading] = React.useState<boolean>(false);
    const mountedRef = React.useRef<boolean>(true);

    type EmbeddingList = {
        label: string,
        value: string,
    }[];
    type AppTypeList = {
        label: string,
        value: string,
        children: {
            label: string,
            value: string,
        }[],
    }[];
    const [embeddingList, setEmbeddingList] = React.useState<EmbeddingList>([]);
    const [standardClass, setStandardClass] = React.useState<AppTypeList>([]); // 选择分类 
    const [modelType, setModelType] = React.useState<AppTypeList>([]); // 选择模型 
    const [splittingType, setSplittingType] = React.useState<AppTypeList>([]); // 选择切分规则 
 // 获取调用模型的列表数据
    const onFetchRerankModelList = async () => {
        const res = await apis.fetchRerankModelList();
        if(res && res.data){
            const list = res.data.map((item: any) => {
                return {
                    label: item.embeddingModel,
                    value: item.embeddingModel,
                }
            })
            setModelType(list);
            // setModeOldList(res.data);
        }
    }
    const getTitle = () => {
        if (id) {
            return '修改知识库';
        } else {
            return '创建知识库';
        }
    };

    // 获取向量化模型列表
    const fetchEmbeddingList = async () => {
        try {
            const res = await apis.fetchEmbeddingList();
            const list = res.data.list.map((item: any) => {
                return {
                    label: item.name,
                    value: item.id,
                }
            });
            setEmbeddingList(list);
        } catch (error: any) {
            console.error(error);
        }
    }

    // 获取知识库详情
    const fetchDetail = async () => {
        try {
            const res = await apis.fetchTakaiKnowledgeLibDetail(props.id);
            const { name, embeddingId, description, visible, knowledgeGraph, standardClassification, splittingType } = res.data;
            console.log('res.data', res.data)
            form.setFieldsValue({
                name: name,
                embeddingId: embeddingId,
                description: description,
                standardClassification: standardClassification,
                // splittingType: splittingType,
                // 将后端的 0/1 或 true/false 映射为 Switch 所需的布尔值
                visible: visible === 0 || visible === '0' || visible === true || visible === 'true',
                knowledgeGraph: knowledgeGraph === 'true' ? true : false,
            });
        } catch (error: any) {
            message.error(error.msg);
        }
    };
    // 获取是否公开类型
    const fetchAppVisible = async (id: string) => {
        try {
            const res = await apis.fetchTakaiAppTypeList('app_visible');
            const list = res.data.map((item: any) => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue,
                }
            });
            if (!id) {
                form.setFieldsValue({
                    visible: list[0].value === '0' ? true : false
                });
            }
        } catch (error: any) {
            console.error(error);
        }
    }
    // // 获取向量化模型
    const fetchAppmodelType = async (id: string) => {
        try {
            const res = await apis.fetchTakaiAppTypeList('model_type');
            const list = res.data.map((item: any) => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue,
                }
            });
            setModelType(list);
            if (!id) {
                form.setFieldsValue({
                    // visible: list[0].value === '0' ? true : false
                });
            }
        } catch (error: any) {
            console.error(error);
        }
    }
    // 获取向默认切分规则
    const fetchsplittingType = async (id: string) => {
        try {
            const res = await apis.fetchTakaiAppTypeList('splitting_type');
            const list = res.data.map((item: any) => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue,
                }
            });
            setSplittingType(list);
            if (!id) {
                form.setFieldsValue({
                    // visible: list[0].value === '0' ? true : false
                });
            }
        } catch (error: any) {
            console.error(error);
        }
    }
    const init = async () => {
        setLoading(true);
        // await fetchEmbeddingList();
        if (props.id) {
            await fetchDetail();
        }
        await fetchAppVisible(props.id);
        onFetchRerankModelList()
        // await fetchAppstandardClass(props.id);
        // await fetchAppmodelType(props.id);
        await fetchsplittingType(props.id);
        setLoading(false);
    };

    React.useEffect(() => {
        init();
        return () => {
            mountedRef.current = false;
        };
    }, []);

    // 点击确定
    const handleClickConfirm = () => {
        form.validateFields().then(async (values) => {
            const data = {
                ...values,
                // 将 Switch 布尔值转换回后端使用的 0/1
                visible: values.visible ? 0 : 1,
                knowledgeGraph: `${values.knowledgeGraph}`
            };
            try {
                setConfirmLoading(true);
                await onClickConfirm(props.id, data);
            } catch (error) {
                console.error(error);
            } finally {
                if (mountedRef.current) setConfirmLoading(false);
            }
        }).catch((error) => {
            console.error(error);
        });
    };

    // 点击取消
    const handleClickCancel = () => {
        // 重置表单，替代 destroyOnClose 的销毁行为
        try {
            form.resetFields();
            if (mountedRef.current) setConfirmLoading(false);
        } catch (error) {
            console.error('Error resetting form fields:', error);
        } finally {
            onClickCancel();
        }
    };

    return (
        <Modal
            width={500}
            title={getTitle()}
            maskClosable={false}
            centered={true}
            open={open}
            confirmLoading={confirmLoading}
            onOk={handleClickConfirm}
            onCancel={handleClickCancel}
        >
            <Spin spinning={loading}>
                <Form form={form} layout='vertical' initialValues={{
                    knowledgeGraph: false, // 给 knowledgeGraph 字段设置初始值为 false
                    // 其他字段的初始值...
                }}
                >
                    <FormItem
                        label='知识库名称'
                        name='name'
                        rules={[{ required: true, message: '知识库名称不能为空', whitespace: true }]}
                    >
                        <Input placeholder='请输入知识库名称' />
                    </FormItem>
                    <div style={{ display: 'flex', gap: 16, marginBottom: 24 }}>
                        <div style={{ flex: 1 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                <span>是否公开</span>
                                <FormItem name='visible' valuePropName='checked' noStyle>
                                    <Switch checkedChildren="是" disabled={id ? true : false} unCheckedChildren="否" />
                                </FormItem>
                            </div>
                        </div>
                        <div style={{ flex: 1 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                <span>知识图谱</span>
                                <FormItem name='knowledgeGraph' valuePropName='checked' noStyle>
                                    <Switch checkedChildren="开启" disabled={true} unCheckedChildren="关闭" />
                                </FormItem>
                            </div>
                        </div>
                    </div>
                    {/* <FormItem
                        label='选择分类'
                        name='standardClassification'
                        rules={[{ required: true, message: '请选择分类' }]}
                    >
                        <Select
                            style={{ width: '100%' }}
                            placeholder='请选择分类'
                            allowClear={true}
                            disabled={id?true:false}
                        >

                            {
                                standardClass.map((item, index) => {
                                    return <Option value={item.value} key={index}>
                                        {item.label}
                                    </Option>
                                })
                            }
                        </Select>
                    </FormItem> */}
                    <FormItem
                        label='向量化模型'
                        name='embeddingId'
                        rules={[{ required: true, message: '向量化模型不能为空' }]}
                    >
                        {
                            <Select
                                style={{ width: '100%' }}
                                placeholder='请选择向量化模型'
                                allowClear={true}
                                disabled={id ? true : false}
                            >
                                {
                                    modelType.map((item, index) => {
                                        return <Option value={item.value} key={index}>
                                            {item.label}
                                        </Option>
                                    })
                                }
                            </Select>
                        }

                    </FormItem>
                    {/* <FormItem
                        label='默认切分规则'
                        name='splittingType'
                        rules={[{ required: true, message: '默认切分规则不能为空' }]}
                    >
                        {
                            <Select
                                style={{ width: '100%' }}
                                placeholder='请选择默认切分规则'
                                allowClear={true}
                            >
                                {
                                    splittingType.map((item, index) => {
                                        return <Option value={item.value} key={index}>
                                            {item.label}
                                        </Option>
                                    })
                                }
                            </Select>
                        }
                    </FormItem> */}
                    <FormItem
                        label='知识库描述'
                        name='description'
                        rules={[{ required: true, message: '知识库描述不能为空', whitespace: true }]}
                    >
                        <TextArea
                            placeholder='知识库描述需要描述清楚知识库中的文件内容，搭建应用时模型会将此作为判断是否获取知识库内容的依据'
                            showCount={true}
                            rows={4}
                            maxLength={100}
                        />
                    </FormItem>
                    <div style={{ width: '100%', height: 10 }}></div>
                </Form>
            </Spin>
        </Modal>
    );
};

export default InfoModal;