import React, { useState, useEffect } from 'react';
import { Modal, Form, Select, Button, Tree, message, Input } from 'antd';
//组件
import SupplierSelector from './SupplierSelector';
// 请求
import { categoryTree, add } from '../services';
const { Option } = Select;

// 主体
const CreateModal: React.FC<{ visible: boolean; onCancel: () => void; }> = ({ visible, onCancel }) => {

    const [form] = Form.useForm();
    //品类选择
    const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
    //供应商
    const [selectedSuppliers, setSelectedSuppliers] = useState<any[]>([]);
    //供应商弹出
    const [supplierModalVisible, setSupplierModalVisible] = useState(false);
    //品类选择渲染数据
    const [categoriesTreeData, setCategoriesTreeData] = useState([]);
    //品类选择数据中字段转换
    const convertTreeData = (data: any) => {
        return data.map((item: any) => ({
            ...item,
            title: item.categoryName,
            key: item.id,
            children: item.children ? convertTreeData(item.children) : undefined,

        }));
    }
    function findLeafKeys(treeData: any[]): string[] {
        let leafKeys: string[] = [];
        function dfs(nodes: any[]) {
            nodes.forEach(node => {
                if (!node.children || node.children.length === 0) {
                    leafKeys.push(node.key);
                } else {
                    dfs(node.children);
                }
            });
        }
        dfs(treeData);
        return leafKeys;
    }
    //品类选择
    const onCheck = (
        checkedKeysValue:
            | React.Key[]
            | { checked: React.Key[]; halfChecked: React.Key[] }
    ) => {
        const keys = Array.isArray(checkedKeysValue)
            ? checkedKeysValue
            : checkedKeysValue.checked;

            // 只取叶子节点 key
        const leafKeys = findLeafKeys(convertTreeData(categoriesTreeData));
        const onlyLeafChecked = keys.filter(key => leafKeys.includes(String(key)));
        setCheckedKeys(keys); // UI 显示用，还是全量
        form.setFieldsValue({ categoryIds: onlyLeafChecked }); // 只存叶子到表单
    };
    
    // 提交
    const onFinish = async (values: any) => {
        const finalPayload: {
            coscoAccessWork: {
                accessWorkName: string;
                deptId: string;
              };
              categoryIds: string[];
              supplierIds: string[];
        } = {
            coscoAccessWork: {
                accessWorkName: '',
                deptId: '',
            },
            categoryIds: [],
            supplierIds: [],
        };
        //标题名称
        finalPayload.coscoAccessWork.accessWorkName = values.accessWorkName;
        //准入部门
        finalPayload.coscoAccessWork.deptId = values.deptId;
        //品类选择
        finalPayload.categoryIds = values.categoryIds;
        //选择供应商
        if(values.supplier.length != 0) {
            values.supplier.forEach((item: { id: string }) => {
                finalPayload.supplierIds.push(item.id)
            })
        }
        console.log( finalPayload, values);
        const res = await add(finalPayload);
        if (res?.success) {
            message.success('创建成功');
            form.resetFields();
            setCheckedKeys([]);
            setSelectedSuppliers([]);
            onCancel();
        } else {
            message.error('创建失败');
        }
    };
    //初始化
    useEffect(() => {
        categoryTree().then((res) => {
            const { code, data } = res;
            if (code == 200) {
                setCategoriesTreeData(data)
            }
        })
    }, [visible, form]);
    return (
        <Modal
            title="品类准入"
            visible={visible}
            footer={null}
            onCancel={() => {
                form.resetFields();
                setCheckedKeys([]);
                setSelectedSuppliers([]);
                onCancel();
            }}
            width="700px"
            destroyOnClose
        >
            <Form
                form={form}
                onFinish={onFinish}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
            >
                <Form.Item
                    label="标题名称"
                    name="accessWorkName"
                    rules={[{ required: true, message: '请输入标题名称' }]}
                >
                    <Input placeholder="请输入标题名称" allowClear />
                </Form.Item>
                <Form.Item
                    label="准入部门"
                    name="deptId"
                    rules={[{ required: true, message: '请选择准入部门' }]}
                >
                    <Select placeholder="请选择部门">
                        <Option value="DEPT001">部门A</Option>
                        <Option value="DEPT001">部门B</Option>
                    </Select>
                </Form.Item>


                <Form.Item
                    label="品类选择"
                    name="categoryIds"
                    rules={[{ required: true, message: '请选择准入品类' }]}
                >
                    <Tree
                        checkable
                        selectable={false}
                        treeData={convertTreeData(categoriesTreeData)}
                        checkedKeys={checkedKeys}
                        onCheck={onCheck}
                        defaultExpandAll
                        style={{
                            maxHeight: 200,
                            overflowY: 'auto',
                            border: '1px solid #d9d9d9',
                            padding: 8,
                            borderRadius: 4,
                        }}
                    />
                </Form.Item>

                <Form.Item
                    label="选择供应商"
                    name="supplier"
                    rules={[{ required: true, message: '请选择供应商' }]}
                >
                    <Button onClick={() => setSupplierModalVisible(true)}>
                        选择供应商
                    </Button>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 6 }}>
                    <Button type="primary" htmlType="submit" style={{ marginRight: 8 }}>
                        提交
                    </Button>
                    <Button
                        onClick={() => {
                            form.resetFields();
                            setCheckedKeys([]);
                            setSelectedSuppliers([]);
                        }}
                    >
                        重置
                    </Button>
                </Form.Item>
            </Form>

            <SupplierSelector
                visible={supplierModalVisible}
                onCancel={() => setSupplierModalVisible(false)}
                onSelect={(selected) => {
                    setSelectedSuppliers(selected);
                    form.setFieldsValue({ supplier: selected });
                    setSupplierModalVisible(false);
                }}
            /> 
        </Modal>
    );
};

export default CreateModal;
