import React, { useState, useEffect } from 'react';
import { Table, Card, Row, Col, Tag, Button, Statistic, Select, Input, Space } from 'antd';
import { SearchOutlined, CheckOutlined, ExclamationCircleOutlined, FileTextOutlined, BarChartOutlined, BellOutlined, AlertOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import styles from './SpecialOperationPermit.less';

const { Option } = Select;
const { Column } = Table;

// 模拟数据 - 统计卡片数据
const statsData = [
  {
    title: '作业总数',
    count: 126,
    icon: <FileTextOutlined />,
    status: '正常',
    color: '#52c41a'
  },
  {
    title: '技能合格率',
    count: '23%',
    icon: <CheckOutlined />,
    status: '待提升',
    color: '#ff7875'
  },
  {
    title: '作业完成率',
    count: '67%',
    icon: <BarChartOutlined />,
    status: '正常',
    color: '#52c41a'
  },
  {
    title: '风险防控数',
    count: 16,
    icon: <BellOutlined />,
    status: '较上月持平',
    color: '#1890ff'
  }
];

// 模拟数据 - 趋势分析图表
const trendAnalysisData = {
  title: {
    text: '趋势分析',
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
  },
  legend: {
    data: ['技能合格率', '作业完成率', '风险防控数'],
    bottom: 0,
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['10-01', '10-02', '10-03', '10-04', '10-05', '10-06', '10-07'],
  },
  yAxis: {
    type: 'value',
    max: 100,
  },
  series: [
    {
      name: '技能合格率',
      type: 'line',
      smooth: true,
      showSymbol: false,
      data: [25, 23, 28, 26, 30, 23, 25],
      itemStyle: { color: '#ff7a75' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(255, 122, 117, 0.8)'
          }, {
            offset: 1, color: 'rgba(255, 122, 117, 0.1)'
          }]
        }
      }
    },
    {
      name: '作业完成率',
      type: 'line',
      smooth: true,
      showSymbol: false,
      data: [65, 68, 70, 65, 62, 67, 69],
      itemStyle: { color: '#9254de' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(146, 84, 222, 0.8)'
          }, {
            offset: 1, color: 'rgba(146, 84, 222, 0.1)'
          }]
        }
      }
    },
    {
      name: '风险防控数',
      type: 'line',
      smooth: true,
      showSymbol: false,
      data: [15, 18, 16, 14, 17, 16, 19],
      itemStyle: { color: '#40a9ff' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 169, 255, 0.8)'
          }, {
            offset: 1, color: 'rgba(64, 169, 255, 0.1)'
          }]
        }
      }
    }
  ],
};

// 模拟数据 - 作业类型分布图表
const operationTypeData = {
  title: {
    text: '作业类型分布',
    left: 'center',
  },
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: ['动火作业', '高处作业', '有限空间作业', '临时用电', '断路作业'],
  },
  series: [
    {
      name: '作业类型',
      type: 'pie',
      radius: '60%',
      data: [
        {
          value: 35,
          name: '动火作业',
          itemStyle: { color: '#1890ff' }
        },
        {
          value: 25,
          name: '高处作业',
          itemStyle: { color: '#52c41a' }
        },
        {
          value: 20,
          name: '有限空间作业',
          itemStyle: { color: '#faad14' }
        },
        {
          value: 15,
          name: '临时用电',
          itemStyle: { color: '#f5222d' }
        },
        {
          value: 5,
          name: '断路作业',
          itemStyle: { color: '#722ed1' }
        }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
    },
  ],
};

// 模拟数据 - 作业列表数据
const operationListData = [
  {
    key: '1',
    operationType: '动火作业',
    operationNo: 'DH-20230906-002',
    applicant: '张小龙',
    location: '2号车间',
    startTime: '2025-09-03 03:23:12',
    warningDept: '生产一部',
    warningType: '气体浓度超标',
    riskLevel: '高风险',
    status: '进行中',
  },
  {
    key: '2',
    operationType: '高处作业',
    operationNo: 'GC-20230906-002',
    applicant: '李小龙',
    location: '2号车间',
    startTime: '2025-09-03 03:23:12',
    warningDept: '生产一部',
    warningType: '气体浓度超标',
    riskLevel: '较高风险',
    status: '未开始',
  },
  {
    key: '3',
    operationType: '有限空间作业',
    operationNo: 'YX-20230906-002',
    applicant: '张小虎',
    location: '2号车间',
    startTime: '2025-09-03 03:23:12',
    warningDept: '生产一部',
    warningType: '气体浓度超标',
    riskLevel: '中风险',
    status: '未开始',
  },
  {
    key: '4',
    operationType: '临时用电',
    operationNo: 'LS-20230906-002',
    applicant: '张小龙',
    location: '2号车间',
    startTime: '2025-09-03 03:23:12',
    warningDept: '生产一部',
    warningType: '气体浓度超标',
    riskLevel: '低风险',
    status: '进行中',
  },
  {
    key: '5',
    operationType: '动火作业',
    operationNo: 'DH-20230906-002',
    applicant: '张小龙',
    location: '2号车间',
    startTime: '2025-09-03 03:23:12',
    warningDept: '生产一部',
    warningType: '气体浓度超标',
    riskLevel: '高风险',
    status: '进行中',
  },
];

// 状态标签渲染
const renderStatusTag = (status) => {
  switch (status) {
    case '进行中':
      return <Tag color="blue">{status}</Tag>;
    case '未开始':
      return <Tag color="default">{status}</Tag>;
    case '已完成':
      return <Tag color="green">{status}</Tag>;
    case '已暂停':
      return <Tag color="orange">{status}</Tag>;
    default:
      return <Tag>{status}</Tag>;
  }
};

// 风险等级标签渲染
const renderRiskLevelTag = (level) => {
  switch (level) {
    case '高风险':
      return <Tag color="red">{level}</Tag>;
    case '较高风险':
      return <Tag color="orange">{level}</Tag>;
    case '中风险':
      return <Tag color="yellow">{level}</Tag>;
    case '低风险':
      return <Tag color="green">{level}</Tag>;
    default:
      return <Tag>{level}</Tag>;
  }
};

const SpecialOperationPermit = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [filteredData, setFilteredData] = useState(operationListData);

  // 搜索处理
  const handleSearch = (value) => {
    setSearchText(value);
    const filtered = operationListData.filter(item => 
      item.operationNo.includes(value) || 
      item.applicant.includes(value) || 
      item.location.includes(value)
    );
    setFilteredData(filtered);
    setCurrentPage(1);
  };

  // 处理操作按钮
  const handleViewDetails = (record) => {
    // 查看详情逻辑
    console.log('查看详情:', record);
  };

  const handleApprove = (record) => {
    // 审批逻辑
    console.log('审批:', record);
  };

  return (
    <div className={styles.container}>
      {/* 顶部统计卡片 */}
      <Row gutter={16} className={styles.statsRow}>
        {statsData.map((stat, index) => (
          <Col key={index} xs={24} sm={12} md={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statIcon}>
                  {React.cloneElement(stat.icon, { style: { color: stat.color } })}
                </div>
                <div className={styles.statInfo}>
                  <div className={styles.statTitle}>{stat.title}</div>
                  <div className={styles.statCount}>{stat.count}</div>
                  <div className={styles.statStatus} style={{ color: stat.color }}>{stat.status}</div>
                </div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 中间图表区域 */}
      <Row gutter={16} className={styles.chartRow}>
        {/* 监控预警 */}
        <Col xs={24} md={6} lg={6}>
          <Card title="监控预警" className={styles.chartCard}>
            <div className={styles.alarmList}>
              <div className={styles.alarmItem}>
                <div className={styles.alarmIcon} style={{ backgroundColor: '#FF4D4F' }}>
                  <AlertOutlined style={{ color: '#fff' }} />
                </div>
                <div className={styles.alarmInfo}>
                  <div className={styles.alarmTitle}>高风险气体超标</div>
                  <div className={styles.alarmDesc}>测试气体浓度超出安全标准值25.0%</div>
                  <div className={styles.alarmTime}>5分钟前</div>
                </div>
              </div>
              
              <div className={styles.alarmItem}>
                <div className={styles.alarmIcon} style={{ backgroundColor: '#FF7A45' }}>
                  <AlertOutlined style={{ color: '#fff' }} />
                </div>
                <div className={styles.alarmInfo}>
                  <div className={styles.alarmTitle}>高温作业防护缺失</div>
                  <div className={styles.alarmDesc}>作业人员未按规定佩戴防护装备</div>
                  <div className={styles.alarmTime}>30分钟前</div>
                </div>
              </div>
              
              <div className={styles.alarmItem}>
                <div className={styles.alarmIcon} style={{ backgroundColor: '#FFC53D' }}>
                  <AlertOutlined style={{ color: '#fff' }} />
                </div>
                <div className={styles.alarmInfo}>
                  <div className={styles.alarmTitle}>受限空间超时</div>
                  <div className={styles.alarmDesc}>作业人员在受限空间内停留超过规定时间</div>
                  <div className={styles.alarmTime}>60分钟前</div>
                </div>
              </div>
              
              <div className={styles.alarmItem}>
                <div className={styles.alarmIcon} style={{ backgroundColor: '#1890FF' }}>
                  <AlertOutlined style={{ color: '#fff' }} />
                </div>
                <div className={styles.alarmInfo}>
                  <div className={styles.alarmTitle}>受限空间作业超时</div>
                  <div className={styles.alarmDesc}>受限空间作业已超规定时间30分钟</div>
                  <div className={styles.alarmTime}>90分钟前</div>
                </div>
              </div>
            </div>
          </Card>
        </Col>
        
        {/* 趋势分析图表 */}
        <Col xs={24} md={18} lg={8}>
          <Card title="趋势分析" className={styles.chartCard}>
            <ReactECharts option={trendAnalysisData} className={styles.chart} />
          </Card>
        </Col>
        {/* 作业类型分布图表 */}
        <Col xs={24} md={24} lg={10}>
          <Card title="作业类型分布" className={styles.chartCard}>
            <ReactECharts option={operationTypeData} className={styles.chart} />
          </Card>
        </Col>
      </Row>

      {/* 作业列表区域 */}
      <Card title="作业管理列表" className={styles.tableCard}>
        {/* 搜索和筛选 */}
        <div className={styles.searchFilter}>
          <Space>
            <Input
              placeholder="搜索作业编号、申请人、作业地点..."
              prefix={<SearchOutlined />}
              allowClear
              style={{ width: 300 }}
              onChange={(e) => handleSearch(e.target.value)}
            />
            <Select placeholder="作业类型" style={{ width: 120 }}>
              <Option value="all">全部</Option>
              <Option value="dh">动火作业</Option>
              <Option value="gc">高处作业</Option>
              <Option value="yx">有限空间作业</Option>
              <Option value="ls">临时用电</Option>
              <Option value="dl">断路作业</Option>
            </Select>
            <Select placeholder="状态" style={{ width: 100 }}>
              <Option value="all">全部</Option>
              <Option value="progress">进行中</Option>
              <Option value="not-started">未开始</Option>
              <Option value="completed">已完成</Option>
              <Option value="paused">已暂停</Option>
            </Select>
            <Select placeholder="风险等级" style={{ width: 100 }}>
              <Option value="all">全部</Option>
              <Option value="high">高风险</Option>
              <Option value="medium-high">较高风险</Option>
              <Option value="medium">中风险</Option>
              <Option value="low">低风险</Option>
            </Select>
          </Space>
        </div>

        {/* 作业列表表格 */}
        <Table
          dataSource={filteredData}
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: filteredData.length,
            showSizeChanger: true,
            showTotal: (total, range) => `共 ${total} 条 ${range[0]}-${range[1]}`
          }}
          rowKey="key"
          size="small"
          className={styles.operationTable}
        >
          <Column title="作业类型" dataIndex="operationType" key="operationType" width={100} />
          <Column title="作业编号" dataIndex="operationNo" key="operationNo" width={150} />
          <Column title="申请人" dataIndex="applicant" key="applicant" width={80} />
          <Column title="作业地点" dataIndex="location" key="location" width={100} />
          <Column title="开始时间" dataIndex="startTime" key="startTime" width={160} />
          <Column title="预警部门" dataIndex="warningDept" key="warningDept" width={100} />
          <Column title="预警类型" dataIndex="warningType" key="warningType" width={120} />
          <Column 
            title="风险等级" 
            dataIndex="riskLevel" 
            key="riskLevel" 
            width={80}
            render={(text) => renderRiskLevelTag(text)}
          />
          <Column 
            title="状态" 
            dataIndex="status" 
            key="status" 
            width={80}
            render={(text) => renderStatusTag(text)}
          />
          <Column 
            title="操作" 
            key="action" 
            width={120}
            fixed="right"
            render={(text, record) => (
              <Space size="middle">
                <Button size="small" type="link" onClick={() => handleViewDetails(record)}>查看</Button>
                <Button size="small" type="link" onClick={() => handleApprove(record)}>审批</Button>
              </Space>
            )}
          />
        </Table>
      </Card>
    </div>
  );
};

export default SpecialOperationPermit;