<template>
  <!-- 气象预警监测表格 -->
  <div class="weather-warning-wrapper">
    <div class="weather-warning-panel">
      <img
        class="clear-icon"
        src="../../../assets/RiskWarning_img/清除icon@2x.png"
        alt=""
        @click="clearFilters"
      />
      <div class="panel-header">
        <div class="header-title">气象预警监测</div>
        <div class="filter-tags">
          <label class="tag">
            <input type="checkbox" v-model="filters.red" />
            <span class="">红色预警</span>
          </label>
          <label class="tag">
            <input type="checkbox" v-model="filters.blue" />
            <span class="">蓝色预警</span>
          </label>
          <label class="tag">
            <input type="checkbox" v-model="filters.orange" />
            <span class="">橙色预警</span>
          </label>
          <label class="tag">
            <input type="checkbox" v-model="filters.yellow" />
            <span class="">黄色预警</span>
          </label>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="loading"
          element-loading-text="加载中..."
          element-loading-background="#1A3E5E"
          :data="filteredData"
          height="100%"
          style="width: 100%; background: transparent"
          :header-cell-style="headerCellStyle"
          :cell-style="cellStyle"
          :row-class-name="rowClassName"
        >
          <el-table-column prop="time" label="预警时间" min-width="vw(140)" />
          <el-table-column prop="type" label="类型" min-width="vw(80)" align="center" />
          <el-table-column label="预警等级" min-width="vw(100)" align="center">
            <template #default="{ row }">
              <div class="warning-level">
                <img
                  :src="
                    row.levelClass === 'red'
                      ? redIcon
                      : row.levelClass === 'blue'
                        ? blueIcon
                        : row.levelClass === 'orange'
                          ? orangeIcon
                          : yellowIcon
                  "
                  alt=""
                />
                <span class="ml_10">{{ row.level }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="district" label="预警区县" min-width="vw(80)" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { request } from '@/utils/request';
import orangeIcon from '../../../assets/RiskWarning_img/橙色@2x.png';
import yellowIcon from '../../../assets/RiskWarning_img/黄色@2x.png';
import redIcon from '../../../assets/RiskWarning_img//红色@2x.png';
import blueIcon from '../../../assets/RiskWarning_img/蓝色@2x.png';

const emit = defineEmits(['clearFilters']);

// 筛选状态
const filters = ref({
  red: false,
  blue: false,
  orange: false,
  yellow: false,
});

// 预警数据
const warningData = ref([]);

// 表格自动滚动相关
const tableRef = ref(null);
const isScrolling = ref(true);
const scrollTimer = ref(null);
const scrollSpeed = 50; // 滚动间隔（毫秒）
const scrollStep = 1; // 每次滚动像素

// 检查是否有筛选条件
const hasFilter = computed(() => {
  return filters.value.red || filters.value.blue || filters.value.orange || filters.value.yellow;
});

// 开始自动滚动
const startAutoScroll = () => {
  if (scrollTimer.value) {
    clearInterval(scrollTimer.value);
  }
  if (!isScrolling.value || hasFilter.value) return;

  const tableBody = document.querySelector(
    '.weather-warning-panel .el-table__body-wrapper .el-scrollbar__wrap'
  );
  if (!tableBody) return;

  scrollTimer.value = setInterval(() => {
    if (tableBody) {
      tableBody.scrollTop += scrollStep;
      // 滚动到底部后回到顶部（使用 >= 判断，并留出一点余量确保准确触发）
      const maxScroll = tableBody.scrollHeight - tableBody.clientHeight;
      if (tableBody.scrollTop >= maxScroll - 2) {
        tableBody.scrollTop = 0;
      }
    }
  }, scrollSpeed);
};

// 停止自动滚动
const stopAutoScroll = () => {
  if (scrollTimer.value) {
    clearInterval(scrollTimer.value);
    scrollTimer.value = null;
  }
};

// 重置滚动到顶部
const resetScrollToTop = () => {
  const tableBody = document.querySelector(
    '.weather-warning-panel .el-table__body-wrapper .el-scrollbar__wrap'
  );
  if (tableBody) {
    tableBody.scrollTop = 0;
  }
};

// 鼠标移入停止滚动
const handleMouseEnter = () => {
  stopAutoScroll();
};

// 鼠标移出开始滚动
const handleMouseLeave = () => {
  if (!hasFilter.value) {
    isScrolling.value = true;
    startAutoScroll();
  }
};

// 监听筛选条件变化
watch(hasFilter, newVal => {
  if (newVal) {
    // 有筛选条件时停止滚动并回到顶部
    stopAutoScroll();
    resetScrollToTop();
  } else {
    // 取消筛选后开始滚动
    isScrolling.value = true;
    nextTick(() => {
      startAutoScroll();
    });
  }
});

// 加载状态
const loading = ref(false);
// 获取气象预警数据
const fetchWeatherWarningData = async () => {
  loading.value = true;
  try {
    const res = await request({
      url: '/snow-ops-platform/weather-warning/affected-count/_by_weather',
      method: 'GET',
      params: {
        offset: 0,
        limit: 100000,
      },
    });
    console.log('气象预警数据:', res);
    if (res.code === '00000' && res.data) {
      // 映射数据格式
      warningData.value = res.data.data.map(item => ({
        time: item.startTime || '',
        type: item.weatherType || '',
        level: item.riskLeve || '',
        levelClass: getLevelClass(item.riskLeve || ''),
        district: item.countyName || '',
      }));
    } else {
      warningData.value = [];
    }
    loading.value = false;
    nextTick(() => {
      startAutoScroll();
      // 添加鼠标事件监听
      const tableContainer = document.querySelector('.weather-warning-panel .table-container');
      if (tableContainer) {
        tableContainer.addEventListener('mouseenter', handleMouseEnter);
        tableContainer.addEventListener('mouseleave', handleMouseLeave);
      }
    });
  } catch (error) {
    console.error('获取气象预警数据失败:', error);
    warningData.value = [];
    loading.value = false;
  }
};

// 根据预警等级获取对应的class
const getLevelClass = level => {
  if (level.includes('红')) return 'red';
  if (level.includes('橙')) return 'orange';
  if (level.includes('黄')) return 'yellow';
  if (level.includes('蓝')) return 'blue';
  return '';
};

// 组件挂载时获取数据
onMounted(() => {
  // 获取气象预警数据
  console.log('获取气象预警数据');
  fetchWeatherWarningData();
});

onUnmounted(() => {
  stopAutoScroll();
  const tableContainer = document.querySelector('.weather-warning-panel .table-container');
  if (tableContainer) {
    tableContainer.removeEventListener('mouseenter', handleMouseEnter);
    tableContainer.removeEventListener('mouseleave', handleMouseLeave);
  }
});

// 过滤后的数据
const filteredData = computed(() => {
  const hasFilter =
    filters.value.red || filters.value.blue || filters.value.orange || filters.value.yellow;
  if (!hasFilter) return warningData.value;

  return warningData.value.filter(item => {
    if (filters.value.red && item.levelClass === 'red') return true;
    if (filters.value.blue && item.levelClass === 'blue') return true;
    if (filters.value.orange && item.levelClass === 'orange') return true;
    if (filters.value.yellow && item.levelClass === 'yellow') return true;
    return false;
  });
});

// el-table 样式
const headerCellStyle = () => ({
  background: '#17466F',
  color: 'rgba(255, 255, 255, 0.6)',
});

const cellStyle = () => ({
  background: '#142E49',
  color: 'rgba(255, 255, 255, 0.9)',
  borderBottom: '1px solid rgba(64, 169, 255, 0.1)',
  padding: '5px 5px',
});

const rowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};

// 清除筛选条件
const clearFilters = () => {
  console.log('清除筛选条件');
  filters.value = {
    red: false,
    blue: false,
    orange: false,
    yellow: false,
  };
  // 触发事件通知父组件
  emit('clearFilters');
};

// 暴露方法给父组件
const setWarningData = data => {
  warningData.value = data;
};

defineExpose({
  clearFilters,
  setWarningData,
});
</script>

<style lang="scss" scoped>
@function vw($px) {
  @return calc($px / 1920 * 100vw);
}

.weather-warning-wrapper {
  position: fixed;
  bottom: vw(0);
  left: 52%;
  transform: translateX(-50%);
  z-index: 2;
}

.weather-warning-panel {
  width: vw(900);
  // background: url('../../../assets/RiskWarning_img/弹窗背景@2x.png') no-repeat center center;
  // background-size: 100% 100%;
  padding: vw(15);
  position: relative;

  .clear-icon {
    position: absolute;
    top: vw(-40);
    right: vw(15);
    width: vw(50);
    height: vw(50);
    cursor: pointer;
    z-index: 10;
  }

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-image: url('../../../assets/RiskWarning_img/二级标题栏bg1@2x.png');
    background-size: 100% 100%;
    background-position: left top;
    padding: vw(15);

    .header-title {
      font-size: vw(18);
      font-weight: 500;
      color: #fff;
    }

    .filter-tags {
      display: flex;
      gap: vw(10);

      .tag {
        display: flex;
        align-items: center;
        gap: vw(5);
        cursor: pointer;
        font-size: vw(14);
        color: rgba(255, 255, 255, 0.8);

        input[type='checkbox'] {
          width: vw(14);
          height: vw(14);
          cursor: pointer;
        }
      }
    }
  }

  .table-container {
    height: vw(130);
    overflow: hidden;

    :deep(.el-table) {
      background: transparent;

      .el-table__header-wrapper {
        th {
          background: #17466f;
          color: rgba(255, 255, 255, 0.6);
          font-weight: normal;
          border-bottom: 1px solid rgba(64, 169, 255, 0.2);
        }
      }

      .el-table__body-wrapper {
        background: transparent;

        tr {
          background: transparent;

          td {
            background: #142e49;
            color: rgba(255, 255, 255, 0.9);
            border-bottom: 1px solid rgba(64, 169, 255, 0.1);
          }

          &.even-row {
            td {
              background: #142e49;
            }
          }

          &.odd-row {
            td {
              background: #1a3a5c;
            }
          }

          &:hover {
            td {
              background: rgba(64, 169, 255, 0.2);
            }
          }
        }
      }
    }
  }
}

.warning-level {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: vw(5);

  img {
    width: vw(20);
    height: vw(20);
  }
}

.ml_10 {
  margin-left: vw(10);
}
:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0%;
}
:deep(.el-scrollbar__wrap--hidden-default) {
  background: #142e49;
}
:deep(.el-table .cell) {
  text-align: center;
}
:deep(.el-table:not(.el-table--border) .el-table__cell) {
  font-size: vw(14);
  padding: 0;
}
:deep(.el-table .cell) {
  font-size: vw(16);
}
</style>
