import React, { PureComponent } from 'react';
import {
  Card,
  Tree,
  Input,
  Button,
  DatePicker,
  Select,
  Row,
  Col,
  Space,
  Radio,
  Checkbox,
  InputNumber,
  Avatar,
  message,
  Timeline,
  Tag,
  Typography,
  Divider
} 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
} from '@ant-design/icons';
import dayjs from 'dayjs';
import styles from './Resignation.less';

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

class Resignation extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedOrgKeys: ['0-0-4'], // 默认选中人事部
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
      // 员工异动审批数据
      transferData: {
        employee: {
          name: '林志强',
          employeeId: 'EMP20230085',
          avatar: '/img/avatar1.jpg',
          idCardFront: '/img/card.jpg',
          idCardBack: '/img/card.jpg',
          originalDepartment: '前端开发部',
          newDepartment: '产品设计部',
          originalPosition: '高级前端工程师',
          newPosition: '产品设计师',
          transferType: '部门调动',
          transferDate: '2023-06-15',
          reason: '根据公司人才发展规划，结合员工个人职业发展意愿，经双方协商一致，同意调动。',
          status: '审批中'
        },
        approvalFlow: [
          {
            step: '提交申请',
            status: 'completed',
            operator: '林志强',
            time: '2023-06-05 09:30',
            comment: '申请人：林志强',
            opinion: ''
          },
          {
            step: '部门经理审批',
            status: 'completed',
            operator: '王建国（前端开发部经理）',
            time: '2023-06-05 14:15',
            comment: '审批人：王建国（前端开发部经理）',
            opinion: '同意调动，该员工在产品设计方面有潜力。'
          },
          {
            step: '技术总监审批',
            status: 'completed',
            operator: '张伟（技术中心总监）',
            time: '2023-06-06 10:45',
            comment: '审批人：张伟（技术中心总监）',
            opinion: '同意，符合技术人才发展规划。'
          },
          {
            step: 'HR审批',
            status: 'completed',
            operator: '李芳（人力资源部经理）',
            time: '2023-06-07 11:20',
            comment: '审批人：李芳（人力资源部经理）',
            opinion: '已核实相关情况，同意调动。'
          },
          {
            step: '总经理审批',
            status: 'completed',
            operator: '陈明（总经理）',
            time: '2023-06-08 16:30',
            comment: '审批人：陈明（总经理）',
            opinion: '同意执行。'
          },
          {
            step: '入职生效',
            status: 'processing',
            operator: '',
            time: '待处理',
            comment: '计划生效日期：2023-06-15',
            opinion: ''
          },
          {
            step: '审批完结',
            status: 'waiting',
            operator: '',
            time: '未开始',
            comment: '',
            opinion: ''
          }
        ]
      },
      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 });
  };

  // 同意审批
  handleApprove = () => {
    message.success('同意审批，已提交到下一环节');
  };

  // 拒绝审批
  handleReject = () => {
    message.error('拒绝审批');
  };

  // 打印
  handlePrint = () => {
    window.print();
  };

  // 获取审批状态图标
  getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircleOutlined className={styles.completedIcon} />;
      case 'processing':
        return <LoadingOutlined className={styles.processingIcon} />;
      case 'waiting':
        return <ClockCircleOutlined className={styles.waitingIcon} />;
      default:
        return <ClockCircleOutlined className={styles.waitingIcon} />;
    }
  };

  // 获取状态标签
  getStatusTag = (status) => {
    switch (status) {
      case '审批中':
        return <Tag color="processing">审批中</Tag>;
      case '已通过':
        return <Tag color="success">已通过</Tag>;
      case '已拒绝':
        return <Tag color="error">已拒绝</Tag>;
      default:
        return <Tag color="default">{status}</Tag>;
    }
  };

  render() {
    const { selectedOrgKeys, expandedKeys, transferData } = this.state;
    const { employee, approvalFlow } = transferData;

    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>
                    <Space>
                      <Button 
                        type="primary" 
                        icon={<CheckOutlined />}
                        onClick={this.handleApprove}
                        // className={styles.approveBtn}
                      >
                        同意
                      </Button>
                      <Button 
                        danger
                        icon={<CloseOutlined />}
                        onClick={this.handleReject}
                        // className={styles.rejectBtn}
                      >
                        拒绝
                      </Button>
                      <Button 
                        icon={<PrinterOutlined />}
                        onClick={this.handlePrint}
                      >
                        打印
                      </Button>
                    </Space>
                  </div>

                  {/* 滚动内容区 */}
                  <div className={styles.content}>
                    {/* 基本信息卡片 */}
                    <Card className={styles.infoCard} title="基本信息">
                      <Row gutter={24}>
                        {/* 员工照片 */}
                        <Col span={6}>
                          <div className={styles.photoContainer}>
                            <img 
                              src={employee.avatar} 
                              alt="员工照片" 
                              className={styles.employeePhoto}
                            />
                            <Text className={styles.photoLabel}>员工照片</Text>
                          </div>
                        </Col>

                        {/* 基本信息 */}
                        <Col span={18}>
                          <div className={styles.basicInfo}>
                            <Row gutter={[16, 12]}>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>员工姓名：</Text>
                                  <Text className={styles.infoValue}>{employee.name}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>员工编号：</Text>
                                  <Text className={styles.infoValue}>{employee.employeeId}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>原部门：</Text>
                                  <Text className={styles.infoValue}>{employee.originalDepartment}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>新部门：</Text>
                                  <Text className={styles.infoValue}>{employee.newDepartment}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>原岗位：</Text>
                                  <Text className={styles.infoValue}>{employee.originalPosition}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>新岗位：</Text>
                                  <Text className={styles.infoValue}>{employee.newPosition}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>异动类型：</Text>
                                  <Text className={styles.infoValue}>{employee.transferType}</Text>
                                </div>
                              </Col>
                              <Col span={12}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>异动时间：</Text>
                                  <Text className={styles.infoValue}>{employee.transferDate}</Text>
                                </div>
                              </Col>
                              <Col span={24}>
                                <div className={styles.infoItem}>
                                  <Text className={styles.infoLabel}>异动原因：</Text>
                                  <Text className={styles.infoValue}>{employee.reason}</Text>
                                </div>
                              </Col>
                            </Row>
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 证件信息 */}
                    <Card className={styles.infoCard} title="证件信息">
                      <Row gutter={24}>
                        <Col span={12}>
                          <div className={styles.idCardContainer}>
                            <Text className={styles.photoLabel}>身份证正面</Text>
                            <img 
                              src={employee.idCardFront} 
                              alt="身份证正面" 
                              className={styles.idCardPhoto}
                            />
                          </div>
                        </Col>
                        <Col span={12}>
                          <div className={styles.idCardContainer}>
                            <Text className={styles.photoLabel}>身份证反面</Text>
                            <img 
                              src={employee.idCardBack} 
                              alt="身份证反面" 
                              className={styles.idCardPhoto}
                            />
                          </div>
                        </Col>
                      </Row>
                    </Card>

                    {/* 审批流程 */}
                    <Card className={styles.infoCard} title="审批流程">
                      <Timeline className={styles.approvalTimeline}>
                        {approvalFlow.map((flow, index) => (
                          <Timeline.Item
                            key={index}
                            dot={this.getStatusIcon(flow.status)}
                            className={styles.timelineItem}
                          >
                            <div className={styles.timelineContent}>
                              <div className={styles.timelineHeader}>
                                <Text strong className={styles.stepTitle}>{flow.step}</Text>
                                <Text className={styles.stepTime}>{flow.time}</Text>
                              </div>
                              <Paragraph className={styles.stepComment}>
                                {flow.comment}
                              </Paragraph>
                              {flow.opinion && (
                                <div className={styles.stepOpinion}>
                                  <Text>审批意见：{flow.opinion}</Text>
                                </div>
                              )}
                            </div>
                          </Timeline.Item>
                        ))}
                      </Timeline>
                    </Card>
                  </div>
                </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }
}

export default Resignation;