import React, { PureComponent } from 'react';
import { Card, Button, Alert, Dropdown, Row, Col, Tree, Statistic, Space } from 'antd';
import {
  ApartmentOutlined,
  TeamOutlined,
  ClockCircleOutlined,
  DownloadOutlined,
  DownOutlined,
  SyncOutlined,
  UserOutlined,
  DollarOutlined,
  SettingOutlined,
  BellOutlined,
  ExpandOutlined,
  FilterOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import styles from './ReportRelation.less';

class ReportRelation extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedYear: '2023',
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
            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 }
                            ],
                        },
                    ],
                },
            ],
    };
  }

  // 获取处理后的树形数据
  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' }} />;
  };

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

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

  // 刷新树数据
  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) });
    }
  };

  // 获取年份菜单
  getYearMenu = () => {
    const years = ['2021', '2022', '2023', '2024'];
    const menuItems = years.map(year => ({
      key: year,
      label: year,
    }));
    
    return {
      items: menuItems,
      onClick: ({ key }) => this.setState({ selectedYear: key })
    };
  };

  // ECharts配置选项
  getDepartmentChartOption = () => {
    return {
      title: {
        text: '各部门人员分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}: {c}人'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: {
          lineStyle: { color: '#f0f0f0' }
        }
      },
      yAxis: {
        type: 'category',
        data: ['人力资源部', '财务部', 'IT部', '市场部', '销售部', '客户服务部', '前端开发部', '后端开发部', '移动开发部'],
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '人数',
          type: 'bar',
          data: [45, 32, 28, 86, 124, 58, 76, 92, 64],
          itemStyle: {
            color: '#1890ff',
            borderRadius: [0, 4, 4, 0]
          },
          barWidth: 20,
          label: {
            show: true,
            position: 'right',
            formatter: '{c}人',
            fontSize: 11
          }
        }
      ]
    };
  };

  // 组织架构分布饼图配置
  getOrgPieChartOption = () => {
    return {
      title: {
        text: '部门人员占比',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}人 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 'middle',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '部门分布',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['65%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 356, name: '行政中心' },
            { value: 268, name: '营销中心' },
            { value: 232, name: '研发中心' },
            { value: 428, name: '其他部门' }
          ],
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          }
        }
      ]
    };
  };

  // 树节点展开/收起处理
  onExpand = (expandedKeys) => {
    this.setState({ expandedKeys });
  };

  render() {
    const { selectedYear, expandedKeys } = this.state;

    return (
      <div className={styles['organ-chart-page']} style={{ 
        height: '100vh', 
        overflowY: 'auto', 
        overflowX: 'hidden',
        padding: '16px'
      }}>
        {/* 公告栏 */}
        {/* <Alert
          message={
            <div className={styles['announcement-container']}>
              <div className={styles['announcement-badge']}>
                <BellOutlined />
                公告
              </div>
              <div className={styles['announcement-content']}>
                <div className={styles['marquee-text']}>
                  <span>2023年度绩效考核方案已发布，请各部门负责人及时查阅</span>
                  <span>系统将于2023年12月25日00:00-06:00进行升级维护</span>
                  <span>新员工入职培训计划已更新，请相关人员注意查收邮件</span>
                  <span>年度优秀员工评选活动正式启动，详情请见内网公告</span>
                </div>
              </div>
            </div>
          }
          type="info"
          closable
          className={styles['organ-chart-announcement']}
        /> */}

        <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.onExpand}
                  treeData={this.getTreeData()}
                  className={styles.orgTree}
                />
              </div>
            </Card>
          </Col>

          {/* 右侧内容区 */}
          <Col span={19}>
            <div style={{ height: 'calc(100vh - 152px)', overflowY: 'auto', paddingRight: '8px' }}>
              {/* 筛选区域 */}
              <Card className={styles['filter-section']} style={{ marginBottom: '16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <h2 className={styles['section-title']}>汇报关系</h2>
                <div className={styles['filter-actions']}>
                  <div className={styles['year-selector']}>
                    <span>年份:</span>
                    <Dropdown 
                      menu={this.getYearMenu()} 
                      trigger={['click']}
                    >
                      <Button type="default">
                        {selectedYear} <DownOutlined />
                      </Button>
                    </Dropdown>
                  </div>
                  <Button type="primary" icon={<FilterOutlined />}>
                    筛选
                  </Button>
                </div>
              </div>
            </Card>

            {/* 主要内容区 */}
            <Card className={styles['main-content']}>
                            {/* 汇报关系图 */}
              <div className={styles['report-relation-wrapper']}>
                <div className={styles['report-relation-container']}>
                  {/* 第一层：CEO */}
                  <div className={styles['hierarchy-level-1']}>
                    <div className={styles['person-card-large']}>
                      <div className={styles['person-avatar-large']}>
                        <UserOutlined />
                      </div>
                      <h4 className={styles['person-name']}>张明远</h4>
                      <p className={styles['person-title']}>CEO</p>
                      <p className={styles['person-company']}>集团公司</p>
                    </div>
                  </div>

                  {/* 连接线系统 - 第一层到第二层 */}
                  <div className={styles['connection-system-1']}>
                    <div className={styles['vertical-main-line']}></div>
                    <div className={styles['horizontal-main-line']}></div>
                    <div className={styles['branch-lines-container']}>
                      <div className={styles['branch-line-left']}></div>
                      <div className={styles['branch-line-right']}></div>
                    </div>
                  </div>

                  {/* 第二层：副总裁 */}
                  <div className={styles['hierarchy-level-2']}>
                    <div className={styles['person-row']}>
                      <div className={styles['person-card-medium']}>
                        <div className={styles['person-avatar-medium']}>
                          <UserOutlined />
                        </div>
                        <h4 className={styles['person-name']}>李华</h4>
                        <p className={styles['person-title']}>副总裁</p>
                        <p className={styles['person-company']}>华东事业部</p>
                      </div>
                      <div className={styles['person-card-medium']}>
                        <div className={styles['person-avatar-medium']}>
                          <UserOutlined />
                        </div>
                        <h4 className={styles['person-name']}>王伟</h4>
                        <p className={styles['person-title']}>副总裁</p>
                        <p className={styles['person-company']}>华南事业部</p>
                      </div>
                    </div>
                  </div>

                  {/* 连接线系统 - 第二层到第三层 */}
                  <div className={styles['connection-system-2']}>
                    <div className={styles['dual-vertical-lines']}>
                      <div className={styles['vertical-line']}></div>
                      <div className={styles['vertical-line']}></div>
                    </div>
                    <div className={styles['horizontal-connector-line']}></div>
                    <div className={styles['branch-lines-container-wide']}>
                      <div className={styles['branch-line-left']}></div>
                      <div className={styles['branch-line-right']}></div>
                    </div>
                  </div>

                  {/* 第三层：总监 */}
                  <div className={styles['hierarchy-level-3']}>
                    <div className={styles['person-row-wide']}>
                      <div className={styles['person-card-small']}>
                        <div className={styles['person-avatar-small']}>
                          <UserOutlined />
                        </div>
                        <h4 className={styles['person-name']}>陈思</h4>
                        <p className={styles['person-title']}>总监</p>
                        <p className={styles['person-company']}>上海分公司</p>
                      </div>
                      <div className={styles['person-card-small']}>
                        <div className={styles['person-avatar-small']}>
                          <UserOutlined />
                        </div>
                        <h4 className={styles['person-name']}>赵阳</h4>
                        <p className={styles['person-title']}>总监</p>
                        <p className={styles['person-company']}>杭州分公司</p>
                      </div>
                    </div>
                  </div>

                  {/* 连接线系统 - 第三层到第四层 */}
                  <div className={styles['connection-system-3']}>
                    <div className={styles['dual-vertical-lines-wide']}>
                      <div className={styles['vertical-line']}></div>
                      <div className={styles['vertical-line']}></div>
                    </div>
                    <div className={styles['horizontal-connector-line-wide']}></div>
                    <div className={styles['branch-lines-container-extra-wide']}>
                      <div className={styles['branch-line-left']}></div>
                      <div className={styles['branch-line-right']}></div>
                    </div>
                  </div>

                  {/* 第四层：经理 */}
                  <div className={styles['hierarchy-level-4']}>
                    <div className={styles['person-row-extra-wide']}>
                      <div className={styles['person-card-mini']}>
                        <div className={styles['person-avatar-mini']}>
                          <UserOutlined />
                        </div>
                        <h4 className={styles['person-name']}>周婷</h4>
                        <p className={styles['person-title']}>经理</p>
                        <p className={styles['person-company']}>研发中心</p>
                      </div>
                      <div className={styles['person-card-mini']}>
                        <div className={styles['person-avatar-mini']}>
                          <UserOutlined />
                        </div>
                        <h4 className={styles['person-name']}>黄晨</h4>
                        <p className={styles['person-title']}>经理</p>
                        <p className={styles['person-company']}>市场部</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            {/* 图表区域 */}
            {/* <Row gutter={16} className={styles['charts-row']}>
              <Col xs={24} lg={14}>
                <Card title="各部门人员分布" className={styles['chart-section']}>
                  <ReactECharts
                    option={this.getDepartmentChartOption()}
                    style={{ height: '300px' }}
                  />
                </Card>
              </Col>
              <Col xs={24} lg={10}>
                <Card title="部门人员占比" className={styles['chart-section']}>
                  <ReactECharts
                    option={this.getOrgPieChartOption()}
                    style={{ height: '300px' }}
                  />
                </Card>
              </Col>
            </Row> */}
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}

export default ReportRelation;