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

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

class Training extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedOrgKeys: ['0-0-4'], // 默认选中人事部
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
      searchKeyword: '',
      // 培训数据
      trainingData: {
        basicInfo: {
          name: '',
          cover: null,
          description: ''
        },
        details: {
          startDate: null,
          endDate: null,
          cost: ''
        }
      },
      // 可选课程
      availableCourses: [
        {
          id: 1,
          name: '高效沟通技巧',
          instructor: '张明远',
          duration: '2小时',
          selected: false
        },
        {
          id: 2,
          name: '团队协作与领导力',
          instructor: '李思雨',
          duration: '3小时',
          selected: false
        },
        {
          id: 3,
          name: '项目管理实战',
          instructor: '王建国',
          duration: '4小时',
          selected: false
        },
        {
          id: 4,
          name: 'Excel高级应用',
          instructor: '陈晓芳',
          duration: '2.5小时',
          selected: false
        },
        {
          id: 5,
          name: '商务礼仪与职业形象',
          instructor: '赵雅芝',
          duration: '2小时',
          selected: false
        }
      ],
      // 已选课程
      selectedCourses: [
        {
          id: 1,
          name: '高效沟通技巧',
          instructor: '张明远',
          duration: '2小时',
          scheduleDate: null,
          scheduleTime: null,
          showSchedule: false
        },
        {
          id: 2,
          name: '团队协作与领导力',
          instructor: '李思雨',
          duration: '3小时',
          scheduleDate: null,
          scheduleTime: null,
          showSchedule: false
        }
      ],
      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 });
  };

  // 新建培训
  handleCreateTraining = () => {
    message.success('新建培训');
  };

  // 选择课程
  handleSelectCourse = (course) => {
    const { selectedCourses, availableCourses } = this.state;
    
    // 检查是否已经选择
    const isSelected = selectedCourses.find(item => item.id === course.id);
    if (isSelected) {
      message.warning('该课程已经选择');
      return;
    }

    const newSelectedCourse = {
      ...course,
      scheduleDate: null,
      scheduleTime: null,
      showSchedule: false
    };

    this.setState({
      selectedCourses: [...selectedCourses, newSelectedCourse],
      availableCourses: availableCourses.map(item => 
        item.id === course.id ? { ...item, selected: true } : item
      )
    });
    message.success('课程添加成功');
  };

  // 移除课程
  handleRemoveCourse = (courseId) => {
    const { selectedCourses, availableCourses } = this.state;
    
    this.setState({
      selectedCourses: selectedCourses.filter(item => item.id !== courseId),
      availableCourses: availableCourses.map(item => 
        item.id === courseId ? { ...item, selected: false } : item
      )
    });
    message.success('课程移除成功');
  };

  // 设置课程时间
  handleSetSchedule = (courseId) => {
    const { selectedCourses } = this.state;
    this.setState({
      selectedCourses: selectedCourses.map(item => 
        item.id === courseId ? { ...item, showSchedule: !item.showSchedule } : item
      )
    });
  };

  // 确认时间设置
  handleConfirmSchedule = (courseId, date, time) => {
    const { selectedCourses } = this.state;
    this.setState({
      selectedCourses: selectedCourses.map(item => 
        item.id === courseId ? { 
          ...item, 
          scheduleDate: date, 
          scheduleTime: time, 
          showSchedule: false 
        } : item
      )
    });
    message.success('时间设置成功');
  };

  // 搜索课程
  handleSearchCourse = (value) => {
    this.setState({ searchKeyword: value });
  };

  // 保存培训
  handleSave = () => {
    message.success('培训保存成功');
  };

  // 取消
  handleCancel = () => {
    message.info('取消操作');
  };

  // 封面上传
  handleCoverUpload = (info) => {
    if (info.file.status === 'done') {
      message.success('封面上传成功');
    }
  };

  // 过滤课程
  getFilteredCourses = () => {
    const { availableCourses, searchKeyword } = this.state;
    if (!searchKeyword) return availableCourses;
    
    return availableCourses.filter(course => 
      course.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      course.instructor.toLowerCase().includes(searchKeyword.toLowerCase())
    );
  };

  render() {
    const { selectedOrgKeys, expandedKeys, selectedCourses, searchKeyword } = this.state;
    const filteredCourses = this.getFilteredCourses();

    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.header}>
                    <Title level={3} style={{ margin: 0, color: '#333', fontSize: '20px' }}>
                      培训管理
                    </Title>
                    <Button 
                      type="primary" 
                      icon={<PlusCircleOutlined />}
                      onClick={this.handleCreateTraining}
                      className={styles.createBtn}
                    >
                      新建培训
                    </Button>
                  </div>

                  {/* 滚动内容区 */}
                  <div className={styles.content}>
                    {/* 培训基本信息 */}
                    <Card className={styles.sectionCard} title="基本信息">
                      <Row gutter={16}>
                        <Col span={12}>
                          <div className={styles.formItem}>
                            <Text className={styles.formLabel}>培训名称</Text>
                            <Input 
                              placeholder="请输入培训名称"
                              className={styles.formInput}
                            />
                          </div>
                        </Col>
                        <Col span={12}>
                          <div className={styles.formItem}>
                            <Text className={styles.formLabel}>培训封面</Text>
                            <div className={styles.uploadContainer}>
                              <Upload
                                showUploadList={false}
                                onChange={this.handleCoverUpload}
                                className={styles.coverUpload}
                              >
                                <div className={styles.uploadArea}>
                                  <PictureOutlined className={styles.uploadIcon} />
                                </div>
                              </Upload>
                              <Text className={styles.uploadText}>点击上传封面</Text>
                            </div>
                          </div>
                        </Col>
                      </Row>
                      <div className={styles.formItem}>
                        <Text className={styles.formLabel}>主题设计</Text>
                        <TextArea 
                          rows={4}
                          placeholder="在此输入培训主题和描述..."
                          className={styles.formTextArea}
                        />
                      </div>
                    </Card>

                    {/* 培训详情 */}
                    <Card className={styles.sectionCard} title="培训详情">
                      <Row gutter={16}>
                        <Col span={16}>
                          <div className={styles.formItem}>
                            <Text className={styles.formLabel}>培训时间</Text>
                            <RangePicker 
                              style={{ width: '100%' }}
                              className={styles.formInput}
                            />
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <Text className={styles.formLabel}>培训费用(元)</Text>
                            <InputNumber 
                              placeholder="请输入费用"
                              style={{ width: '100%' }}
                              className={styles.formInput}
                            />
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 课程管理 */}
                    <Card className={styles.sectionCard} title="课程管理">
                      <Row gutter={16}>
                        {/* 可选课程 */}
                        <Col span={12}>
                          <div className={styles.courseSection}>
                            <div className={styles.courseSectionHeader}>
                              <Text className={styles.courseSectionTitle}>可选课程</Text>
                              <Input 
                                placeholder="搜索课程"
                                prefix={<SearchOutlined />}
                                value={searchKeyword}
                                onChange={(e) => this.handleSearchCourse(e.target.value)}
                                className={styles.searchInput}
                              />
                            </div>
                            <div className={styles.courseList}>
                              {filteredCourses.map(course => (
                                <div 
                                  key={course.id} 
                                  className={`${styles.courseItem} ${course.selected ? styles.courseItemSelected : ''}`}
                                  onClick={() => this.handleSelectCourse(course)}
                                >
                                  <div className={styles.courseInfo}>
                                    <Text className={styles.courseName}>{course.name}</Text>
                                    <Text className={styles.courseInstructor}>讲师: {course.instructor}</Text>
                                  </div>
                                  <Tag className={styles.courseDuration}>{course.duration}</Tag>
                                </div>
                              ))}
                            </div>
                          </div>
                        </Col>

                        {/* 已选课程 */}
                        <Col span={12}>
                          <div className={styles.courseSection}>
                            <Text className={styles.courseSectionTitle}>已选课程</Text>
                            <div className={styles.courseList}>
                              {selectedCourses.map(course => (
                                <div key={course.id} className={styles.selectedCourseItem}>
                                  <div className={styles.courseItemHeader}>
                                    <div className={styles.courseInfo}>
                                      <Text className={styles.courseName}>{course.name}</Text>
                                      <Text className={styles.courseInstructor}>讲师: {course.instructor}</Text>
                                    </div>
                                    <div className={styles.courseActions}>
                                      <Tag className={styles.courseDuration}>{course.duration}</Tag>
                                      <Button 
                                        type="link" 
                                        size="small"
                                        onClick={() => this.handleSetSchedule(course.id)}
                                        className={styles.scheduleBtn}
                                      >
                                        设置时间
                                      </Button>
                                      <Button 
                                        type="text" 
                                        size="small"
                                        icon={<DeleteOutlined />}
                                        onClick={() => this.handleRemoveCourse(course.id)}
                                        className={styles.removeBtn}
                                      />
                                    </div>
                                  </div>
                                  
                                  {course.showSchedule && (
                                    <div className={styles.scheduleSettings}>
                                      <div className={styles.scheduleRow}>
                                        <Text className={styles.scheduleLabel}>上课时间:</Text>
                                        <DatePicker 
                                          placeholder="选择日期"
                                          className={styles.dateInput}
                                        />
                                        <Input 
                                          type="time"
                                          className={styles.timeInput}
                                        />
                                      </div>
                                      <div className={styles.scheduleActions}>
                                        <Button 
                                          type="primary" 
                                          size="small"
                                          onClick={() => this.handleConfirmSchedule(course.id)}
                                          className={styles.confirmBtn}
                                        >
                                          确认
                                        </Button>
                                      </div>
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 底部操作按钮 */}
                    <div className={styles.actionButtons}>
                      <Button onClick={this.handleCancel}>取消</Button>
                      <Button 
                        type="primary" 
                        onClick={this.handleSave}
                        className={styles.saveBtn}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }
}

export default Training;