import React, { PureComponent } from 'react';
import {
  Card,
  Tree,
  Input,
  Button,
  DatePicker,
  Select,
  Row,
  Col,
  Space,
  Radio,
  Checkbox,
  InputNumber,
  Avatar,
  message,
  Typography
} from 'antd';
import {
  SaveOutlined,
  CloseOutlined,
  PlusCircleOutlined,
  DeleteOutlined,
  ExpandOutlined,
  UserOutlined,
  TeamOutlined,
  ApartmentOutlined,
  SyncOutlined,
  DollarOutlined,
  SettingOutlined,
  CalendarOutlined,
  UsergroupAddOutlined,
  UserSwitchOutlined,
  StopOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ContactsOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import styles from './OnBoarding.less';

const { Option } = Select;
const { TextArea } = Input;
const { Title } = Typography;
class OnBoarding extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedOrgKeys: ['0-0-4'], // 默认选中人事部
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
      // 入职计划表单数据
      onboardingForm: {
        // 入职部门信息
        departmentName: '人力资源部',
        departmentManager: '张明远',
        currentStaff: '24/30',
        
        // 计划时段设置
        planStartDate: dayjs('2023-09-01'),
        planEndDate: dayjs('2023-09-30'),
        
        // 可入职岗位设置
        availablePositions: [
          { id: 1, name: '人力资源专员', count: 3, checked: true },
          { id: 2, name: '薪酬福利专员', count: 2, checked: true },
          { id: 3, name: '培训发展专员', count: 1, checked: false },
          { id: 4, name: '招聘专员', count: 2, checked: false }
        ],
        
        // 计划入职人数
        totalPlan: 5,
        confirmedCount: 2,
        remainingCount: 3,
        
        // 人员要求
        ageRange: '22-30岁',
        gender: '不限',
        education: '本科及以上',
        workYears: '1-3年',
        otherRequirements: '',
        
        // 黑名单
        blacklist: [
          { id: 1, name: '林晓梅', idCard: '310***19880512****', avatar: null },
          { id: 2, name: '王建国', idCard: '420***19900215****', avatar: null }
        ],
        
        // 白名单
        whitelist: [
          { id: 1, name: '陈思思', recommender: '张明远', avatar: null }
        ]
      },
      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 });
    
    if (selectedKeys.length > 0) {
      const selectedKey = selectedKeys[0];
      const findNodeByKey = (nodes, key) => {
        for (let node of nodes) {
          if (node.key === key) {
            return node;
          }
          if (node.children) {
            const found = findNodeByKey(node.children, key);
            if (found) return found;
          }
        }
        return null;
      };
      
      const selectedNode = findNodeByKey(this.state.organizationData, selectedKey);
      if (selectedNode) {
        this.handleOnboardingFormChange('departmentName', selectedNode.title);
        const departmentInfo = this.getDepartmentInfo(selectedNode.title);
        this.setState(prevState => ({
          onboardingForm: {
            ...prevState.onboardingForm,
            ...departmentInfo
          }
        }));
      }
    }
  };

  // 获取部门信息
  getDepartmentInfo = (departmentName) => {
    const departmentMap = {
      '技术部': {
        departmentManager: '李技术',
        currentStaff: '115/120',
        availablePositions: [
          { id: 1, name: '前端工程师', count: 2, checked: true },
          { id: 2, name: '后端工程师', count: 3, checked: true },
          { id: 3, name: '测试工程师', count: 1, checked: false }
        ]
      },
      '产品部': {
        departmentManager: '王产品',
        currentStaff: '65/68',
        availablePositions: [
          { id: 1, name: '产品经理', count: 1, checked: true },
          { id: 2, name: '产品设计师', count: 2, checked: true }
        ]
      },
      '人事部': {
        departmentManager: '张明远',
        currentStaff: '24/30',
        availablePositions: [
          { id: 1, name: '人力资源专员', count: 3, checked: true },
          { id: 2, name: '薪酬福利专员', count: 2, checked: true },
          { id: 3, name: '培训发展专员', count: 1, checked: false },
          { id: 4, name: '招聘专员', count: 2, checked: false }
        ]
      },
      '财务部': {
        departmentManager: '赵财务',
        currentStaff: '30/32',
        availablePositions: [
          { id: 1, name: '会计', count: 1, checked: true },
          { id: 2, name: '出纳', count: 1, checked: false }
        ]
      },
      '运营部': {
        departmentManager: '钱运营',
        currentStaff: '48/52',
        availablePositions: [
          { id: 1, name: '市场专员', count: 2, checked: true },
          { id: 2, name: '客服专员', count: 1, checked: true }
        ]
      }
    };
    
    return departmentMap[departmentName] || {
      departmentManager: '未知',
      currentStaff: '0/0',
      availablePositions: []
    };
  };

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

  // 入职表单字段变化
  handleOnboardingFormChange = (field, value) => {
    this.setState(prevState => ({
      onboardingForm: {
        ...prevState.onboardingForm,
        [field]: value
      }
    }));
  };

  // 岗位选择变化
  handlePositionChange = (id, checked) => {
    const { onboardingForm } = this.state;
    const newPositions = onboardingForm.availablePositions.map(pos => 
      pos.id === id ? { ...pos, checked } : pos
    );
    this.setState({
      onboardingForm: {
        ...onboardingForm,
        availablePositions: newPositions
      }
    });
  };

  // 添加新岗位
  addNewPosition = () => {
    const { onboardingForm } = this.state;
    const newPosition = {
      id: Date.now(),
      name: '新岗位',
      count: 1,
      checked: false
    };
    this.setState({
      onboardingForm: {
        ...onboardingForm,
        availablePositions: [...onboardingForm.availablePositions, newPosition]
      }
    });
    message.success('新岗位添加成功');
  };

  // 移除黑名单人员
  removeFromBlacklist = (id) => {
    const { onboardingForm } = this.state;
    const newBlacklist = onboardingForm.blacklist.filter(person => person.id !== id);
    this.setState({
      onboardingForm: {
        ...onboardingForm,
        blacklist: newBlacklist
      }
    });
    message.success('已移除黑名单人员');
  };

  // 移除白名单人员
  removeFromWhitelist = (id) => {
    const { onboardingForm } = this.state;
    const newWhitelist = onboardingForm.whitelist.filter(person => person.id !== id);
    this.setState({
      onboardingForm: {
        ...onboardingForm,
        whitelist: newWhitelist
      }
    });
    message.success('已移除白名单人员');
  };

  // 添加黑名单人员
  addToBlacklist = () => {
    message.info('功能开发中，敬请期待');
  };

  // 添加白名单人员
  addToWhitelist = () => {
    message.info('功能开发中，敬请期待');
  };

  // 保存设置
  handleSave = () => {
    const { onboardingForm } = this.state;
    
    if (!onboardingForm.departmentName) {
      message.error('请选择部门');
      return;
    }
    
    if (!onboardingForm.planStartDate || !onboardingForm.planEndDate) {
      message.error('请选择计划时段');
      return;
    }
    
    if (onboardingForm.planStartDate.isAfter(onboardingForm.planEndDate)) {
      message.error('开始日期不能晚于结束日期');
      return;
    }
    
    if (onboardingForm.totalPlan <= 0) {
      message.error('计划总人数必须大于0');
      return;
    }
    
    console.log('保存入职计划设置：', onboardingForm);
    message.success('入职计划设置保存成功');
  };

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

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

    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>

              {/* 右侧入职计划设置 - 替换为HTML内容 */}
              <Col span={19}>
                <Card className={styles.mainCard}>
                  {/* 头部标题 */}
                  <div className={styles.header}>
                    <Title level={3} style={{ margin: 0, color: '#333', fontSize: '18px' }}>
                      入职计划设置
                    </Title>
                    <Space>
                      <Button 
                        type="primary" 
                        icon={<SaveOutlined />}
                        onClick={this.handleSave}
                      >
                        保存设置
                      </Button>
                      <Button 
                        icon={<CloseOutlined />}
                        onClick={this.handleCancel}
                      >
                        取消
                      </Button>
                    </Space>
                  </div>

                  {/* 表单内容区 */}
                  <div className={styles.content}>
                    {/* 入职部门信息 */}
                    <Card 
                      title={
                        <span>
                          <ApartmentOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          入职部门信息
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <Row gutter={16}>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <label>部门名称</label>
                            <div className={styles.readOnlyField}>
                              {onboardingForm.departmentName}
                            </div>
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <label>部门负责人</label>
                            <div className={styles.readOnlyField}>
                              {onboardingForm.departmentManager}
                            </div>
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <label>当前在岗人数</label>
                            <div className={styles.readOnlyField}>
                              {onboardingForm.currentStaff}
                            </div>
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 计划时段设置 */}
                    <Card 
                      title={
                        <span>
                          <CalendarOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          计划时段设置
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <Row gutter={16}>
                        <Col span={12}>
                          <div className={styles.formItem}>
                            <label>计划开始日期</label>
                            <DatePicker
                              value={onboardingForm.planStartDate}
                              style={{ width: '100%' }}
                              onChange={(date) => this.handleOnboardingFormChange('planStartDate', date)}
                              placeholder="选择开始日期"
                            />
                          </div>
                        </Col>
                        <Col span={12}>
                          <div className={styles.formItem}>
                            <label>计划结束日期</label>
                            <DatePicker
                              value={onboardingForm.planEndDate}
                              style={{ width: '100%' }}
                              onChange={(date) => this.handleOnboardingFormChange('planEndDate', date)}
                              placeholder="选择结束日期"
                            />
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 可入职岗位设置 */}
                    <Card 
                      title={
                        <span>
                          <ContactsOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          可入职岗位设置
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <div className={styles.positionList}>
                        {onboardingForm.availablePositions.map(position => (
                          <div key={position.id} className={styles.positionItem}>
                            <Checkbox
                              checked={position.checked}
                              onChange={(e) => this.handlePositionChange(position.id, e.target.checked)}
                            >
                              {position.name} ({position.count}人)
                            </Checkbox>
                          </div>
                        ))}
                        <Button 
                          type="link" 
                          icon={<PlusCircleOutlined />}
                          onClick={this.addNewPosition}
                          className={styles.addButton}
                        >
                          添加其他岗位
                        </Button>
                      </div>
                    </Card>

                    {/* 计划入职人数 */}
                    <Card 
                      title={
                        <span>
                          <UsergroupAddOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          计划入职人数
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <Row gutter={16}>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <label>计划总人数</label>
                            <InputNumber
                              value={onboardingForm.totalPlan}
                              min={0}
                              style={{ width: '100%' }}
                              onChange={(value) => this.handleOnboardingFormChange('totalPlan', value)}
                              placeholder="请输入计划总人数"
                            />
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <label>已确认人数</label>
                            <InputNumber
                              value={onboardingForm.confirmedCount}
                              disabled
                              style={{ width: '100%' }}
                            />
                          </div>
                        </Col>
                        <Col span={8}>
                          <div className={styles.formItem}>
                            <label>剩余名额</label>
                            <InputNumber
                              value={onboardingForm.remainingCount}
                              disabled
                              style={{ width: '100%' }}
                            />
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 人员要求 */}
                    <Card 
                      title={
                        <span>
                          <UserSwitchOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          人员要求
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <div className={styles.requirementSection}>
                        <div className={styles.formItem}>
                          <label style={{display: 'block',marginRight: '10px'}}>年龄段</label>
                          <Radio.Group 
                            value={onboardingForm.ageRange}
                            onChange={(e) => this.handleOnboardingFormChange('ageRange', e.target.value)}
                          >
                            <Radio value="22-30岁">22-30岁</Radio>
                            <Radio value="30-35岁">30-35岁</Radio>
                            <Radio value="不限">不限</Radio>
                          </Radio.Group>
                        </div>

                        <div className={styles.formItem}>
                          <label style={{display: 'block', marginRight: '10px'}}>性别</label>
                          <Radio.Group 
                            value={onboardingForm.gender}
                            onChange={(e) => this.handleOnboardingFormChange('gender', e.target.value)}
                          >
                            <Radio value="男">男</Radio>
                            <Radio value="女">女</Radio>
                            <Radio value="不限">不限</Radio>
                          </Radio.Group>
                        </div>

                        <Row gutter={16}>
                          <Col span={12}>
                            <div className={styles.formItem}>
                              <label>学历要求</label>
                              <Select
                                value={onboardingForm.education}
                                style={{ width: '100%' }}
                                onChange={(value) => this.handleOnboardingFormChange('education', value)}
                                placeholder="请选择学历要求"
                              >
                                <Option value="本科及以上">本科及以上</Option>
                                <Option value="硕士及以上">硕士及以上</Option>
                                <Option value="大专及以上">大专及以上</Option>
                                <Option value="不限">不限</Option>
                              </Select>
                            </div>
                          </Col>
                          <Col span={12}>
                            <div className={styles.formItem}>
                              <label>工作年限</label>
                              <Select
                                value={onboardingForm.workYears}
                                style={{ width: '100%' }}
                                onChange={(value) => this.handleOnboardingFormChange('workYears', value)}
                                placeholder="请选择工作年限"
                              >
                                <Option value="1-3年">1-3年</Option>
                                <Option value="3-5年">3-5年</Option>
                                <Option value="5年以上">5年以上</Option>
                                <Option value="不限">不限</Option>
                              </Select>
                            </div>
                          </Col>
                        </Row>

                        <div className={styles.formItem}>
                          <label>其他要求</label>
                          <TextArea
                            value={onboardingForm.otherRequirements}
                            rows={3}
                            placeholder="请输入其他特殊要求..."
                            onChange={(e) => this.handleOnboardingFormChange('otherRequirements', e.target.value)}
                          />
                        </div>
                      </div>
                    </Card>

                    {/* 黑名单设置 */}
                    <Card 
                      title={
                        <span>
                          <StopOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          黑名单设置
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <div className={styles.personList}>
                        {onboardingForm.blacklist.map(person => (
                          <div key={person.id} className={styles.personItem}>
                            <div className={styles.personInfo}>
                              <Avatar 
                                src={person.avatar} 
                                size={32} 
                                icon={!person.avatar ? <UserOutlined /> : undefined}
                              />
                              <div className={styles.personDetails}>
                                <div className={styles.personName}>{person.name}</div>
                                <div className={styles.personMeta}>身份证: {person.idCard}</div>
                              </div>
                            </div>
                            <Button 
                              type="link" 
                              danger 
                              size="small"
                              icon={<CloseCircleOutlined />}
                              onClick={() => this.removeFromBlacklist(person.id)}
                            >
                              移除
                            </Button>
                          </div>
                        ))}
                        <Button 
                          type="link" 
                          icon={<PlusCircleOutlined />}
                          onClick={this.addToBlacklist}
                          className={styles.addButton}
                        >
                          添加黑名单人员
                        </Button>
                      </div>
                    </Card>

                    {/* 白名单设置 */}
                    <Card 
                      title={
                        <span>
                          <CheckCircleOutlined style={{ marginRight: 8, color: '#2D5CF6' }} />
                          白名单设置
                        </span>
                      } 
                      size="small" 
                      className={styles.formCard}
                    >
                      <div className={styles.personList}>
                        {onboardingForm.whitelist.map(person => (
                          <div key={person.id} className={styles.personItem}>
                            <div className={styles.personInfo}>
                              <Avatar 
                                src={person.avatar} 
                                size={32} 
                                icon={!person.avatar ? <UserOutlined /> : undefined}
                              />
                              <div className={styles.personDetails}>
                                <div className={styles.personName}>{person.name}</div>
                                <div className={styles.personMeta}>推荐人: {person.recommender}</div>
                              </div>
                            </div>
                            <Button 
                              type="link" 
                              danger 
                              size="small"
                              icon={<CloseCircleOutlined />}
                              onClick={() => this.removeFromWhitelist(person.id)}
                            >
                              移除
                            </Button>
                          </div>
                        ))}
                        <Button 
                          type="link" 
                          icon={<PlusCircleOutlined />}
                          onClick={this.addToWhitelist}
                          className={styles.addButton}
                        >
                          添加白名单人员
                        </Button>
                      </div>
                    </Card>
                  </div>
                </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }
}

export default OnBoarding;