import React, { useState, useEffect } from 'react';
import { Modal, Tree, Button, message, Spin } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { treeList, lock } from '../services'; // 请替换为你的实际接口路径

interface LockNode extends DataNode {
    key: string;
    title: string;
    categoryLibraryId: string;
    categoryId: string;
    lockType: string;
    children?: LockNode[];
}
 
const LockManagerModal: React.FC<{
    visible: boolean;
    storeId: string;
    onCancel: () => void;
}> = ({ visible, storeId, onCancel }) => {
    const [treeData, setTreeData] = useState<LockNode[]>([]);
    const [loading, setLoading] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    // 初始化加载时设置展开 keys
    const loadTree = async () => {
        setLoading(true);
        try {
            const res = await treeList({ categoryLibraryId: storeId });
            if (res.code === 200) {
                const formatted = formatData(res.data);
                setTreeData(formatted);

                const keys: string[] = [];
                const collect = (nodes: LockNode[]) => {
                    nodes.forEach(n => {
                        keys.push(n.key);
                        if (n.children && n.children.length) collect(n.children);
                    });
                };
                collect(formatted);
                setExpandedKeys(keys);
                setAutoExpandParent(true);
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (visible) {
            loadTree();
        }
    }, [visible]);

    const formatData = (list: any[]): LockNode[] => {
        return list.map(item => ({
            key: item.categoryId,
            title: item.categoryName,
            categoryId: item.categoryId,
            categoryLibraryId: item.categoryLibraryId,
            lockType: item.lockType ? item.lockType : '0',
            children: item.categoryList ? formatData(item.categoryList) : [],
        }));
    };
    const formatTitle = (node: LockNode) => {
        return (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ flex: 1, paddingRight: 24 }}>{node.title}</span>
            <Button
              size="small"
              type={node.lockType === '1' ? 'default' : 'primary'}
              style={{
                backgroundColor: node.lockType === '0' ? '' : '#52c41a', // 锁定红色，解锁绿色
                borderColor: node.lockType === '0' ? '' : '#52c41a',
                color: '#fff',
              }}
              onClick={(e) => {
                e.stopPropagation();
                toggleNodeLock(node.key);
              }}
            >
              {node.lockType === '1' ? '解锁' : '锁定'}
            </Button>
          </div>
        );
      };

    const toggleNodeLock = (key: string) => {
        const toggleLock = (nodes: LockNode[]): LockNode[] => {
            return nodes.map(node => {
                if (node.key === key) {
                    return { ...node, lockType: node.lockType === '1' ? '0' : '1' };
                }
                if (node.children) {
                    return { ...node, children: toggleLock(node.children) };
                }
                return node;
            });
        };
        setTreeData(prev => toggleLock(prev));
    };

    const handleSubmit = async () => {
        setSubmitLoading(true);
        try {
            const payload: { categoryId: string; lockType: string, categoryLibraryId: string }[] = [];
            const collectData = (nodes: LockNode[]) => {
                nodes.forEach(node => {
                    payload.push({ categoryId: node.categoryId, lockType: node.lockType,  categoryLibraryId: node.categoryLibraryId });
                    if (node.children) {
                        collectData(node.children);
                    }
                });
            };
            collectData(treeData);
            console.log(payload,'payload');
            
            const res = await lock(payload); 
            if (res.code === 200) {
                message.success('提交成功');
                onCancel();
            }
        } finally {
            setSubmitLoading(false);
        }
    };

    const renderTree = (nodes: LockNode[]): DataNode[] => {
        return nodes.map(node => ({
            ...node,
            title: formatTitle(node),
            children: node.children ? renderTree(node.children) : [],
        }));
    };

    return (
        <Modal
            title="品类锁定管理"
            visible={visible}
            onCancel={onCancel}
            onOk={handleSubmit}
            confirmLoading={submitLoading}
            width={600}
        >
            <Spin spinning={loading}>
                <Tree
                    treeData={renderTree(treeData)}
                    selectable={false}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onExpand={(keys) => {
                        setExpandedKeys(keys as string[]);
                        setAutoExpandParent(false);
                    }}
                />
            </Spin>
        </Modal>
    );
};

export default LockManagerModal;
