import React, { useEffect, useState } from 'react';
import { Card, Button, Table, Space, Modal, Form, Input, InputNumber, message, Tag, Dropdown, MenuProps } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined, TagsOutlined, MoreOutlined, SettingOutlined } from '@ant-design/icons';
import type { RoleResponse, RoleTagResponse, RoleQuery } from './types';
import { getRoleList, createRole, updateRole, deleteRole, getRolePermissions, assignPermissions } from './service';
import type { TablePaginationConfig } from 'antd/es/table';
import type {FilterValue, SorterResult} from 'antd/es/table/interface';
import PermissionModal from './components/PermissionModal';
import TagModal from './components/TagModal';
import AssignTagModal from './components/AssignTagModal';

const RolePage: React.FC = () => {
    const [form] = Form.useForm();
    const [visible, setVisible] = useState(false);
    const [editingId, setEditingId] = useState<number | null>(null);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [permissionModalVisible, setPermissionModalVisible] = useState(false);
    const [tagModalVisible, setTagModalVisible] = useState(false);
    const [assignTagModalVisible, setAssignTagModalVisible] = useState(false);
    const [selectedRole, setSelectedRole] = useState<RoleResponse>();
    const [loading, setLoading] = useState(false);
    const [roles, setRoles] = useState<RoleResponse[]>([]);
    const [defaultCheckedKeys, setDefaultCheckedKeys] = useState<number[]>([]);
    const [pagination, setPagination] = useState<TablePaginationConfig>({
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true
    });
    const [sortField, setSortField] = useState<string>('sort');
    const [sortOrder, setSortOrder] = useState<'ascend' | 'descend'>('ascend');

    const fetchRoles = async (params: RoleQuery = {}) => {
        try {
            setLoading(true);
            const { pageNum = 1, pageSize = 10 } = pagination;
            const result = await getRoleList({
                pageNum,
                pageSize,
                sortField,
                sortOrder: sortOrder === 'ascend' ? 'asc' : sortOrder === 'descend' ? 'desc' : undefined,
                ...params
            });
            setRoles(result.content);
            setPagination({
                ...pagination,
                current: result.number + 1,
                pageSize: result.size,
                total: result.totalElements
            });
        } catch (error) {
            message.error('获取角色列表失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchRoles();
    }, []);

    const handleAdd = () => {
        setEditingId(null);
        form.resetFields();
        form.setFieldsValue({
            enabled: true,
            sort: 0
        });
        setVisible(true);
    };

    const handleEdit = (record: RoleResponse) => {
        setEditingId(record.id);
        form.setFieldsValue(record);
        setVisible(true);
    };

    const handleDelete = async (id: number) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个角色吗？',
            onOk: async () => {
                try {
                    await deleteRole(id);
                    message.success('删除成功');
                    fetchRoles();
                } catch (error) {
                    message.error('删除失败');
                }
            }
        });
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            setConfirmLoading(true);

            if (editingId) {
                await updateRole(editingId, values);
                message.success('更新成功');
            } else {
                await createRole(values);
                message.success('创建成功');
            }

            setVisible(false);
            fetchRoles();
        } catch (error) {
            message.error('操作失败');
        } finally {
            setConfirmLoading(false);
        }
    };

    // 处理表格变化
    const handleTableChange = (
        newPagination: TablePaginationConfig,
        filters: Record<string, FilterValue | null>,
        sorter: SorterResult<RoleResponse> | SorterResult<RoleResponse>[]
    ) => {
        const { field, order } = Array.isArray(sorter) ? sorter[0] : sorter;
        setSortField(field as string);
        setSortOrder(order as 'ascend' | 'descend');
        
        const params = {
            current: newPagination.current,
            pageSize: newPagination.pageSize,
            sortField: field as string,
            sortOrder: order === 'ascend' ? 'asc' : order === 'descend' ? 'desc' : undefined
        };
        
        fetchRoles({
            pageNum: params.current,
            pageSize: params.pageSize,
            sortField: params.sortField,
            sortOrder: params.sortOrder
        });
    };

    // 处理分配权限
    const handleAssignPermissions = async (record: RoleResponse) => {
        try {
            const permissions = await getRolePermissions(record.id);
            setSelectedRole(record);
            setPermissionModalVisible(true);
            setDefaultCheckedKeys(Array.isArray(permissions) ? 
                (typeof permissions[0] === 'number' ? permissions : permissions.map(p => p.id)) : 
                []);
        } catch (error) {
            message.error('获取角色权限失败');
        }
    };

    // 处理权限分配确认
    const handlePermissionAssign = async (permissionIds: number[]) => {
        if (!selectedRole) return;
        try {
            await assignPermissions(selectedRole.id, permissionIds);
            message.success('权限分配成功');
            setPermissionModalVisible(false);
            fetchRoles();
        } catch (error) {
            message.error('权限分配失败');
        }
    };

    const handleAssignTags = (record: RoleResponse) => {
        setSelectedRole(record);
        setAssignTagModalVisible(true);
    };

    const columns = [
        {
            title: '角色编码',
            dataIndex: 'code',
            width: 150,
            sorter: true
        },
        {
            title: '角色名称',
            dataIndex: 'name',
            width: 150
        },
        {
            title: '标签',
            dataIndex: 'tags',
            width: 200,
            render: (tags: RoleTagResponse[]) => (
                <Space size={[0, 4]} wrap>
                    {tags?.map(tag => (
                        <Tag key={tag.id} color={tag.color}>
                            {tag.name}
                        </Tag>
                    ))}
                </Space>
            )
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 80,
            sorter: true
        },
        {
            title: '描述',
            dataIndex: 'description',
            ellipsis: true,
            width: 200
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: 180,
            sorter: true
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right' as const,
            width: 120,
            render: (_: any, record: RoleResponse) => {
                const items: MenuProps['items'] = [
                    {
                        key: 'permissions',
                        icon: <KeyOutlined />,
                        label: '分配权限',
                        onClick: () => handleAssignPermissions(record)
                    },
                    {
                        key: 'tags',
                        icon: <TagsOutlined />,
                        label: '分配标签',
                        onClick: () => handleAssignTags(record)
                    }
                ];

                // 如果不是admin角色，添加删除选项
                if (record.code !== 'admin') {
                    items.push({
                        key: 'delete',
                        icon: <DeleteOutlined />,
                        label: '删除',
                        danger: true,
                        onClick: () => handleDelete(record.id)
                    });
                }

                return (
                    <Space>
                        <Button
                            type="link"
                            icon={<EditOutlined />}
                            onClick={() => handleEdit(record)}
                        >
                            编辑
                        </Button>
                        <Dropdown
                            menu={{ items }}
                            placement="bottomRight"
                            trigger={['click']}
                        >
                            <Button
                                type="text"
                                icon={<MoreOutlined />}
                                style={{ padding: '4px 8px' }}
                            />
                        </Dropdown>
                    </Space>
                );
            }
        }
    ];

    return (
        <Card>
            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    新建角色
                </Button>
                <Button icon={<SettingOutlined />} onClick={() => setTagModalVisible(true)}>
                    标签管理
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={roles}
                rowKey="id"
                loading={loading}
                pagination={pagination}
                onChange={handleTableChange}
                scroll={{ x: 1300 }}
            />

            <Modal
                title={editingId ? '编辑角色' : '新建角色'}
                open={visible}
                onOk={handleSubmit}
                onCancel={() => setVisible(false)}
                confirmLoading={confirmLoading}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="code"
                        label="角色编码"
                        rules={[{ required: true, message: '请输入角色编码' }]}
                    >
                        <Input placeholder="请输入角色编码" disabled={!!editingId} />
                    </Form.Item>

                    <Form.Item
                        name="name"
                        label="角色名称"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                    >
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>

                    <Form.Item
                        name="sort"
                        label="排序"
                        initialValue={0}
                    >
                        <InputNumber min={0} />
                    </Form.Item>

                    <Form.Item
                        name="description"
                        label="描述"
                    >
                        <Input.TextArea rows={4} placeholder="请输入描述" />
                    </Form.Item>
                </Form>
            </Modal>

            {selectedRole && (
                <>
                    <PermissionModal
                        visible={permissionModalVisible}
                        roleId={selectedRole.id}
                        onCancel={() => setPermissionModalVisible(false)}
                        onOk={handlePermissionAssign}
                        defaultCheckedKeys={defaultCheckedKeys}
                    />
                    <AssignTagModal
                        visible={assignTagModalVisible}
                        roleId={selectedRole.id}
                        onCancel={() => setAssignTagModalVisible(false)}
                        onSuccess={() => {
                            setAssignTagModalVisible(false);
                            fetchRoles();
                        }}
                        selectedTags={selectedRole.tags}
                    />
                </>
            )}

            <TagModal
                visible={tagModalVisible}
                onCancel={() => setTagModalVisible(false)}
                onSuccess={() => {
                    setTagModalVisible(false);
                    fetchRoles();
                }}
            />
        </Card>
    );
};

export default RolePage; 