import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Space, InputNumber, Switch, TreeSelect, Select, message, Card } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';
import type { DepartmentResponse } from './types';
import { getDepartmentTree } from './service';
import type { UserResponse } from '@/pages/System/User/types';
import { getUsers } from './service';
import request from '@/utils/request';
import type { FixedType } from 'rc-table/lib/interface';

interface TreeSelectNode {
    title: string;
    value: number;
    disabled?: boolean;
    children?: TreeSelectNode[];
}

const DepartmentPage: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [departmentTree, setDepartmentTree] = useState<DepartmentResponse[]>([]);
    const [users, setUsers] = useState<UserResponse[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [editingDepartment, setEditingDepartment] = useState<DepartmentResponse | null>(null);
    const [form] = Form.useForm();

    // 处理树形数据，添加 hasChildren 属性
    const processTreeData = (departments: DepartmentResponse[]) => {
        return departments.map(dept => ({
            ...dept,
            hasChildren: Boolean(dept.children?.length),
            children: dept.children ? processTreeData(dept.children) : undefined
        }));
    };

    // 加载部门树数据
    const loadDepartmentTree = async () => {
        setLoading(true);
        try {
            const response = await getDepartmentTree();
            setDepartmentTree(processTreeData(response || []));
        } catch (error) {
            message.error('加载部门数据失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取扁平化的部门列表
    const getFlatDepartments = (departments: DepartmentResponse[]): DepartmentResponse[] => {
        return departments.reduce((acc, dept) => {
            acc.push(dept);
            if (dept.children?.length) {
                acc.push(...getFlatDepartments(dept.children));
            }
            return acc;
        }, [] as DepartmentResponse[]);
    };

    useEffect(() => {
        Promise.all([
            loadDepartmentTree(),
            getUsers().then(setUsers)
        ]);
    }, []);

    const handleAdd = () => {
        setEditingDepartment(null);
        form.resetFields();
        
        const allDepartments = getFlatDepartments(departmentTree);
        const maxSort = Math.max(0, ...allDepartments.map(dept => dept.sort));
        
        form.setFieldsValue({
            enabled: true,
            sort: maxSort + 1
        });
        setModalVisible(true);
    };

    const handleEdit = (record: DepartmentResponse) => {
        setEditingDepartment(record);
        form.setFieldsValue({
            ...record,
            parentId: record.parentId || undefined
        });
        setModalVisible(true);
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            const data = {
                ...values,
                parentId: values.parentId || 0
            };

            if (editingDepartment) {
                await request.put(`/api/v1/department/${editingDepartment.id}`, {
                    ...data,
                    version: editingDepartment.version
                });
                message.success('更新成功');
            } else {
                await request.post('/api/v1/department', data);
                message.success('创建成功');
            }
            setModalVisible(false);
            loadDepartmentTree();
        } catch (error) {
            console.error('操作失败:', error);
        }
    };

    const handleDelete = (id: number) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除该部门吗？',
            onOk: async () => {
                try {
                    await request.delete(`/api/v1/department/${id}`);
                    message.success('删除成功');
                    loadDepartmentTree();
                } catch (error) {
                    message.error('删除失败');
                }
            }
        });
    };

    const columns = [
        {
            title: '部门名称',
            dataIndex: 'name',
            key: 'name',
            width: 250,
            fixed: 'left' as FixedType
        },
        {
            title: '部门编码',
            dataIndex: 'code',
            key: 'code',
            width: 120
        },
        {
            title: '部门描述',
            dataIndex: 'description',
            key: 'description',
            width: 200,
            ellipsis: true
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort',
            width: 80
        },
        {
            title: '负责人',
            dataIndex: 'leaderName',
            key: 'leaderName',
            width: 100
        },
        {
            title: '状态',
            dataIndex: 'enabled',
            key: 'enabled',
            width: 80,
            render: (enabled: boolean) => (
                <Switch checked={enabled} disabled size="small"/>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 160,
            fixed: 'right' as FixedType,
            render: (_: any, record: DepartmentResponse) => (
                <Space size={0}>
                    <Button
                        type="link"
                        size="small"
                        icon={<EditOutlined/>}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        danger
                        icon={<DeleteOutlined/>}
                        onClick={() => handleDelete(record.id)}
                        disabled={Boolean(record.children?.length)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ];

    return (
        <Card>
            <div style={{ marginBottom: 16 }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    新增部门
                </Button>
            </div>

            <Table
                loading={loading}
                columns={columns}
                dataSource={departmentTree}
                rowKey="id"
                scroll={{ x: 1200 }}
                pagination={false}
                size="middle"
                bordered
                defaultExpandAllRows
                expandable={{
                    showIcon: true,
                    expandIcon: ({ expanded, onExpand, record }) => {
                        if (!record.hasChildren) {
                            return null;
                        }
                        return expanded ? (
                            <CaretDownOutlined onClick={e => onExpand(record, e)} />
                        ) : (
                            <CaretRightOutlined onClick={e => onExpand(record, e)} />
                        );
                    }
                }}
            />

            <Modal
                title={editingDepartment ? '编辑部门' : '新增部门'}
                open={modalVisible}
                onOk={handleSubmit}
                onCancel={() => setModalVisible(false)}
                width={600}
                destroyOnClose
            >
                <Form form={form} layout="vertical">
                    <Form.Item name="parentId" label="上级部门">
                        <TreeSelect
                            treeData={departmentTree.map(dept => ({
                                title: dept.name,
                                value: dept.id,
                                disabled: editingDepartment?.id === dept.id,
                                children: dept.children?.map(child => ({
                                    title: child.name,
                                    value: child.id,
                                    disabled: editingDepartment?.id === child.id
                                }))
                            }))}
                            placeholder="不选择则为顶级部门"
                            allowClear
                            treeDefaultExpandAll
                            disabled={Boolean(editingDepartment?.children?.length)}
                        />
                    </Form.Item>
                    
                    <Form.Item
                        name="code"
                        label="部门编码"
                        rules={[
                            {required: true, message: '请输入部门编码'},
                            {pattern: /^[A-Z_]+$/, message: '部门编码只能包含大写字母和下划线'}
                        ]}
                    >
                        <Input placeholder="请输入部门编码"/>
                    </Form.Item>

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

                    <Form.Item
                        name="description"
                        label="部门描述"
                    >
                        <Input.TextArea placeholder="请输入部门描述"/>
                    </Form.Item>

                    <Form.Item
                        name="sort"
                        label="显示排序"
                        rules={[{required: true, message: '请输入显示排序'}]}
                    >
                        <InputNumber
                            style={{width: '100%'}}
                            min={0}
                            placeholder="请输入显示排序"
                        />
                    </Form.Item>

                    <Form.Item
                        name="leaderId"
                        label="负责人"
                    >
                        <Select
                            placeholder="请选择负责人"
                            allowClear
                            showSearch
                            optionFilterProp="children"
                            onChange={(value, option: any) => {
                                form.setFieldsValue({
                                    leaderId: value,
                                    leaderName: option?.label
                                });
                            }}
                        >
                            {users.map(user => (
                                <Select.Option
                                    key={user.id}
                                    value={user.id}
                                    label={user.nickname || user.username}
                                >
                                    {user.nickname || user.username}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item name="leaderName" hidden>
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        name="enabled"
                        label="状态"
                        valuePropName="checked"
                    >
                        <Switch checkedChildren="启用" unCheckedChildren="禁用"/>
                    </Form.Item>
                </Form>
            </Modal>
        </Card>
    );
};

export default DepartmentPage; 