import React, { useState, useEffect } from 'react';
import { Modal, TreeSelect, Button, message } from 'antd';
//本地服务/接口
import { treeData } from '../services';


interface Props {
    visible: boolean;
    onCancel: () => void;
}

const CategoryAddModal: React.FC<Props> = ({ visible, onCancel }) => {
    const [value, setValue] = useState<string[]>([]);
    // 树数据
    const [dataTree, setDataTree] = useState<any[]>([]);

    const [submitting, setSubmitting] = useState(false);

    useEffect(() => {
        if (!visible) setValue([]);
        //tree数据
        treeData().then((res) => {
            const { code, data } = res;
            if (code == 200) {
                setDataTree(data)
            }
        })
    }, [visible]);

    // 提交方法
    const handleOk = async () => {
        if (value.length === 0) {
            message.warning('请选择品类');
            return;
        }
        setSubmitting(true);
        try {
            // TODO: 替换为你自己的接口调用
            // const res = await addCategory({ categoryIds: value });
            // 假设接口成功
            // if (res.code === 200) {
            //   message.success('新增品类成功');
            //   onCancel();
            // } else {
            //   message.error(res.msg || '操作失败');
            // }
            // 示例（去掉上面的注释用你自己的接口）
            setTimeout(() => {
                message.success('新增品类成功');
                setSubmitting(false);
                onCancel();
            }, 800);
        } catch (e) {
            message.error('提交失败');
            setSubmitting(false);
        }
    };

    return (
        <Modal
            visible={visible}
            title='品类'
            onCancel={onCancel}
            footer={
                <div style={{ display: 'flex', justifyContent: 'center', gap: 32 }}>
                    <Button
                        type="primary"
                        style={{ minWidth: 120 }}
                        loading={submitting}
                        onClick={handleOk}
                    >确定</Button>
                    <Button style={{ minWidth: 120 }} onClick={onCancel}>取消</Button>
                </div>
            }
            width={600}
            destroyOnClose
            bodyStyle={{ minHeight: 300 }}
        >
            <TreeSelect
                style={{ width: '100%' }}
                value={value}
                treeData={dataTree}
                placeholder="请选择品类"
                allowClear
                multiple
                treeCheckable
                showSearch
                filterTreeNode={(input, node:any) =>
                    (node.title as string).toLowerCase().includes(input.toLowerCase())
                }
                onChange={setValue}
                dropdownStyle={{ maxHeight: 350, overflow: 'auto' }}
            />
        </Modal>
    );
};

export default CategoryAddModal;
