import React, { PureComponent } from 'react';
import {
    Card,
    Tree,
    Button,
    Select,
    Space,
    Row,
    Col,
    Pagination,
    Modal,
    message
} 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 './WorkReport.less';
import StandardTable from '@/components/StandardTable';
import WorkReportAdd from './form/WorkReportAdd';
import WorkReportRenderSimpleForm from "./form/WorkReportRenderSimpleForm" //表单

const { Option } = Select;

class WorkReport 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,
                    workType: '招聘面试',
                    workPerson: '张三',
                    department: '人事部',
                    startTime: '2025-09-03 09:00',
                    endTime: '2025-09-03 17:30',
                    duration: '8.5小时',
                    workQuantity: 3
                },
                {
                    key: '2',
                    id: 2,
                    workType: '培训组织',
                    workPerson: '李四',
                    department: '人事部',
                    startTime: '2025-09-03 08:30',
                    endTime: '2025-09-03 18:00',
                    duration: '9.5小时',
                    workQuantity: 2
                },
                {
                    key: '3',
                    id: 3,
                    workType: '绩效考核',
                    workPerson: '王五',
                    department: '人事部',
                    startTime: '2025-09-03 09:15',
                    endTime: '2025-09-03 17:45',
                    duration: '8.5小时',
                    workQuantity: 5
                },
                {
                    key: '4',
                    id: 4,
                    workType: '薪酬核算',
                    workPerson: '赵六',
                    department: '人事部',
                    startTime: '2025-09-03 08:45',
                    endTime: '2025-09-03 17:15',
                    duration: '8.5小时',
                    workQuantity: 4
                },
                {
                    key: '5',
                    id: 5,
                    workType: '招聘面试',
                    workPerson: '陈七',
                    department: '人事部',
                    startTime: '2025-09-03 09:30',
                    endTime: '2025-09-03 16:30',
                    duration: '7小时',
                    workQuantity: 1
                },
            ],
            pagination: {
                current: 1,
                pageSize: 5,
                total: 356,
            },
            selectedRecord: null,  // 选中的记录，用于编辑
        };
        
        // 默认列配置
        this.defaultColumns = [
            {
                title: '序号',
                dataIndex: 'id',
                key: 'id',
                width: 80,
                align: 'center',
                render: (text, record, index) => (
                    <span style={{ fontWeight: '500' }}>
                        {index + 1}
                    </span>
                ),
            },
            {
                title: '作业类型',
                dataIndex: 'workType',
                key: 'workType',
                width: 120,
                align: 'center',
                render: (text) => (
                    <span style={{ 
                        backgroundColor: '#f0f9ff',
                        border: '1px solid #91d5ff',
                        borderRadius: '6px',
                        padding: '2px 8px',
                        color: '#1890ff',
                        fontSize: '12px',
                        fontWeight: '500'
                    }}>
                        {text}
                    </span>
                ),
            },
            {
                title: '作业人员',
                dataIndex: 'workPerson',
                key: 'workPerson',
                width: 100,
                align: 'center',
                render: (text, record) => (
                    <Button
                        type="link"
                        style={{ padding: 0, fontWeight: 500, color: '#1890ff' }}
                        onClick={() => this.handlePersonClick(record)}
                    >
                        {text}
                    </Button>
                ),
            },
            {
                title: '部门',
                dataIndex: 'department',
                key: 'department',
                width: 120,
                align: 'center',
            },
            {
                title: '开始时间',
                dataIndex: 'startTime',
                key: 'startTime',
                width: 150,
                align: 'center',
                render: (time) => (
                    <span style={{ color: '#52c41a', fontWeight: '500' }}>
                        {time}
                    </span>
                ),
            },
            {
                title: '结束时间',
                dataIndex: 'endTime',
                key: 'endTime',
                width: 150,
                align: 'center',
                render: (time) => (
                    <span style={{ color: '#ff4d4f', fontWeight: '500' }}>
                        {time}
                    </span>
                ),
            },
            {
                title: '持续时长',
                dataIndex: 'duration',
                key: 'duration',
                width: 100,
                align: 'center',
                render: (duration) => (
                    <span style={{ 
                        backgroundColor: '#f6ffed',
                        border: '1px solid #b7eb8f',
                        borderRadius: '6px',
                        padding: '2px 8px',
                        color: '#52c41a',
                        fontWeight: 'bold'
                    }}>
                        {duration}
                    </span>
                ),
                sorter: (a, b) => {
                    const aHours = parseFloat(a.duration);
                    const bHours = parseFloat(b.duration);
                    return aHours - bHours;
                },
            },
            {
                title: '作业数量',
                dataIndex: 'workQuantity',
                key: 'workQuantity',
                width: 100,
                align: 'center',
                render: (quantity) => (
                    <span style={{ 
                        fontWeight: 'bold',
                        color: quantity >= 4 ? '#52c41a' : 
                               quantity >= 2 ? '#1890ff' : '#faad14'
                    }}>
                        {quantity}
                    </span>
                ),
                sorter: (a, b) => a.workQuantity - b.workQuantity,
            },
            {
                title: '操作',
                key: 'action',
                width: 120,
                align: 'center',
                render: (_, record) => (
                    <Space size="middle">
                        <Button
                            type="link"
                            size="small"
                            icon={<EditOutlined />}
                            title="编辑工作报告"
                            onClick={() => this.handleEdit(record)}
                        >
                            编辑
                        </Button>
                        <Button
                            type="link"
                            size="small"
                            danger
                            icon={<DeleteOutlined />}
                            title="删除记录"
                            onClick={() => this.handleDelete(record)}
                        >
                            删除
                        </Button>
                    </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 (
            <WorkReportRenderSimpleForm {...parentMethods} />
        );
    }

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

        return (
            <WorkReportRenderSimpleForm  {...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,
            selectedRecord: null  // 清空选中记录
        });
    };

    // 新增成功回调
    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
            }
        });
    };

    // 处理作业人员点击事件
    handlePersonClick = (record) => {
        Modal.info({
            title: `${record.workPerson} - 作业详情`,
            width: 600,
            content: (
                <div style={{ marginTop: 16 }}>
                    <Row gutter={[16, 16]}>
                        <Col span={12}><strong>作业人员：</strong>{record.workPerson}</Col>
                        <Col span={12}><strong>所属部门：</strong>{record.department}</Col>
                        <Col span={12}><strong>作业类型：</strong>{record.workType}</Col>
                        <Col span={12}><strong>作业数量：</strong><span style={{ color: '#1890ff', fontWeight: 'bold' }}>{record.workQuantity}</span></Col>
                        <Col span={24} style={{ borderTop: '1px solid #f0f0f0', paddingTop: 16, marginTop: 16 }}>
                            <h4>时间统计</h4>
                        </Col>
                        <Col span={12}><strong>开始时间：</strong><span style={{ color: '#52c41a' }}>{record.startTime}</span></Col>
                        <Col span={12}><strong>结束时间：</strong><span style={{ color: '#ff4d4f' }}>{record.endTime}</span></Col>
                        <Col span={12}><strong>持续时长：</strong><span style={{ 
                            backgroundColor: '#f6ffed',
                            border: '1px solid #b7eb8f',
                            borderRadius: '4px',
                            padding: '2px 6px',
                            color: '#52c41a',
                            fontWeight: 'bold'
                        }}>{record.duration}</span></Col>
                        <Col span={12}><strong>工作效率：</strong><span style={{ color: '#faad14', fontWeight: 'bold' }}>
                            {(record.workQuantity / parseFloat(record.duration)).toFixed(2)} 件/小时
                        </span></Col>
                    </Row>
                </div>
            ),
            okText: '确定'
        });
    };

    // 处理编辑
    handleEdit = (record) => {
        console.log('编辑工作报告:', record);
        this.setState({
            selectedRecord: record,
            addModalVisible: true
        });
    };

    // 处理删除
    handleDelete = (record) => {
        Modal.confirm({
            title: '删除确认',
            content: `确定要删除 "${record.workPerson}" 的工作报告记录吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                // 实际项目中这里应该调用删除接口
                console.log('删除工作报告记录:', record.id);
                
                const newData = this.state.tableData.filter(item => item.id !== record.id);
                this.setState({ 
                    tableData: newData,
                    pagination: {
                        ...this.state.pagination,
                        total: newData.length
                    }
                });
                message.success('工作报告删除成功');
            }
        });
    };

    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>

                {/* 新增/编辑绩效弹窗 */}
                <WorkReportAdd
                    visible={addModalVisible}
                    loading={addLoading}
                    editData={this.state.selectedRecord}
                    onCancel={this.hideAddModal}
                    onSuccess={this.handleAddSuccess}
                />
            </div>
        );
    }
}

export default WorkReport;