import * as React from 'react';
import { Modal, Spin, Form, Input, Select, message, Checkbox, GetProp, Tooltip } from 'antd';
import { InboxOutlined, QuestionCircleOutlined } from '@ant-design/icons';

import { apis, ModifyDocumentSettingApiParams } from '@/apis';

import useAppState from '@/store';
const { getAppState } = useAppState();
const { TextArea } = Input;

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


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

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

    const [form] = Form.useForm();

    const [loading, setLoading] = React.useState<boolean>(false);

    const [isVisibleSlice, setIsVisibleSlice] = React.useState(false);
    const [titleName, setTitleName] = React.useState<string>('');

    const [standardClass, setStandardClass] = React.useState<any>([]);// 选择分类-下拉框
    const [parsingTypeList, setParsingTypeList] = React.useState<any>([]);// 解析工具
    const [parsingTypeListBackup, setParsingTypeListBackup] = React.useState<any[]>([]);// 解析工具-下拉选项-备份数据

    const [splittingOldList, setSplittingOldList] = React.useState<any[]>([]); // 旧的切分规则列表
    const [splittingTypeList, setSplittingTypeList] = React.useState<any>([]); // 选择切分规则
    const [standardClassification, setStandardClassification] = React.useState<string>(''); // 选择分类设置
    const onChangeF = (value: string) => {
        if (value === '0') {
            setIsVisibleSlice(!isVisibleSlice);
        } else {
            setIsVisibleSlice(false);
        }
    };
    // 获取解析工具
    const fetchAppstandardClass = async () => {
        try {
            const res = await apis.fetchTakaiAppTypeList('parsing_type');
            const list = res.data.map((item: any) => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue,
                }
            });
            form.setFieldsValue({
                customSeparator: record?.customSeparator,
            })

            setParsingTypeList(list);
            setParsingTypeListBackup(list);
        } catch (error: any) {
            console.error(error);
        }
    }
    // 获取向默认切分规则
    const fetchsplittingType = async () => {
        try {
            const res = await apis.fetchTakaiAppTypeList('splitting_type');
            const list = res.data.map((item: any) => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue,
                    remark: item.remark,
                }
            });
            if (record.customSeparator === '0') {
                setIsVisibleSlice(!isVisibleSlice);
            }
            if (record.parsingType === '2') {
                const newList = list.filter((item: any) => item.value !== '3');
                setSplittingTypeList(newList);
            }else{
                setSplittingTypeList(list);
            }
            setSplittingOldList(list);
        } catch (error: any) {
            console.error(error);
        }
    }
    const init = async () => {
        setLoading(true);
        if (props.id) {
            fetchsplittingType()
            fetchAppstandardClass()
            
        }
        setLoading(false);
        const res: any = await getAppState();
        const reslist = res.filter((item: any) => {
            if (record?.standardClassification === '0' || record?.standardClassification === '1') {
                if (item.value === '0' || item.value === '1') {
                    return item
                }
            }
            if (record?.standardClassification === '3') {
                if (item.value === '3') {
                    return item
                }
            }
            if (record?.standardClassification === '2') {
                if (item.value === '2') {
                    return item
                }
            }
        })
        setStandardClass(reslist);
    };

    React.useEffect(() => {
        init();
        form.setFieldsValue({
            parsingType: record?.parsingType,
            customSeparator: record?.customSeparator,
            standardClassification: record?.standardClassification,
            sliceValue: record?.sliceValue,
            name: record?.name,
            remark: record?.remark,
        })
        setStandardClassification(record?.standardClassification);
    }, []);

    // 点击确定
    const handleClickConfirm = () => {
        form.validateFields().then(async (values) => {
            const data = { ...record, ...values, konowledge_id: record.knowledgeId };
            console.log(loading, 'loading');
            await onClickConfirm(props.id, data);
        }).catch((error) => {
            console.error(error);
        })
    };

    return (
        <Modal
            width={600}
            title='知识配置'
            maskClosable={false}
            centered={true}
            open={open}
            onOk={handleClickConfirm}
            onCancel={onClickCancel}
            confirmLoading={loading}
        >
            <Spin spinning={loading}>
                <Form form={form} layout='vertical'>
                    <FormItem
                        label='分类设置'
                        name='standardClassification'
                    >
                        <Select
                            style={{ width: '100%' }}
                            allowClear={true}
                            optionLabelProp="label"
                            placeholder='请选择分类设置'
                            onChange={(e) => {
                                // 切换分类时，清空已选本地文件與 OSS 列表
                                setStandardClassification(e);
                                if (e === '0') {
                                    const newSplittingList = splittingOldList.filter((item: any) => item.value === '3');
                                    setSplittingTypeList(newSplittingList);
                                    form.setFieldsValue({
                                        customSeparator: newSplittingList[0]?.value,
                                    });

                                    const newParsingTypeList = parsingTypeListBackup.filter((item: any) => item.value === '0');
                                    setParsingTypeList(newParsingTypeList);
                                    form.setFieldsValue({
                                        parsingType: newParsingTypeList[0]?.value,
                                    })
                                } else {
                                    setSplittingTypeList(splittingOldList);
                                    setParsingTypeList(parsingTypeListBackup);
                                }
                                if (e === '1') {
                                    // 通用规范
                                    form.setFieldsValue({
                                        customSeparator: '2',
                                    });
                                }
                                form.setFieldsValue({
                                    name: '',
                                });
                            }}
                        >
                            {
                                standardClass.map((item: any, index: any) => {
                                    return <Option value={item.value} key={index} label={item.label}>
                                        {item.label}
                                        <Tooltip title={item.remark} >
                                            <QuestionCircleOutlined style={{ color: '#FF9800', marginLeft: '3px' }} />
                                        </Tooltip>
                                    </Option>
                                })
                            }
                        </Select>
                    </FormItem>

                    {(standardClassification === '0' || standardClassification === '1') && <><FormItem
                        label='解析工具'
                        name='parsingType'
                    >
                        {/* <p>{standardClass}</p> */}
                        <Select
                            style={{ width: '100%' }}
                            placeholder='请选择解析设置'
                            allowClear={true}
                            onChange={(e) => {
                                if (e === '2') {
                                    const newSplittingList = splittingOldList.filter((item: any) => item.value !== '3');
                                    setSplittingTypeList(newSplittingList);
                                    form.setFieldsValue({
                                        customSeparator: newSplittingList[0]?.value,
                                    });
                                } else {
                                    setSplittingTypeList(splittingOldList);
                                }
                            }}
                        >
                            {
                                parsingTypeList.map((item: any, index: any) => {
                                    return <Option value={item.value} key={index}>
                                        {item.label}
                                    </Option>
                                })
                            }
                        </Select>
                    </FormItem>
                        <FormItem
                            label='切片设置'
                            name='customSeparator'
                        >
                            <Select
                                style={{ width: '100%' }}
                                allowClear={true}
                                placeholder='请选择切片设置'
                                onChange={onChangeF}
                                optionLabelProp="label"
                            >
                                {
                                    splittingTypeList.map((item: any, index: any) => {
                                        return <Option value={item.value} key={index} label={item.label}>
                                            {item.label}
                                            <Tooltip title={item.remark} >
                                                <QuestionCircleOutlined style={{ color: '#FF9800', marginLeft: '3px' }} />
                                            </Tooltip>
                                        </Option>
                                    })
                                }
                            </Select>
                        </FormItem></>}
                    {isVisibleSlice &&
                        <FormItem
                            label='分隔符'
                            name='sliceValue'
                            rules={[{ required: true, message: '自定义切片设置不能为空' }]}
                        >
                            <Input max={1024}
                            />
                        </FormItem>
                    }
                    {standardClassification === '3' && <><FormItem
                        label='文件名称'
                        name='name'
                        rules={[{ required: true, message: '文件名称不能为空', whitespace: true }]}
                    >
                        <Input placeholder='请输入文件名称' />
                    </FormItem>
                        <FormItem
                            label='描述'
                            name='remark'
                            rules={[{ required: true, message: '描述不能为空', whitespace: true }]}
                        >
                            <TextArea
                                placeholder='请输入描述信息'
                                showCount={true}
                                rows={6}
                                maxLength={500}
                            />
                        </FormItem></>}
                    <div style={{ width: '100%', height: 10 }}></div>
                </Form>
            </Spin>
        </Modal>
    );
};

export default InfoModalSetting;