import React, { PureComponent } from 'react';
import {
  Card,
  Tree,
  Input,
  Button,
  DatePicker,
  Select,
  Table,
  Form,
  Row,
  Col,
  Space,
  Divider,
  message
} from 'antd';
import {
  SaveOutlined,
  CloseOutlined,
  PlusOutlined,
  DeleteOutlined,
  ExpandOutlined,
  FilterOutlined,
  DownOutlined,
  UserOutlined,
  TeamOutlined,
  ApartmentOutlined,
  SyncOutlined,
  DollarOutlined,
  SettingOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import styles from './SalaryRuleset.less';

const { Option } = Select;
const { TextArea } = Input;

class SalaryRuleset extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedOrgKeys: [],
      expandedKeys: ['0-0', '0-0-0', '0-0-1', '0-0-2'],
      form: {
        ruleName: '',
        applicableOrg: '集团公司/北京分公司',
        effectiveDate: dayjs('2023-07-01'),
        socialBase: '员工基本工资',
        fundBase: '员工基本工资',
        taxThreshold: '5000',
        specialDeduction: '自动计算'
      },
      salaryItems: [
        {
          key: '1',
          name: '基本工资',
          type: '固定工资',
          taxType: '税前',
          formula: '岗位工资基数 * 职级系数'
        },
        {
          key: '2',
          name: '绩效奖金',
          type: '浮动工资',
          taxType: '税前',
          formula: '基本工资 * 绩效系数'
        },
        {
          key: '3',
          name: '交通补贴',
          type: '补贴',
          taxType: '税后',
          formula: '固定金额 500'
        }
      ],
      insuranceRates: [
        { key: '1', name: '养老保险', companyRate: '16%', personalRate: '8%' },
        { key: '2', name: '医疗保险', companyRate: '9.5%', personalRate: '2%' },
        { key: '3', name: '失业保险', companyRate: '0.5%', personalRate: '0.5%' },
        { key: '4', name: '公积金', companyRate: '12%', personalRate: '12%' }
      ],
      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' }} />;
    if (title.includes('技术') || title.includes('开发') || title.includes('测试')) return <SettingOutlined style={{ color: '#52c41a' }} />;
    if (title.includes('产品') || title.includes('设计') || title.includes('体验')) return <TeamOutlined style={{ color: '#fa8c16' }} />;
    if (title.includes('运营') || title.includes('市场') || title.includes('客户') || title.includes('商务')) return <TeamOutlined style={{ color: '#eb2f96' }} />;
    if (title.includes('财务') || title.includes('会计') || title.includes('审计')) return <DollarOutlined style={{ color: '#722ed1' }} />;
    if (title.includes('人事') || title.includes('HR') || title.includes('招聘') || title.includes('培训') || title.includes('薪酬')) return <UserOutlined style={{ color: '#13c2c2' }} />;
    return <TeamOutlined style={{ color: '#666' }} />;
  };

  // 刷新树数据
  handleTreeRefresh = () => {
    // 这里可以添加刷新树数据的逻辑
  };

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

  // 薪酬项表格列配置
  salaryColumns = [
    {
      title: '薪酬项名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text, record, index) => (
        <Input
          size="small"
          value={text}
          onChange={(e) => this.handleSalaryItemChange(index, 'name', e.target.value)}
        />
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (text, record, index) => (
        <Select
          size="small"
          value={text}
          style={{ width: '100%' }}
          onChange={(value) => this.handleSalaryItemChange(index, 'type', value)}
        >
          <Option value="固定工资">固定工资</Option>
          <Option value="浮动工资">浮动工资</Option>
          <Option value="补贴">补贴</Option>
        </Select>
      )
    },
    {
      title: '计税方式',
      dataIndex: 'taxType',
      key: 'taxType',
      width: 120,
      render: (text, record, index) => (
        <Select
          size="small"
          value={text}
          style={{ width: '100%' }}
          onChange={(value) => this.handleSalaryItemChange(index, 'taxType', value)}
        >
          <Option value="税前">税前</Option>
          <Option value="税后">税后</Option>
        </Select>
      )
    },
    {
      title: '计算公式',
      dataIndex: 'formula',
      key: 'formula',
      width: 250,
      render: (text, record, index) => (
        <Input
          size="small"
          value={text}
          onChange={(e) => this.handleSalaryItemChange(index, 'formula', e.target.value)}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record, index) => (
        <Button
          type="link"
          danger
          size="small"
          icon={<DeleteOutlined />}
          onClick={() => this.deleteSalaryItem(index)}
        />
      )
    }
  ];

  // 保险缴费比例表格列配置
  insuranceColumns = [
    {
      title: '项目',
      dataIndex: 'name',
      key: 'name',
      width: 120
    },
    {
      title: '单位比例',
      dataIndex: 'companyRate',
      key: 'companyRate',
      width: 120,
      render: (text, record, index) => (
        <Input
          size="small"
          value={text}
          style={{ width: '80px' }}
          onChange={(e) => this.handleInsuranceRateChange(index, 'companyRate', e.target.value)}
        />
      )
    },
    {
      title: '个人比例',
      dataIndex: 'personalRate',
      key: 'personalRate',
      width: 120,
      render: (text, record, index) => (
        <Input
          size="small"
          value={text}
          style={{ width: '80px' }}
          onChange={(e) => this.handleInsuranceRateChange(index, 'personalRate', e.target.value)}
        />
      )
    }
  ];

  // 组织树选择
  onTreeSelect = (selectedKeys, info) => {
    console.log('选中节点:', selectedKeys, info);
    this.setState({ selectedOrgKeys: selectedKeys });
    if (selectedKeys.length > 0) {
      const selectedNode = info.node;
      // 从节点的title中提取组织名称
      const orgName = selectedNode.title.props ? 
        selectedNode.title.props.children[1].props.children : 
        selectedNode.title;
      this.handleFormChange('applicableOrg', orgName);
    }
  };

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

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

  // 薪酬项变化
  handleSalaryItemChange = (index, field, value) => {
    const { salaryItems } = this.state;
    const newItems = [...salaryItems];
    newItems[index][field] = value;
    this.setState({ salaryItems: newItems });
  };

  // 删除薪酬项
  deleteSalaryItem = (index) => {
    const { salaryItems } = this.state;
    const newItems = salaryItems.filter((_, i) => i !== index);
    this.setState({ salaryItems: newItems });
    message.success('已删除薪酬项');
  };

  // 添加薪酬项
  addSalaryItem = () => {
    const { salaryItems } = this.state;
    const newItem = {
      key: Date.now().toString(),
      name: '',
      type: '固定工资',
      taxType: '税前',
      formula: ''
    };
    this.setState({ salaryItems: [...salaryItems, newItem] });
  };

  // 保险费率变化
  handleInsuranceRateChange = (index, field, value) => {
    const { insuranceRates } = this.state;
    const newRates = [...insuranceRates];
    newRates[index][field] = value;
    this.setState({ insuranceRates: newRates });
  };

  // 保存规则
  handleSave = () => {
    const { form, salaryItems, insuranceRates } = this.state;
    
    if (!form.ruleName.trim()) {
      message.error('请输入规则名称');
      return;
    }

    // 这里应该调用API保存数据
    console.log('保存数据：', {
      form,
      salaryItems,
      insuranceRates
    });
    
    message.success('薪酬规则保存成功');
  };

  // 取消操作
  handleCancel = () => {
    // 重置表单或返回上一页
    message.info('已取消操作');
  };

  render() {
    const { selectedOrgKeys, expandedKeys, form, salaryItems, insuranceRates } = 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>

              {/* 右侧主要内容 */}
              <Col span={19}>
            <Card className={styles.mainCard}>
              {/* 头部操作区 */}
              <div className={styles.header}>
                <h2>薪酬计算规则设置</h2>
                <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="基本信息" size="small" className={styles.formCard}>
                  <Row gutter={16}>
                    <Col span={8}>
                      <div className={styles.formItem}>
                        <label>规则名称</label>
                        <Input
                          value={form.ruleName}
                          placeholder="请输入规则名称"
                          onChange={(e) => this.handleFormChange('ruleName', e.target.value)}
                        />
                      </div>
                    </Col>
                    <Col span={8}>
                      <div className={styles.formItem}>
                        <label>适用组织</label>
                        <Select
                          value={form.applicableOrg}
                          style={{ width: '100%' }}
                          onChange={(value) => this.handleFormChange('applicableOrg', value)}
                          suffixIcon={<DownOutlined />}
                        >
                          <Option value="集团公司">集团公司</Option>
                          <Option value="集团公司/北京分公司">集团公司/北京分公司</Option>
                          <Option value="集团公司/上海分公司">集团公司/上海分公司</Option>
                          <Option value="集团公司/深圳分公司">集团公司/深圳分公司</Option>
                        </Select>
                      </div>
                    </Col>
                    <Col span={8}>
                      <div className={styles.formItem}>
                        <label>生效日期</label>
                        <DatePicker
                          value={form.effectiveDate}
                          style={{ width: '100%' }}
                          onChange={(date) => this.handleFormChange('effectiveDate', date)}
                        />
                      </div>
                    </Col>
                  </Row>
                </Card>

                {/* 薪酬项设置 */}
                <Card 
                  title="薪酬项设置" 
                  size="small" 
                  className={styles.formCard}
                  extra={
                    <Button 
                      type="link" 
                      icon={<PlusOutlined />}
                      onClick={this.addSalaryItem}
                    >
                      添加薪酬项
                    </Button>
                  }
                >
                  <Table
                    columns={this.salaryColumns}
                    dataSource={salaryItems}
                    pagination={false}
                    size="small"
                    className={styles.salaryTable}
                  />
                </Card>

                {/* 社保公积金设置 */}
                <Card title="社保公积金设置" size="small" className={styles.formCard}>
                  <Row gutter={16} className={styles.socialRow}>
                    <Col span={12}>
                      <div className={styles.formItem}>
                        <label>社保缴纳基数</label>
                        <Select
                          value={form.socialBase}
                          style={{ width: '100%' }}
                          onChange={(value) => this.handleFormChange('socialBase', value)}
                        >
                          <Option value="员工基本工资">员工基本工资</Option>
                          <Option value="员工总工资">员工总工资</Option>
                          <Option value="固定基数">固定基数</Option>
                        </Select>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div className={styles.formItem}>
                        <label>公积金缴纳基数</label>
                        <Select
                          value={form.fundBase}
                          style={{ width: '100%' }}
                          onChange={(value) => this.handleFormChange('fundBase', value)}
                        >
                          <Option value="员工基本工资">员工基本工资</Option>
                          <Option value="员工总工资">员工总工资</Option>
                          <Option value="固定基数">固定基数</Option>
                        </Select>
                      </div>
                    </Col>
                  </Row>
                  
                  <div className={styles.insuranceTable}>
                    <h4>缴纳比例</h4>
                    <Table
                      columns={this.insuranceColumns}
                      dataSource={insuranceRates}
                      pagination={false}
                      size="small"
                    />
                  </div>
                </Card>

                {/* 个税设置 */}
                <Card title="个人所得税设置" size="small" className={styles.formCard}>
                  <Row gutter={16}>
                    <Col span={12}>
                      <div className={styles.formItem}>
                        <label>起征点</label>
                        <Input
                          value={form.taxThreshold}
                          onChange={(e) => this.handleFormChange('taxThreshold', e.target.value)}
                        />
                      </div>
                    </Col>
                    <Col span={12}>
                      <div className={styles.formItem}>
                        <label>专项附加扣除</label>
                        <Select
                          value={form.specialDeduction}
                          style={{ width: '100%' }}
                          onChange={(value) => this.handleFormChange('specialDeduction', value)}
                        >
                          <Option value="自动计算">自动计算</Option>
                          <Option value="手动输入">手动输入</Option>
                          <Option value="不扣除">不扣除</Option>
                        </Select>
                      </div>
                    </Col>
                  </Row>
                </Card>
              </div>
              </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }
}

export default SalaryRuleset;