import React, { useEffect, useState } from 'react';
import { Modal, Tree, Spin } from 'antd';
import type { DataNode } from 'antd/es/tree';
import type { Key } from 'rc-tree/lib/interface';
import { getPermissionTree } from '../service';

interface PermissionModalProps {
    visible: boolean;
    roleId: number;
    onCancel: () => void;
    onOk: (permissionIds: number[]) => void;
    defaultCheckedKeys?: number[];
}

interface Permission {
    id: number;
    code: string;
    name: string;
    type: string;
    sort: number;
}

interface MenuItem {
    id: number;
    name: string;
    path: string;
    icon: string;
    type: number;
    permissionChildren: MenuItem[];
    permissions: Permission[];
}

const PermissionModal: React.FC<PermissionModalProps> = ({
    visible,
    roleId,
    onCancel,
    onOk,
    defaultCheckedKeys = []
}) => {
    const [loading, setLoading] = useState(false);
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [checkedKeys, setCheckedKeys] = useState<number[]>([]);
    const [idMapping, setIdMapping] = useState<Record<string, number>>({});
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

    // 将菜单和权限数据转换为Tree组件需要的格式
    const convertToTreeData = (menuList: MenuItem[]): { treeData: DataNode[], idMapping: Record<string, number>, expandedKeys: string[] } => {
        const mapping: Record<string, number> = {};
        const expanded: string[] = [];

        const convertMenuToNode = (menu: MenuItem): DataNode => {
            const children: DataNode[] = [];
            const menuKey = `menu-${menu.id}`;
            expanded.push(menuKey);

            // 添加功能权限节点
            if (menu.permissions?.length > 0) {
                menu.permissions.forEach(perm => {
                    const key = `permission-${perm.id}`;
                    mapping[key] = perm.id;
                    children.push({
                        key,
                        title: perm.name,
                        isLeaf: true
                    });
                });
            }

            // 递归处理子菜单
            if (menu.permissionChildren?.length > 0) {
                menu.permissionChildren.forEach(child => {
                    children.push(convertMenuToNode(child));
                });
            }

            return {
                key: menuKey,
                title: menu.name,
                children: children.length > 0 ? children : undefined,
                selectable: false  // 菜单节点不可选择，只能展开/收缩
            };
        };

        const treeData = menuList.map(convertMenuToNode);
        return { treeData, idMapping: mapping, expandedKeys: expanded };
    };

    useEffect(() => {
        const loadPermissionTree = async () => {
            if (!visible) return;
            
            setLoading(true);
            try {
                const response = await getPermissionTree();
                const { treeData: newTreeData, idMapping: newIdMapping, expandedKeys: newExpandedKeys } = convertToTreeData(response);
                setTreeData(newTreeData);
                setIdMapping(newIdMapping);
                setExpandedKeys(newExpandedKeys);
                
                // 设置选中的权限
                setCheckedKeys(defaultCheckedKeys);
                
                console.log('权限树数据:', response);
                console.log('转换后的树数据:', newTreeData);
                console.log('ID映射:', newIdMapping);
                console.log('默认选中的权限:', defaultCheckedKeys);
            } catch (error) {
                console.error('获取权限树失败:', error);
            } finally {
                setLoading(false);
            }
        };

        loadPermissionTree();
    }, [visible, defaultCheckedKeys]);

    const handleCheck = (checked: Key[] | { checked: Key[]; halfChecked: Key[] }) => {
        const checkedKeys = Array.isArray(checked) ? checked : checked.checked;
        const permissionIds: number[] = [];
        
        checkedKeys.forEach(key => {
            const keyStr = key.toString();
            if (keyStr.startsWith('permission-')) {
                const id = idMapping[keyStr];
                if (id) {
                    permissionIds.push(id);
                }
            }
        });
        
        console.log('选中的权限ID:', permissionIds);
        setCheckedKeys(permissionIds);
    };

    const handleExpand = (newExpandedKeys: Key[]) => {
        setExpandedKeys(newExpandedKeys);
    };

    const handleOk = () => {
        onOk(checkedKeys);
    };

    // 将权限ID转换为Tree需要的key
    const getTreeCheckedKeys = (): string[] => {
        console.log('当前选中的权限:', checkedKeys);
        return checkedKeys.map(id => `permission-${id}`);
    };

    return (
        <Modal
            title="分配权限"
            open={visible}
            onCancel={onCancel}
            onOk={handleOk}
            width={600}
            styles={{
                body: {
                    padding: '12px',
                    maxHeight: 'calc(100vh - 250px)',
                    overflow: 'auto'
                }
            }}
        >
            <Spin spinning={loading}>
                <Tree
                    checkable
                    checkedKeys={getTreeCheckedKeys()}
                    expandedKeys={expandedKeys}
                    onExpand={handleExpand}
                    onCheck={handleCheck}
                    treeData={treeData}
                    autoExpandParent={false}
                />
            </Spin>
        </Modal>
    );
};

export default PermissionModal; 