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
} from '@ant-design/icons';
import dayjs from 'dayjs';
import styles from './TrainingPlan.less';

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

class TrainingPlan extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedOrgKeys: ['0-0-4'], // 默认选中人事部
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
      // 培训计划详情数据
      trainingPlanData: {
        id: 'TP2023Q3001',
        title: '2023年第三季度新员工培训计划',
        dateRange: '2023-07-01 至 2023-09-30',
        participants: 86,
        manager: '张明远',
        status: '进行中',
        completedCourses: 12,
        totalCourses: 24,
        participationRate: 87.5,
        description: '本培训计划针对2023年第三季度新入职员工设计，包含公司文化、产品知识、业务流程等全方位培训内容。通过系统化的培训帮助新员工快速融入团队，掌握工作所需的基本技能和知识，提升工作效率和团队协作能力。'
      },
      // 课程列表数据
      courseList: [
        {
          key: '1',
          courseName: '公司文化与价值观',
          instructor: '李华',
          courseTime: '2023-07-03 09:00-12:00',
          courseType: '现场',
          courseUrl: '进入课程',
          location: '总部大楼3层培训室A'
        },
        {
          key: '2',
          courseName: '产品知识入门',
          instructor: '王伟',
          courseTime: '2023-07-05 14:00-17:00',
          courseType: '在线',
          courseUrl: '进入课程',
          location: 'https://meeting.zoom.us/123456'
        },
        {
          key: '3',
          courseName: '业务流程概述',
          instructor: '张丽',
          courseTime: '2023-07-07 09:00-12:00',
          courseType: '现场',
          courseUrl: '进入课程',
          location: '总部大楼3层培训室B'
        },
        {
          key: '4',
          courseName: '团队协作与沟通',
          instructor: '陈明',
          courseTime: '2023-07-10 14:00-17:00',
          courseType: '在线',
          courseUrl: '进入课程',
          location: 'https://meeting.zoom.us/789012'
        },
        {
          key: '5',
          courseName: '办公软件高级应用',
          instructor: '刘芳',
          courseTime: '2023-07-12 09:00-12:00',
          courseType: '现场',
          courseUrl: '进入课程',
          location: '总部大楼3层培训室A'
        }
      ],
      pagination: {
        current: 1,
        pageSize: 5,
        total: 24
      },
      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 });
  };

  // 编辑培训计划
  handleEdit = () => {
    message.success('编辑培训计划');
  };

  // 分享培训计划
  handleShare = () => {
    message.success('分享培训计划');
  };

  // 筛选课程
  handleFilter = () => {
    message.info('筛选课程');
  };

  // 导出课程
  handleExport = () => {
    message.success('导出课程列表');
  };

  // 添加课程
  handleAddCourse = () => {
    message.success('添加新课程');
  };

  // 编辑课程
  handleEditCourse = (record) => {
    message.success(`编辑课程: ${record.courseName}`);
  };

  // 删除课程
  handleDeleteCourse = (record) => {
    message.success(`删除课程: ${record.courseName}`);
  };

  // 进入课程
  handleEnterCourse = (record) => {
    message.success(`进入课程: ${record.courseName}`);
  };

  // 分页变化
  handlePaginationChange = (page, pageSize) => {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: page,
        pageSize: pageSize
      }
    });
  };

  // 获取课程类型标签
  getCourseTypeTag = (type) => {
    return type === '现场' ? 
      <Tag color="blue" className={styles.typeTag}>现场</Tag> : 
      <Tag color="green" className={styles.typeTag}>在线</Tag>;
  };

  render() {
    const { selectedOrgKeys, expandedKeys, trainingPlanData, courseList, pagination } = this.state;

    // 课程表格列配置
    const columns = [
      {
        title: '课程名称',
        dataIndex: 'courseName',
        key: 'courseName',
        render: (text) => <Text strong>{text}</Text>
      },
      {
        title: '讲师',
        dataIndex: 'instructor',
        key: 'instructor'
      },
      {
        title: '课程时间',
        dataIndex: 'courseTime',
        key: 'courseTime'
      },
      {
        title: '课程类型',
        dataIndex: 'courseType',
        key: 'courseType',
        render: (type) => this.getCourseTypeTag(type)
      },
      {
        title: '课程入口',
        dataIndex: 'courseUrl',
        key: 'courseUrl',
        render: (text, record) => (
          <Button 
            type="link" 
            onClick={() => this.handleEnterCourse(record)}
            className={styles.enterBtn}
          >
            {text}
          </Button>
        )
      },
      {
        title: '课程地址',
        dataIndex: 'location',
        key: 'location'
      },
      {
        title: '操作',
        key: 'action',
        render: (_, record) => (
          <Space>
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => this.handleEditCourse(record)}
              className={styles.actionBtn}
            />
            <Button 
              type="text" 
              icon={<DeleteOutlined />} 
              onClick={() => this.handleDeleteCourse(record)}
              className={styles.deleteBtn}
            />
          </Space>
        )
      }
    ];

    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}>
                    {/* 培训基本信息 */}
                    <Card className={styles.infoCard}>
                      <div className={styles.planHeader}>
                        <div className={styles.planInfo}>
                          <Title level={2} className={styles.planTitle}>
                            {trainingPlanData.title}
                          </Title>
                          <div className={styles.planMeta}>
                            <Space size="large">
                              <span className={styles.metaItem}>
                                <CalendarOutlined className={styles.metaIcon} />
                                {trainingPlanData.dateRange}
                              </span>
                              <span className={styles.metaItem}>
                                <TeamOutlined className={styles.metaIcon} />
                                参与人数: {trainingPlanData.participants}人
                              </span>
                              <span className={styles.metaItem}>
                                <ContactsOutlined className={styles.metaIcon} />
                                负责人: {trainingPlanData.manager}
                              </span>
                            </Space>
                          </div>
                        </div>
                        <div className={styles.planActions}>
                          <Button 
                            type="primary" 
                            icon={<EditOutlined />}
                            onClick={this.handleEdit}
                            className={styles.editBtn}
                          >
                            编辑
                          </Button>
                          <Button 
                            icon={<ShareAltOutlined />}
                            onClick={this.handleShare}
                            className={styles.shareBtn}
                          >
                            分享
                          </Button>
                        </div>
                      </div>

                      {/* 统计信息 */}
                      <Row gutter={16} className={styles.statsRow}>
                        <Col span={8}>
                          <div className={styles.statCard}>
                            <div className={styles.statLabel}>培训状态</div>
                            <div className={styles.statValue}>
                              <Tag color="processing">{trainingPlanData.status}</Tag>
                            </div>
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.statCard}>
                            <div className={styles.statLabel}>已完成课程</div>
                            <div className={styles.statValue}>
                              {trainingPlanData.completedCourses}/{trainingPlanData.totalCourses}
                            </div>
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.statCard}>
                            <div className={styles.statLabel}>平均参与率</div>
                            <div className={styles.statValue}>
                              {trainingPlanData.participationRate}%
                            </div>
                          </div>
                        </Col>
                      </Row>

                      {/* 培训描述 */}
                      <div className={styles.description}>
                        <Title level={4} className={styles.descTitle}>培训描述</Title>
                        <Paragraph className={styles.descContent}>
                          {trainingPlanData.description}
                        </Paragraph>
                      </div>
                    </Card>

                    {/* 课程计划列表 */}
                    <Card className={styles.courseCard}>
                      <div className={styles.courseHeader}>
                        <Title level={3} className={styles.courseTitle}>课程计划</Title>
                        <Space>
                          <Button 
                            icon={<FilterOutlined />}
                            onClick={this.handleFilter}
                            className={styles.filterBtn}
                          >
                            筛选
                          </Button>
                          <Button 
                            icon={<DownloadOutlined />}
                            onClick={this.handleExport}
                            className={styles.exportBtn}
                          >
                            导出
                          </Button>
                          <Button 
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={this.handleAddCourse}
                            className={styles.addBtn}
                          >
                            添加课程
                          </Button>
                        </Space>
                      </div>

                      {/* 课程表格 */}
                      <div className={styles.courseTable}>
                        <Table
                          columns={columns}
                          dataSource={courseList}
                          pagination={false}
                          className={styles.table}
                          onRow={(record) => ({
                            className: styles.tableRow
                          })}
                        />

                        {/* 分页 */}
                        <div className={styles.paginationContainer}>
                          <div className={styles.paginationInfo}>
                            显示 {((pagination.current - 1) * pagination.pageSize) + 1} 至{' '}
                            {Math.min(pagination.current * pagination.pageSize, pagination.total)} 项，
                            共 {pagination.total} 项
                          </div>
                          <Pagination
                            current={pagination.current}
                            pageSize={pagination.pageSize}
                            total={pagination.total}
                            onChange={this.handlePaginationChange}
                            showSizeChanger={false}
                            className={styles.pagination}
                          />
                        </div>
                      </div>
                    </Card>
                  </div>
                </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }
}

export default TrainingPlan;