import React, { PureComponent } from 'react';
import {
  Card,
  Tree,
  Input,
  Button,
  DatePicker,
  Select,
  Row,
  Col,
  Space,
  Radio,
  Checkbox,
  InputNumber,
  Avatar,
  message,
  Timeline,
  Tag,
  Typography,
  Divider,
  Upload,
  Form,
  Table,
  Pagination
} from 'antd';
import {
  SaveOutlined,
  CloseOutlined,
  PlusCircleOutlined,
  DeleteOutlined,
  ExpandOutlined,
  UserOutlined,
  TeamOutlined,
  ApartmentOutlined,
  SyncOutlined,
  DollarOutlined,
  SettingOutlined,
  CalendarOutlined,
  UsergroupAddOutlined,
  UserSwitchOutlined,
  StopOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ContactsOutlined,
  PrinterOutlined,
  CheckOutlined,
  ClockCircleOutlined,
  LoadingOutlined,
  EyeOutlined,
  SearchOutlined,
  PictureOutlined,
  UploadOutlined,
  EditOutlined,
  ShareAltOutlined,
  FilterOutlined,
  DownloadOutlined,
  PlusOutlined,
  CaretDownOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import dayjs from 'dayjs';
import styles from './Performance.less';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;

class Performance extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedOrgKeys: ['0-0-4'], // 默认选中人事部
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
      // 绩效数据
      performanceData: {
        selectedPlan: '2023年Q3季度考核',
        currentPage: 1,
        pageSize: 10,
        total: 128,
        // 绩效评分分布数据
        scoreDistribution: [
          { name: '0-60分', value: 12, color: '#FF6B6B' },
          { name: '60-80分', value: 45, color: '#4ECDC4' },
          { name: '80-100分', value: 71, color: '#45B7D1' }
        ],
        // 部门绩效平均分数据
        departmentScores: {
          departments: ['技术研发', '市场营销', '产品运营', '人力资源', '财务中心', '客户服务'],
          scores: [89.5, 87.2, 85.8, 84.3, 83.7, 82.1]
        },
        // 人员绩效明细数据
        performanceList: [
          {
            key: '1',
            name: '张明远',
            department: '技术研发中心',
            totalScore: 96.5,
            codeLines: 12500,
            documentWords: 8500,
            projectAmount: '¥1,250,000',
            workHours: 186,
            values: 48.0
          },
          {
            key: '2',
            name: '李思颖',
            department: '市场营销中心',
            totalScore: 95.0,
            codeLines: 11800,
            documentWords: 9200,
            projectAmount: '¥1,100,000',
            workHours: 182,
            values: 47.0
          },
          {
            key: '3',
            name: '王浩然',
            department: '产品运营中心',
            totalScore: 93.5,
            codeLines: 11000,
            documentWords: 7800,
            projectAmount: '¥980,000',
            workHours: 180,
            values: 47.0
          },
          {
            key: '4',
            name: '陈雨桐',
            department: '人力资源中心',
            totalScore: 92.0,
            codeLines: 10500,
            documentWords: 9500,
            projectAmount: '¥920,000',
            workHours: 178,
            values: 46.5
          },
          {
            key: '5',
            name: '刘子轩',
            department: '技术研发中心',
            totalScore: 91.5,
            codeLines: 9800,
            documentWords: 7200,
            projectAmount: '¥890,000',
            workHours: 175,
            values: 46.0
          },
          {
            key: '6',
            name: '赵欣然',
            department: '客户服务中心',
            totalScore: 90.0,
            codeLines: 9200,
            documentWords: 8500,
            projectAmount: '¥850,000',
            workHours: 172,
            values: 45.5
          },
          {
            key: '7',
            name: '孙伟杰',
            department: '财务中心',
            totalScore: 89.5,
            codeLines: 8900,
            documentWords: 6800,
            projectAmount: '¥820,000',
            workHours: 170,
            values: 45.0
          },
          {
            key: '8',
            name: '周晓彤',
            department: '市场营销中心',
            totalScore: 88.0,
            codeLines: 8500,
            documentWords: 7900,
            projectAmount: '¥780,000',
            workHours: 168,
            values: 44.5
          },
          {
            key: '9',
            name: '吴宇航',
            department: '技术研发中心',
            totalScore: 87.5,
            codeLines: 8200,
            documentWords: 6500,
            projectAmount: '¥750,000',
            workHours: 165,
            values: 44.0
          },
          {
            key: '10',
            name: '郑雅文',
            department: '产品运营中心',
            totalScore: 86.0,
            codeLines: 8000,
            documentWords: 7800,
            projectAmount: '¥720,000',
            workHours: 162,
            values: 43.5
          }
        ]
      },
      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', fontSize: '14px' }} />;
    if (title.includes('技术') || title.includes('开发') || title.includes('测试')) return <SettingOutlined style={{ color: '#52c41a', fontSize: '14px' }} />;
    if (title.includes('产品') || title.includes('设计') || title.includes('体验')) return <TeamOutlined style={{ color: '#fa8c16', fontSize: '14px' }} />;
    if (title.includes('运营') || title.includes('市场') || title.includes('客户') || title.includes('商务')) return <TeamOutlined style={{ color: '#eb2f96', fontSize: '14px' }} />;
    if (title.includes('财务') || title.includes('会计') || title.includes('审计')) return <DollarOutlined style={{ color: '#722ed1', fontSize: '14px' }} />;
    if (title.includes('人事') || title.includes('HR') || title.includes('招聘') || title.includes('培训') || title.includes('薪酬')) return <UserOutlined style={{ color: '#13c2c2', fontSize: '14px' }} />;
    return <TeamOutlined style={{ color: '#666', fontSize: '14px' }} />;
  };

  // 刷新树数据
  handleTreeRefresh = () => {
    message.info('刷新组织架构数据');
  };

  // 展开/收缩所有节点
  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) });
    }
  };

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

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

  // 绩效计划切换
  handlePlanChange = (value) => {
    this.setState({
      performanceData: {
        ...this.state.performanceData,
        selectedPlan: value
      }
    });
    message.success(`切换到: ${value}`);
  };

  // 部门层级切换
  handleDepartmentLevelChange = (value) => {
    message.success(`切换到: ${value}`);
  };

  // 分页变化
  handlePageChange = (page, pageSize) => {
    this.setState({
      performanceData: {
        ...this.state.performanceData,
        currentPage: page,
        pageSize: pageSize
      }
    });
  };

  // 饼图配置
  getPieOption = () => {
    const { scoreDistribution } = this.state.performanceData;
    return {
      animation: false,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: scoreDistribution.map(item => item.name)
      },
      series: [
        {
          name: '绩效评分分布',
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 4,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: scoreDistribution.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: item.color
            }
          }))
        }
      ]
    };
  };

  // 柱状图配置
  getBarOption = () => {
    const { departmentScores } = this.state.performanceData;
    const colorList = ['#45B7D1', '#4ECDC4', '#A5DEE4', '#7AC5CD', '#66C6C4', '#85C1E9'];
    
    return {
      animation: false,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
      },
      yAxis: {
        type: 'category',
        data: departmentScores.departments
      },
      series: [
        {
          name: '平均分',
          type: 'bar',
          data: departmentScores.scores.map((score, index) => ({
            value: score,
            itemStyle: {
              color: colorList[index],
              borderRadius: [0, 4, 4, 0]
            }
          }))
        }
      ]
    };
  };

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

    // 表格列配置
    const columns = [
      {
        title: (
          <div className={styles.tableHeader}>
            <span>姓名</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'name',
        key: 'name',
        sorter: true,
        render: (text) => <Text strong>{text}</Text>
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>部门</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'department',
        key: 'department',
        sorter: true
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>总分</span>
            <SortDescendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'totalScore',
        key: 'totalScore',
        sorter: true,
        render: (score) => <Text strong className={styles.scoreText}>{score}</Text>
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>代码行数</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'codeLines',
        key: 'codeLines',
        sorter: true,
        render: (value) => value.toLocaleString()
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>文档字数</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'documentWords',
        key: 'documentWords',
        sorter: true,
        render: (value) => value.toLocaleString()
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>项目金额数</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'projectAmount',
        key: 'projectAmount',
        sorter: true
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>出勤时长</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'workHours',
        key: 'workHours',
        sorter: true
      },
      {
        title: (
          <div className={styles.tableHeader}>
            <span>价值观</span>
            <SortAscendingOutlined className={styles.sortIcon} />
          </div>
        ),
        dataIndex: 'values',
        key: 'values',
        sorter: true
      }
    ];

    return (
      <div className={styles.container}>
        <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
                      selectedKeys={selectedOrgKeys}
                      expandedKeys={expandedKeys}
                      treeData={this.getTreeData()}
                      onSelect={this.onTreeSelect}
                      onExpand={this.onTreeExpand}
                      className={styles.orgTree}
                    />
                  </div>
                </Card>
              </Col>

              {/* 右侧绩效仪表盘 */}
              <Col span={19}>
                <Card className={styles.mainCard}>
                  {/* 滚动内容区 */}
                  <div className={styles.content}>
                    {/* 头部标题和选择器 */}
                    <div className={styles.dashboardHeader}>
                      <Title level={3} className={styles.dashboardTitle}>绩效仪表盘</Title>
                      <div className={styles.planSelector}>
                        <Text className={styles.selectorLabel}>绩效计划：</Text>
                        <Select
                          value={performanceData.selectedPlan}
                          onChange={this.handlePlanChange}
                          className={styles.planSelect}
                          suffixIcon={<CaretDownOutlined />}
                        >
                          <Option value="2023年Q3季度考核">2023年Q3季度考核</Option>
                          <Option value="2023年Q2季度考核">2023年Q2季度考核</Option>
                          <Option value="2023年Q1季度考核">2023年Q1季度考核</Option>
                          <Option value="2022年年度考核">2022年年度考核</Option>
                        </Select>
                      </div>
                    </div>

                    {/* 图表区域 */}
                    <Row gutter={16} className={styles.chartsRow}>
                      <Col span={12}>
                        <Card className={styles.chartCard}>
                          <Title level={4} className={styles.chartTitle}>绩效评分分布</Title>
                          <div className={styles.chartContainer}>
                            <ReactECharts
                              option={this.getPieOption()}
                              style={{ height: '300px', width: '100%' }}
                              opts={{ renderer: 'canvas' }}
                            />
                          </div>
                        </Card>
                      </Col>
                      <Col span={12}>
                        <Card className={styles.chartCard}>
                          <div className={styles.chartHeader}>
                            <Title level={4} className={styles.chartTitle}>部门绩效平均分</Title>
                            <Select
                              defaultValue="一级部门"
                              className={styles.departmentSelect}
                              onChange={this.handleDepartmentLevelChange}
                              suffixIcon={<CaretDownOutlined />}
                            >
                              <Option value="一级部门">一级部门</Option>
                              <Option value="二级部门">二级部门</Option>
                              <Option value="三级部门">三级部门</Option>
                            </Select>
                          </div>
                          <div className={styles.chartContainer}>
                            <ReactECharts
                              option={this.getBarOption()}
                              style={{ height: '300px', width: '100%' }}
                              opts={{ renderer: 'canvas' }}
                            />
                          </div>
                        </Card>
                      </Col>
                    </Row>

                    {/* 人员绩效明细表 */}
                    <Card className={styles.tableCard}>
                      <Title level={4} className={styles.tableTitle}>人员绩效明细</Title>
                      <div className={styles.tableWrapper}>
                        <Table
                          columns={columns}
                          dataSource={performanceData.performanceList}
                          pagination={false}
                          className={styles.performanceTable}
                          scroll={{ y: 400 }}
                          onRow={(record) => ({
                            className: styles.tableRowHover
                          })}
                        />
                        
                        {/* 分页 */}
                        <div className={styles.paginationContainer}>
                          <div className={styles.paginationInfo}>
                            显示 {((performanceData.currentPage - 1) * performanceData.pageSize) + 1} 到{' '}
                            {Math.min(performanceData.currentPage * performanceData.pageSize, performanceData.total)} 条，
                            共 {performanceData.total} 条记录
                          </div>
                          <Pagination
                            current={performanceData.currentPage}
                            pageSize={performanceData.pageSize}
                            total={performanceData.total}
                            onChange={this.handlePageChange}
                            showSizeChanger={false}
                            className={styles.pagination}
                          />
                        </div>
                      </div>
                    </Card>
                  </div>
                </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }
}

export default Performance;