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 
} from '@ant-design/icons';
import styles from './StaffInfo.less';
import StandardTable from '@/components/StandardTable';
import StaffInfoAdd from './form/StaffInfoAdd';
import StaffInfoRenderSimpleForm from "./form/StaffInfoRenderSimpleForm" //表单

const { Option } = Select;

class StaffInfo 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,
                    name: '张三',
                    phone: 28,  // 年龄
                    idCard: '技术部',  // 部门
                    department: '高级工程师',  // 岗位
                    position: '全职',  // 工作性质
                    status: '138****1234',  // 电话
                    entryDate: '2020-03-15'
                },
                {
                    key: '2',
                    id: 2,
                    name: '李四',
                    phone: 30,  // 年龄
                    idCard: '产品部',  // 部门
                    department: '产品经理',  // 岗位
                    position: '全职',  // 工作性质
                    status: '139****5678',  // 电话
                    entryDate: '2019-08-20'
                },
                {
                    key: '3',
                    id: 3,
                    name: '王五',
                    phone: 25,  // 年龄
                    idCard: '运营部',  // 部门
                    department: '运营专员',  // 岗位
                    position: '全职',  // 工作性质
                    status: '136****9999',  // 电话
                    entryDate: '2021-05-10'
                },
                {
                    key: '4',
                    id: 4,
                    name: '赵六',
                    phone: 32,  // 年龄
                    idCard: '财务部',  // 部门
                    department: '会计',  // 岗位
                    position: '全职',  // 工作性质
                    status: '137****8888',  // 电话
                    entryDate: '2018-12-01'
                },
                {
                    key: '5',
                    id: 5,
                    name: '陈七',
                    phone: 26,  // 年龄
                    idCard: '人事部',  // 部门
                    department: 'HR专员',  // 岗位
                    position: '全职',  // 工作性质
                    status: '135****7777',  // 电话
                    entryDate: '2022-01-15'
                },
            ],
            pagination: {
                current: 1,
                pageSize: 5,
                total: 356,
            }
        };
        
        // 默认列配置
        this.defaultColumns = [
            {
                title: '序号',
                dataIndex: 'id',
                key: 'id',
                width: 60,
                align: 'center',
            },
            {
                title: '姓名',
                dataIndex: 'name',
                key: 'name',
                width: 60,
                render: (text, record) => (
                    <Button
                        type="link"
                        style={{ padding: 0, fontWeight: 500 }}
                        onClick={() => this.handleNameClick(record)}
                    >
                        {text}
                    </Button>
                ),
            },
            {
                title: '年龄',
                dataIndex: 'phone',
                key: 'phone',
                width: 50,
            },
            {
                title: '部门',
                dataIndex: 'idCard',
                key: 'idCard',
                width: 70,
            },
            {
                title: '岗位',
                dataIndex: 'department',
                key: 'department',
                width: 80,
            },
            {
                title: '工作性质',
                dataIndex: 'position',
                key: 'position',
                width: 50,
            },
            {
                title: '电话',
                dataIndex: 'status',
                key: 'status',
                width: 100,
            },
            {
                title: '操作',
                key: 'action',
                width: 80,
                align: 'center',
                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 (
            <StaffInfoRenderSimpleForm {...parentMethods} />
        );
    }

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

        return (
            <StaffInfoRenderSimpleForm  {...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={<UserAddOutlined />}
                                            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>

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

export default StaffInfo;