import React, { PureComponent } from 'react';
import {
    Card,
    Tree,
    Button,
    Select,
    Space,
    Row,
    Col,
    Pagination
} from 'antd';
import { history } from 'umi';
import {
    ExpandOutlined,
    UserOutlined,
    TeamOutlined,
    ApartmentOutlined,
    SyncOutlined,
    DollarOutlined,
    SettingOutlined,
    DownloadOutlined, 
    UserAddOutlined,
    EditOutlined,
    DeleteOutlined,
    PlusOutlined
} from '@ant-design/icons';
import styles from './DeptMaintain.less';
import StandardTable from '@/components/StandardTable';
import DeptMaintainAdd from './form/DeptMaintainAdd';
import DeptMaintainRenderSimpleForm from "./form/DeptMaintainRenderSimpleForm" //表单

const { Option } = Select;

class DeptMaintain extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            searchForm: {},
            selectedKeys: [],
            expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
            addModalVisible: false,  // 新增弹窗显示状态
            addLoading: false,       // 新增loading状态
            organizationData: [
                {
                    title: '飞利信科技有限公司',
                    key: '0-0',
                    count: 356,
                    children: [
                        {
                            title: '技术部',
                            key: '0-0-0',
                            count: 120,
                            children: [
                                { title: '前端组', key: '0-0-0-0', count: 45 },
                                { title: '后端组', key: '0-0-0-1', count: 52 },
                                { title: '测试组', key: '0-0-0-2', count: 23 }
                            ],
                        },
                        {
                            title: '产品部',
                            key: '0-0-1',
                            count: 68,
                            children: [
                                { title: '产品设计组', key: '0-0-1-0', count: 28 },
                                { title: '用户体验组', key: '0-0-1-1', count: 25 },
                                { title: '产品运营组', key: '0-0-1-2', count: 15 }
                            ],
                        },
                        {
                            title: '运营部',
                            key: '0-0-2',
                            count: 52,
                            children: [
                                { title: '市场营销组', key: '0-0-2-0', count: 22 },
                                { title: '客户服务组', key: '0-0-2-1', count: 18 },
                                { title: '商务合作组', key: '0-0-2-2', count: 12 }
                            ],
                        },
                        {
                            title: '财务部',
                            key: '0-0-3',
                            count: 32,
                            children: [
                                { title: '会计组', key: '0-0-3-0', count: 18 },
                                { title: '审计组', key: '0-0-3-1', count: 14 }
                            ],
                        },
                        {
                            title: '人事部',
                            key: '0-0-4',
                            count: 84,
                            children: [
                                { title: 'HR专员组', key: '0-0-4-0', count: 25 },
                                { title: '招聘组', key: '0-0-4-1', count: 22 },
                                { title: '培训组', key: '0-0-4-2', count: 18 },
                                { title: '薪酬组', key: '0-0-4-3', count: 19 }
                            ],
                        },
                    ],
                },
            ],
            tableData: [
                {
                    key: '1',
                    id: 1,
                    department: '技术部',
                    departmentHead: '张文军',
                    employeeCount: 120,
                    description: '负责公司所有技术研发工作',
                    createDate: '2020-01-15'
                },
                {
                    key: '2',
                    id: 2,
                    department: '产品部',
                    departmentHead: '李莉',
                    employeeCount: 68,
                    description: '负责产品规划、设计和运营',
                    createDate: '2020-02-10'
                },
                {
                    key: '3',
                    id: 3,
                    department: '运营部',
                    departmentHead: '王强',
                    employeeCount: 52,
                    description: '负责市场推广和客户服务',
                    createDate: '2020-03-05'
                },
                {
                    key: '4',
                    id: 4,
                    department: '财务部',
                    departmentHead: '赵敏',
                    employeeCount: 32,
                    description: '负责财务管理和会计核算',
                    createDate: '2020-01-20'
                },
                {
                    key: '5',
                    id: 5,
                    department: '人事部',
                    departmentHead: '陈晓红',
                    employeeCount: 84,
                    description: '负责人力资源管理和员工关系',
                    createDate: '2020-02-25'
                },
            ],
            pagination: {
                current: 1,
                pageSize: 5,
                total: 356,
            }
        };
        
        // 默认列配置
        this.defaultColumns = [
            {
                title: '序号',
                dataIndex: 'id',
                key: 'id',
                width: 60,
                align: 'center',
            },
            {
                title: '部门名称',
                dataIndex: 'department',
                key: 'department',
                width: 50,
            },
            {
                title: '部门负责人',
                dataIndex: 'departmentHead',
                key: 'departmentHead',
                width: 70,
            },
            {
                title: '员工人数',
                dataIndex: 'employeeCount',
                key: 'employeeCount',
                width: 50,
            },
            {
                title: '操作',
                key: 'action',
                align: 'center',
                width: 80,
                render: (_, record) => (
                    <Space size="middle">
                        <Button
                            type="link"
                            size="small"
                            icon={<EditOutlined />}
                            title="编辑"
                            onClick={() => this.handleEdit(record)}
                        />
                        <Button
                            type="link"
                            size="small"
                            danger
                            icon={<DeleteOutlined />}
                            title="删除"
                            onClick={() => this.handleDelete(record)}
                        />
                    </Space>
                ),
            },
        ];
    }

    // 获取处理后的树形数据
    getTreeData = () => {
        const { organizationData } = this.state;

        const processNode = (node) => ({
            key: node.key,
            title: (
                <span className={styles['tree-node-title']}>
                    {this.getNodeIcon(node.title)}
                    <span className={styles['node-title']}>{node.title}</span>
                    <span className={styles['node-count']}>({node.count})</span>
                </span>
            ),
            children: node.children ? node.children.map(processNode) : undefined
        });

        return organizationData.map(processNode);
    };

    // 获取节点图标
    getNodeIcon = (title) => {
        if (title.includes('公司') || title.includes('集团')) return <ApartmentOutlined style={{ color: '#1890ff' }} />;
        if (title.includes('技术') || title.includes('开发') || title.includes('测试')) return <SettingOutlined style={{ color: '#52c41a' }} />;
        if (title.includes('产品') || title.includes('设计') || title.includes('体验')) return <TeamOutlined style={{ color: '#fa8c16' }} />;
        if (title.includes('运营') || title.includes('市场') || title.includes('客户') || title.includes('商务')) return <TeamOutlined style={{ color: '#eb2f96' }} />;
        if (title.includes('财务') || title.includes('会计') || title.includes('审计')) return <DollarOutlined style={{ color: '#722ed1' }} />;
        if (title.includes('人事') || title.includes('HR') || title.includes('招聘') || title.includes('培训') || title.includes('薪酬')) return <UserOutlined style={{ color: '#13c2c2' }} />;
        return <TeamOutlined style={{ color: '#666' }} />;
    };

    // 搜索处理
    handleSearch = (values) => {
        console.log('搜索参数:', values);
        this.setState({ searchForm: values });
    };

    // 重置搜索
    handleReset = () => {
        this.formRef?.resetFields();
        this.setState({ searchForm: {} });
    };

    // 树节点选择
    onTreeSelect = (selectedKeys, info) => {
        console.log('选中节点:', selectedKeys, info);
        this.setState({ selectedKeys });
    };

    // 树节点展开
    onTreeExpand = (expandedKeys) => {
        this.setState({ expandedKeys });
    };

    // 刷新树数据
    handleTreeRefresh = () => {
        // console.log('刷新组织架构');
        // 这里可以添加刷新树数据的逻辑
    };

    // 展开/收缩所有节点
    handleTreeToggle = () => {
        const { expandedKeys, organizationData } = this.state;
        if (expandedKeys.length > 0) {
            // 收缩所有节点
            this.setState({ expandedKeys: [] });
        } else {
            // 展开所有节点
            const getAllKeys = (nodes) => {
                let keys = [];
                nodes.forEach(node => {
                    keys.push(node.key);
                    if (node.children) {
                        keys = keys.concat(getAllKeys(node.children));
                    }
                });
                return keys;
            };
            this.setState({ expandedKeys: getAllKeys(organizationData) });
        }
    };

    renderSimpleForm() {
        const { prooperlog = {} } = this.props;
        const { params = {} } = prooperlog;
        const parentMethods = {
            handleSearch: this.handleSearch,
            handleFormReset: this.handleFormReset,
            toggleForm: this.toggleForm,
            submitButtons: styles.submitButtons,
            params
        };
        return (
            <DeptMaintainRenderSimpleForm {...parentMethods} />
        );
    }

    renderAdvancedForm() {
        const { prooperlog: { params } } = this.props;
        const parentMethods = {
            handleSearch: this.handleSearch,
            handleFormReset: this.handleFormReset,
            toggleForm: this.toggleForm,
            params
        };

        return (
            <DeptMaintainRenderSimpleForm  {...parentMethods} />
        );
    }

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    // 分页处理
    onPaginationChange = (page, pageSize) => {
        this.setState({
            pagination: {
                ...this.state.pagination,
                current: page,
                pageSize,
            }
        });
    };

    // 显示新增弹窗
    showAddModal = () => {
        this.setState({ addModalVisible: true });
    };

    // 关闭新增弹窗
    hideAddModal = () => {
        this.setState({ addModalVisible: false });
    };

    // 新增成功回调
    handleAddSuccess = (values) => {
        console.log('新增成功:', values);

        // 这里可以刷新列表数据
        // 模拟添加到表格数据中
        const newStaff = {
            key: String(Date.now()),
            id: this.state.tableData.length + 1,
            name: values.name,
            phone: values.age,  // 年龄
            idCard: values.department,  // 部门
            department: values.position,  // 岗位
            position: values.workType,  // 工作性质
            status: values.phone,  // 电话
            entryDate: new Date().toISOString().split('T')[0]
        };

        this.setState({
            tableData: [...this.state.tableData, newStaff],
            pagination: {
                ...this.state.pagination,
                total: this.state.pagination.total + 1
            }
        });
    };

    // 处理姓名点击事件
    handleNameClick = (record) => {
        console.log('点击员工:', record);
        // 跳转到人员详情页面，传递员工ID参数
        history.push(`/topnavbar00/staffmanage/particulars`);
    };

    // 处理编辑
    handleEdit = (record) => {
        console.log('编辑员工:', record);
        // 这里可以打开编辑弹窗或跳转到编辑页面
    };

    // 处理删除
    handleDelete = (record) => {
        console.log('删除员工:', record);
        // 这里可以弹出确认框并执行删除操作
    };

    render() {
        const { tableData, pagination, expandedKeys, addModalVisible, addLoading } = this.state;

        return (
            <div className={styles.staffInfoContainer}>
                {/* 主体内容 */}
                <div className={styles.mainContent}>
                    <Card className={styles.contentCard}>
                        <Row gutter={24}>
                            {/* 左侧组织架构树 */}
                            <Col span={5}>
                                <Card
                                    title={
                                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                                <TeamOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                                                <span>组织架构</span>
                                            </div>
                                            <Space>
                                                <Button
                                                    type="text"
                                                    icon={<SyncOutlined />}
                                                    size="small"
                                                    style={{ color: '#1890ff' }}
                                                    onClick={this.handleTreeRefresh}
                                                    title="刷新"
                                                />
                                                <Button
                                                    type="text"
                                                    icon={<ExpandOutlined />}
                                                    size="small"
                                                    style={{ color: '#1890ff' }}
                                                    onClick={this.handleTreeToggle}
                                                    title={expandedKeys.length > 0 ? "收缩全部" : "展开全部"}
                                                />
                                            </Space>
                                        </div>
                                    }
                                    className={styles.treeCard}
                                >
                                    <div className={styles.treeContainer}>
                                        <Tree
                                            showIcon
                                            expandedKeys={expandedKeys}
                                            onSelect={this.onTreeSelect}
                                            onExpand={this.onTreeExpand}
                                            treeData={this.getTreeData()}
                                            className={styles.orgTree}
                                        />
                                    </div>
                                </Card>
                            </Col>

                            {/* 右侧人员信息区 */}
                            <Col span={19}>
                                {/* 筛选条件 */}
                                <Card className={styles.searchCard}>
                                    {this.renderForm()}
                                </Card>

                                {/* 操作按钮和统计 */}
                                <div className={styles.actionBar}>
                                    <div className={styles.totalInfo}>
                                        {/* 共 {pagination.total} 条记录 */}
                                    </div>
                                    <Space size="middle">
                                        <Button
                                            icon={<DownloadOutlined />}
                                            size="middle"
                                            // className={styles.exportButton}
                                        >
                                            导出
                                        </Button>
                                        <Button
                                            type="primary"
                                            icon={<PlusOutlined />}
                                            size="middle"
                                            // className={styles.addButton}
                                            onClick={this.showAddModal}
                                        >
                                            新增
                                        </Button>
                                    </Space>
                                </div>

                                {/* 人员表格 */}
                                <Card className={styles.tableCard}>
                                    <StandardTable
                                        columns={this.defaultColumns}
                                        dataSource={tableData}
                                        pagination={false}
                                        // scroll={{ x: 1000,y: 600 }}
                                        size="small"
                                        selectedRows={[]}
                                    />

                                    {/* 分页 */}
                                    <div className={styles.paginationWrapper}>
                                        <Pagination
                                            current={pagination.current}
                                            total={pagination.total}
                                            pageSize={pagination.pageSize}
                                            showSizeChanger
                                            showQuickJumper
                                            showTotal={(total, range) =>
                                                `显示 ${range[0]} 到 ${range[1]} 条，共 ${total} 条记录`
                                            }
                                            onChange={this.onPaginationChange}
                                            onShowSizeChange={this.onPaginationChange}
                                        />
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </Card>
                </div>

                {/* 新增人员弹窗 */}
                <DeptMaintainAdd
                    visible={addModalVisible}
                    loading={addLoading}
                    onCancel={this.hideAddModal}
                    onSuccess={this.handleAddSuccess}
                />
            </div>
        );
    }
}

export default DeptMaintain;