import React, { useState, useEffect, useRef } from 'react';
import { Button, DatePicker } from "antd";
import { ClockCircleOutlined, EnvironmentOutlined, UserOutlined, CalendarOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
import * as echarts from 'echarts';
import styles from './EmergencyDrill.less';
import { Import } from '../business_hiddentrouble/component/hiddenDangerInspection/hiddenDangerInspection';
import StandardTable from '@/components/StandardTable';
import iconDrill1 from '../../assets/business_Emergency/iconDrill1.svg';
import iconDrill2 from '../../assets/business_Emergency/iconDrill2.jpg';
import iconDrill3 from '../../assets/business_Emergency/iconDrill3.svg';
import iconDrill4 from '../../assets/business_Emergency/iconDrill4.svg';
import iconDrill5 from '../../assets/business_Emergency/iconDrill5.svg';
import iconDrill6 from '../../assets/business_Emergency/iconDrill6.svg';
import iconDrill7 from '../../assets/business_Emergency/iconDrill7.svg';

const EmergencyDrill = () => {
  const [timeType, setTimeType] = useState('month');
  const chartRef = useRef(null);
  const chartInstanceRef = useRef(null);

  // 第三块状态
  const [dateRange, setDateRange] = useState(null);
  const [companyName, setCompanyName] = useState('');
  const [unitName, setUnitName] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 48,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
  });
  const chartRef2 = useRef(null);
  const chartInstanceRef2 = useRef(null);

  useEffect(() => {
    if (!chartRef.current) return;

    // 初始化图表
    if (!chartInstanceRef.current) {
      chartInstanceRef.current = echarts.init(chartRef.current);
    }

    // 模拟数据
    const data = [12, 18, 8, 15, 22, 10, 14, 20, 16, 11, 19, 25];

    const option = {
      grid: {
        left: '3%',
        right: '3%',
        top: '10%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisLabel: {
          color: '#666666',
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: '#E5E5E5',
            type: 'dashed'
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#E5E5E5',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 30,
        interval: 5,
        axisLabel: {
          color: '#666666',
          fontSize: 12
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#E5E5E5',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          data: data,
          type: 'bar',
          barWidth: 23,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#556FEB' },
              { offset: 1, color: '#8DAAF7' }
            ])
          }
        }
      ]
    };

    chartInstanceRef.current.setOption(option);

    // 使用 ResizeObserver 监听容器尺寸变化
    const resizeObserver = new ResizeObserver(() => {
      chartInstanceRef.current?.resize();
    });

    if (chartRef.current) {
      resizeObserver.observe(chartRef.current);
    }

    // 窗口大小变化时重新渲染
    const handleResize = () => {
      chartInstanceRef.current?.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', handleResize);
    };
  }, [timeType]);

  // 组件卸载时销毁图表
  useEffect(() => {
    return () => {
      chartInstanceRef.current?.dispose();
      chartInstanceRef2.current?.dispose();
    };
  }, []);

  // 第二个图表 - 折线图
  useEffect(() => {
    if (!chartRef2.current) return;

    // 初始化图表
    if (!chartInstanceRef2.current) {
      chartInstanceRef2.current = echarts.init(chartRef2.current);
    }

    // 模拟数据
    const plannedData = [12, 15, 10, 18, 20, 16, 14, 22, 19, 17, 21, 23]; // 计划演练
    const actualData = [10, 13, 9, 16, 18, 15, 12, 20, 17, 15, 19, 21]; // 实际完成

    const option = {
      grid: {
        left: '3%',
        right: '3%',
        top: '15%',
        bottom: '3%',
        containLabel: true
      },
      legend: {
        data: ['计划演练', '实际完成'],
        top: '5%',
        right: 'center',
        textStyle: {
          color: '#666666',
          fontSize: 12
        },
        itemWidth: 14,
        itemHeight: 8
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisLabel: {
          color: '#666666',
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: '#E5E5E5',
            type: 'dashed'
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#E5E5E5',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 30,
        interval: 5,
        axisLabel: {
          color: '#666666',
          fontSize: 12
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#E5E5E5',
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '计划演练',
          type: 'line',
          data: plannedData,
          smooth: false,
          lineStyle: {
            color: '#3CC3DF',
            width: 1
          },
          itemStyle: {
            color: '#fff',
            borderColor: '#3CC3DF',
            borderWidth: 1
          },
          symbol: 'circle',
          symbolSize: 6,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(60, 195, 223, 0.4)' },
                { offset: 1, color: 'rgba(60, 195, 223, 0.05)' }
              ]
            }
          }
        },
        {
          name: '实际完成',
          type: 'line',
          data: actualData,
          smooth: false,
          lineStyle: {
            color: '#8979FF',
            width: 1
          },
          itemStyle: {
            color: '#fff',
            borderColor: '#8979FF',
            borderWidth: 1
          },
          symbol: 'circle',
          symbolSize: 6,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(137, 121, 255, 0.4)' },
                { offset: 1, color: 'rgba(137, 121, 255, 0.05)' }
              ]
            }
          }
        }
      ]
    };

    chartInstanceRef2.current.setOption(option);

    // 使用 ResizeObserver 监听容器尺寸变化
    const resizeObserver = new ResizeObserver(() => {
      chartInstanceRef2.current?.resize();
    });

    if (chartRef2.current) {
      resizeObserver.observe(chartRef2.current);
    }

    // 窗口大小变化时重新渲染
    const handleResize = () => {
      chartInstanceRef2.current?.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div className={styles.containerDrill}>
      <div className={styles.block1}>
        <div className={styles.block1_item1}>
          <div className={styles.item1_row1}>
            <div className={styles.row1_left}>
              <div className={styles.colorBlock}></div>
              <span className={styles.title}>预案演练</span>
            </div>
            <Button className={styles.startBtn}>
              <span className={styles.btnIcon}>▶</span>
              <span>开始演练</span>
            </Button>
          </div>

          <div className={styles.item1_row2}>
            <div className={styles.row2_left}>
              <div className={styles.row2_title}>化工事故应急预案</div>
              <div className={styles.row2_version}>最新版本:V3.2</div>
            </div>
            <div className={styles.row2_right}>
              <img src={iconDrill1} alt="drill icon" className={styles.drillIcon} />
            </div>
          </div>

          <div className={styles.item1_row3}>
            <div className={styles.row3_left}>
              <div className={styles.row3_title}>化工事故应急预案</div>
              <div className={styles.row3_version}>最新版本:V3.2</div>
            </div>
            <div className={styles.row3_right}>
              <img src={iconDrill1} alt="drill icon" className={styles.drillIcon} />
            </div>
          </div>

          <div className={styles.item1_row4}>
            <div className={styles.row4_left}>
              <div className={styles.row4_title}>化工事故应急预案</div>
              <div className={styles.row4_version}>最新版本:V3.2</div>
            </div>
            <div className={styles.row4_right}>
              <img src={iconDrill1} alt="drill icon" className={styles.drillIcon} />
            </div>
          </div>
        </div>

        <div className={styles.block1_item2}>
          <div className={styles.item2_row1}>
            <div className={styles.row1_left}>
              <div className={styles.colorBlock}></div>
              <span className={styles.title}>演练数据统计</span>
            </div>
            <div className={styles.timeBtnGroup}>
              <Button
                className={timeType === 'month' ? 'active' : ''}
                onClick={() => setTimeType('month')}
              >
                月
              </Button>
              <Button
                className={timeType === 'season' ? 'active' : ''}
                onClick={() => setTimeType('season')}
              >
                季
              </Button>
              <Button
                className={timeType === 'year' ? 'active' : ''}
                onClick={() => setTimeType('year')}
              >
                年
              </Button>
            </div>
          </div>

          <div ref={chartRef} className={styles.chartContainer}></div>
        </div>

        <div className={styles.block1_item3}>
          <div className={styles.item3_header}>
            <div className={styles.colorBlock}></div>
            <span className={styles.title}>演练完成情况</span>
          </div>

          <div ref={chartRef2} className={styles.chartContainer}></div>
        </div>
      </div>

      <div className={styles.block2}>
        <div className={styles.block2_item1}>
          <div className={styles.block2_item1_header}>
            <div className={styles.colorBlock}></div>
            <div className={styles.title}>协同演练</div>
          </div>

          <div className={styles.block2_item1_content}>
            <div className={styles.drillCard1}>
              <div className={styles.cardHeader}>
                <div className={styles.cardTitle}>生产车间火灾应急演练</div>
                <div className={styles.statusTag}>进行中</div>
              </div>
              <div className={styles.cardInfo}>
                <div className={styles.infoItem}>
                  <ClockCircleOutlined className={styles.infoIcon} />
                  <span>2023-09-12 09:30</span>
                </div>
                <div className={styles.infoItem}>
                  <EnvironmentOutlined className={styles.infoIcon} />
                  <span>第二生产车间</span>
                </div>
                <div className={styles.infoItem}>
                  <UserOutlined className={styles.infoIcon} />
                  <span>参与人数：32人</span>
                </div>
              </div>
              <div className={styles.cardButtons}>
                <Button type="primary" className={styles.joinBtn}>加入演练</Button>
                <Button className={styles.detailBtn}>查看详情</Button>
              </div>
            </div>
            <div className={styles.drillCard2}>
              <div className={styles.cardHeader}>
                <div className={styles.cardTitle}>生产车间火灾应急演练</div>
                <div className={styles.statusTag}>即将开始</div>
              </div>
              <div className={styles.cardInfo}>
                <div className={styles.infoItem}>
                  <ClockCircleOutlined className={styles.infoIcon} />
                  <span>2023-09-12 09:30</span>
                </div>
                <div className={styles.infoItem}>
                  <EnvironmentOutlined className={styles.infoIcon} />
                  <span>第二生产车间</span>
                </div>
                <div className={styles.infoItem}>
                  <UserOutlined className={styles.infoIcon} />
                  <span>参与人数：32人</span>
                </div>
              </div>
              <div className={styles.cardButtons}>
                <Button className={styles.reminderBtn}>设置提醒</Button>
                <Button className={styles.detailBtn}>查看详情</Button>
              </div>
            </div>
            <div className={styles.drillCard3}>
              <div className={styles.cardHeader}>
                <div className={styles.cardTitle}>生产车间火灾应急演练</div>
                <div className={styles.statusTag}>已完成</div>
              </div>
              <div className={styles.cardInfo}>
                <div className={styles.infoItem}>
                  <ClockCircleOutlined className={styles.infoIcon} />
                  <span>2023-09-12 09:30</span>
                </div>
                <div className={styles.infoItem}>
                  <EnvironmentOutlined className={styles.infoIcon} />
                  <span>第二生产车间</span>
                </div>
                <div className={styles.infoItem}>
                  <UserOutlined className={styles.infoIcon} />
                  <span>参与人数：32人</span>
                </div>
              </div>
              <div className={styles.cardButtons}>
                <Button className={styles.reportBtn}>查看报告</Button>
                <Button className={styles.detailBtn}>查看详情</Button>
              </div>
            </div>
            <div className={styles.drillCard4}>
              <div className={styles.cardHeader}>
                <div className={styles.cardTitle}>生产车间火灾应急演练</div>
                <div className={styles.statusTag}>已完成</div>
              </div>
              <div className={styles.cardInfo}>
                <div className={styles.infoItem}>
                  <ClockCircleOutlined className={styles.infoIcon} />
                  <span>2023-09-12 09:30</span>
                </div>
                <div className={styles.infoItem}>
                  <EnvironmentOutlined className={styles.infoIcon} />
                  <span>第二生产车间</span>
                </div>
                <div className={styles.infoItem}>
                  <UserOutlined className={styles.infoIcon} />
                  <span>参与人数：32人</span>
                </div>
              </div>
              <div className={styles.cardButtons}>
                <Button className={styles.reportBtn}>查看报告</Button>
                <Button className={styles.detailBtn}>查看详情</Button>
              </div>
            </div>
          </div>
        </div>

        <div className={styles.block2_item2}>
          <div className={styles.sectionHeader}>
            <div className={styles.headerLine}></div>
            <span className={styles.headerTitle}>现场视频</span>
          </div>

          <div className={styles.videoContainer}>
            {[1, 2, 3].map((item, index) => (
              <div key={index} className={styles.videoCard}>
                <div className={styles.videoThumbnail}>
                  <img src={iconDrill2} alt="视频缩略图" />
                  <div className={styles.videoDuration}>08:45</div>
                </div>
                <div className={styles.videoInfo}>
                  <div className={styles.videoTitle}>生产车间火灾应急演练</div>
                  <div className={styles.videoMeta}>
                    <span className={styles.videoDate}>2023-09-12</span>
                    <div className={styles.videoActions}>
                      <img src={iconDrill3} alt="下载" className={styles.actionIcon} />
                      <img src={iconDrill4} alt="删除" className={styles.actionIcon} />
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className={styles.block3}>
        {/* 第三块内容区域 */}
        <div className={styles.block3Header}>
          <div className={styles.headerLine}></div>
          <div className={styles.headerTitle}>应急演练</div>
        </div>

        <div className={styles.searchBar}>
          <div className={styles.searchLeft}>
            {/* 日期 */}
            <div className={styles.searchItem}>

              <span className={styles.searchLabel}>演练日期:</span>
              <div style={{ display: 'flex', alignItems: 'center', border: '1px  solid #DDDEE6', borderRadius: '2px' }}>
                <div className={styles.datePickerWithIcon}>
                  <img src={iconDrill5} alt="日期icon" className={styles.dateIcon} />
                  <DatePicker
                    showTime={{ format: 'HH:mm' }}
                    format="YYYY-MM-DD HH:mm"
                    value={dateRange ? dateRange[0] : null}
                    onChange={(value) => {
                      setDateRange([value, dateRange ? dateRange[1] : null]);
                    }}
                    placeholder="请输入演练日期"
                    className={styles.datePickerFirst}
                    suffixIcon={null}
                  />
                </div>
                {/* 短线 */}
                <div className={styles.dateSeparator}></div>

                <div className={styles.datePickerWithIcon}>
                  <img src={iconDrill5} alt="日期icon" className={styles.dateIcon} />
                  <DatePicker
                    showTime={{ format: 'HH:mm' }}
                    format="YYYY-MM-DD HH:mm"
                    value={dateRange ? dateRange[1] : null}
                    onChange={(value) => {
                      setDateRange([dateRange ? dateRange[0] : null, value]);
                    }}
                    placeholder="请输入演练日期"
                    className={styles.datePickerFirst}
                    suffixIcon={null}
                  />
                </div>
              </div>
            </div>

            <div className={styles.searchItem}>
              <input
                type="text"
                className={styles.companyInput}
                value={companyName}
                onChange={(e) => setCompanyName(e.target.value)}
                placeholder="请输入演练企业"
              />
            </div>
            <div className={styles.searchItem}>
              <select
                className={styles.unitSelect}
                value={unitName}
                onChange={(e) => setUnitName(e.target.value)}
              >
                <option value="">请选择单位名称</option>
                <option value="unit1">单位1</option>
                <option value="unit2">单位2</option>
              </select>
            </div>
            <Button
              type="primary"
              className={styles.searchButton}
              icon={<img src={iconDrill6} alt="查询icon" style={{ width: 14, height: 14 }} />}
            >
              查询
            </Button>
          </div>
          <Button
            type="primary"
            className={styles.uploadButton}
            icon={<img src={iconDrill7} alt="上传icon" style={{ width: 14, height: 14 }} />}
          >
            上传
          </Button>
        </div>

        <div className={styles.tableContainer}>
          <StandardTable
            rowKey="key"
            data={{
              list: [
                {
                  key: '1',
                  company: '文登市兴文新材料有限公司',
                  drillDate: '2025-10-13 02:59:33',
                  drillType: '化学品泄漏',
                  drillLocation: '西辛南区6号',
                  participants: 40,
                  score: '83分',
                  status: '进行中',
                  improvements: '住厂涉及工艺、设备、原材料非正常操作的...',
                },
                {
                  key: '2',
                  company: '文登市兴文新材料有限公司',
                  drillDate: '2025-10-12 03:10:35',
                  drillType: '火灾',
                  drillLocation: '新胜北大街9号',
                  participants: 38,
                  score: '71分',
                  status: '已安排',
                  improvements: '对电工、焊工、危化品操作员等特殊工种人员...',
                },
                {
                  key: '3',
                  company: '合湾新材科技有限公司',
                  drillDate: '2025-10-10 17:20:18',
                  drillType: '公共安全',
                  drillLocation: '如南南庄',
                  participants: 6,
                  score: '55分',
                  status: '已完成',
                  improvements: '建立高危化学品风险评估机制，对城市生态性...',
                },
              ],
              pagination,
            }}
            columns={[
              {
                title: '企业',
                dataIndex: 'company',
                key: 'company',
                width: 200,
              },
              {
                title: '演练日期',
                dataIndex: 'drillDate',
                key: 'drillDate',
                width: 150,
              },
              {
                title: '演练类型',
                dataIndex: 'drillType',
                key: 'drillType',
                width: 120,
              },
              {
                title: '演练地点',
                dataIndex: 'drillLocation',
                key: 'drillLocation',
                width: 160,
              },
              {
                title: '参加人数',
                dataIndex: 'participants',
                key: 'participants',
                width: 80,
                align: 'center',
              },
              {
                title: '评分',
                dataIndex: 'score',
                key: 'score',
                width: 80,
                align: 'center',
              },
              {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                width: 80,
                align: 'center',
                render: (status) => {
                  let className = styles.statusInProgress;
                  if (status === '已安排') className = styles.statusScheduled;
                  if (status === '已完成') className = styles.statusCompleted;
                  return <span className={className}>{status}</span>;
                },
              },
              {
                title: '存在问题或改进措施',
                dataIndex: 'improvements',
                key: 'improvements',
                ellipsis: true,
              },
              {
                title: '操作',
                key: 'action',
                width: 150,
                align: 'center',
                render: () => (
                  <div className={styles.actionButtons}>
                    <span className={styles.actionLink}>查看</span>
                    <span className={styles.actionLink}>下载</span>
                    <span className={styles.actionLink} style={{ color: '#FF4D4F' }}>删除</span>
                  </div>
                ),
              },
            ]}
            onChange={(newPagination) => setPagination(newPagination)}
          />
        </div>
      </div>
    </div>
  );
};

export default EmergencyDrill;
