<template>
  <div class="data-table" :style="{ width: width, height: height }">
    <el-table
      ref="tableRef"
      :data="dataRef"
      :show-header="showHeader"
      :border="border"
      class="custom-table"
      @mouseenter.native="handleMouseEnter"
      @mouseleave.native="handleMouseLeave"
    >
      <el-table-column
        v-for="col in columns"
        :key="col.prop"
        :prop="col.prop"
        :label="col.label"
        :width="col.width"
        :align="col.align || 'center'"
      >
        <template #default="scope" v-if="col.prop === 'riskLevel'">
          <div class="risk-icon" :class="scope.row.riskLevel"></div>
        </template>
        <template #default="scope" v-else-if="col.date">
          <div class="table-cell">{{ scope.row[col.prop] }}</div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'

interface Column {
  prop: string
  label: string
  width?: number
  date?: boolean
  align?: string
}

const props = withDefaults(
  defineProps<{
    columns: Column[]
    data: any[]
    autoScroll?: boolean
    showHeader?: boolean
    height?: string
    width?: string
    border?: boolean
    scrollThreshold?: number
  }>(),
  {
    autoScroll: false,
    showHeader: true,
    height: '100%',
    width: '100%',
    border: false,
    scrollThreshold: 5,
  }
)

const tableRef = ref<any>(null)
const scrollId = ref<number | null>(null)
const scrollSpeed = 0.5 // 滚动速度，每帧滚动的像素数
const dataRef = ref<any[]>([]) // 用于显示的数据
const originalData = ref<any[]>([]) // 原始数据副本
const isAutoScrolling = ref(false) // 是否正在自动滚动

// 初始化数据
const init = () => {
  originalData.value = [...props.data]
  if (props.autoScroll && props.data.length > props.scrollThreshold) {
    // 自动滚动时使用双倍数据
    dataRef.value = [...props.data, ...props.data]
    isAutoScrolling.value = true
  } else {
    dataRef.value = [...props.data]
    isAutoScrolling.value = false
  }

  const tableBody = tableRef.value?.$el.querySelector('.el-scrollbar__wrap')
  if (tableBody) {
    tableBody.scrollTop = 0
  }

  // 初始化时如果需要自动滚动，启动滚动
  if (props.autoScroll && props.data.length > props.scrollThreshold) {
    startScroll()
  }
}

// 监听数据变化
watch(
  () => props.data,
  () => {
    init()
  },
  { deep: true }
)

// 监听自动滚动状态变化
watch(
  () => props.autoScroll,
  (newVal) => {
    if (newVal && props.data.length > props.scrollThreshold) {
      isAutoScrolling.value = true
      dataRef.value = [...props.data, ...props.data]
      startScroll()
      const tableBody = tableRef.value?.$el.querySelector('.el-scrollbar__wrap')
      if (tableBody) {
        tableBody.scrollTop = 0
      }
    } else {
      isAutoScrolling.value = false
      // 停止滚动时恢复原始数据
      dataRef.value = [...originalData.value]
      const tableBody = tableRef.value?.$el.querySelector('.el-scrollbar__wrap')
      if (tableBody) {
        tableBody.scrollTop = 0
      }
    }
  }
)

const startScroll = () => {
  if (!props.autoScroll || props.data.length <= props.scrollThreshold) return

  const animateScroll = () => {
    if (!isAutoScrolling.value) return

    const tableBody = tableRef.value?.$el.querySelector('.el-scrollbar__wrap')
    if (tableBody) {
      // 平滑滚动，每次滚动指定像素数
      tableBody.scrollTop += scrollSpeed

      // 当滚动到一半（第二份数据开始）时，重置到顶部
      if (tableBody.scrollTop >= tableBody.scrollHeight / 2) {
        tableBody.scrollTop = 0
      }
    }
    scrollId.value = window.requestAnimationFrame(animateScroll)
  }

  scrollId.value = window.requestAnimationFrame(animateScroll)
}

const stopScroll = () => {
  if (scrollId.value) {
    window.cancelAnimationFrame(scrollId.value)
    scrollId.value = null
  }
  // dataRef.value = [...originalData.value]
}

const handleMouseEnter = () => {
  stopScroll()
}

const handleMouseLeave = () => {
  if (props.autoScroll && props.data.length > props.scrollThreshold) {
    isAutoScrolling.value = true
    // dataRef.value = [...props.data, ...props.data]
    startScroll()
  }
}

onMounted(() => {
  init()
})

onUnmounted(() => {
  stopScroll()
})
</script>

<style lang="scss" scoped>
.data-table {
  padding: 0 16px 30px;
  overflow: hidden;
  box-sizing: border-box;

  .custom-table {
    height: 100%;
    background-color: transparent;

    :deep(.el-table__header-wrapper tr) {
      background-color: transparent;
    }

    :deep(.el-table__header-wrapper th) {
      padding: 10px 0;
      background-color: rgba(0, 255, 230, 0.15) !important;
    }

    :deep(.el-table__header th .cell) {
      padding: 0 6px;
      color: #00d6c0;
      font-size: 24px;
      font-weight: normal;
      line-height: 24px;
      text-align: center;
    }

    :deep(.el-table__body-wrapper) {
      background-color: rgba(255, 255, 255, 0.01);
    }

    :deep(.el-table__body-wrapper tr) {
      padding: 4px 0;
      background-color: rgba(255, 255, 255, 0.01) !important;
    }

    :deep(.el-table__body-wrapper td) {
      padding: 8px 0;
      background-color: rgba(255, 255, 255, 0.01) !important;

      .cell {
        padding: 0 8px;
        color: #02bcad;
        font-size: 24px;
        line-height: 30px;
        // text-align: center;
      }

      .table-cell {
        font-size: 20px;
        line-height: 26px;
        // text-align: center;
      }
    }

    :deep(.el-table__body .el-table__row) {
      background-color: rgba(255, 255, 255, 0.01) !important;

      &:hover > td {
        background-color: rgba(0, 255, 230, 0.08) !important;
      }
    }

    :deep(.el-table__row td) {
      border-color: #0c4044 !important;
    }

    :deep(.el-table__header th) {
      border-color: #0c4044 !important;
    }

    :deep(.el-table) {
      border-color: #0c4044 !important;
    }

    :deep(.el-table__empty-text) {
      color: #02bcad;
    }

    .risk-icon {
      width: 38px;
      height: 34px;
      margin: 0 auto;
      background-size: auto;
      background-repeat: no-repeat;
      background-position: center;
    }

    .risk-icon.high {
      background-image: url('@/assets/icons/icon-warning-red.png');
    }

    .risk-icon.medium {
      background-image: url('@/assets/icons/icon-warning-orange.png');
    }

    .risk-icon.low {
      background-image: url('@/assets/icons/icon-warning-orange.png');
    }
  }

  :deep(.el-table--border:after),
  :deep(.el-table--border:before),
  :deep(.el-table--border .el-table__inner-wrapper:after),
  :deep(.el-table__inner-wrapper:before),
  :deep(.el-table__border-left-patch) {
    background-color: #0c4044 !important;
  }
}
</style>
