<template>
  <div class="warning-box">
    <LDBTitleBox title="报警信息" align="right" />
    <div class="alarm-content-container">
      <el-row>
        <el-col :span="10" :offset="2" class="alarm-header-time">报警时间</el-col>
        <el-col :span="12" class="alarm-header-content">报警内容</el-col>
      </el-row>
      <div class="alarm-list-container" :class="{ 'auto-scroll': effectiveAlarmList.length > 5 }"
        @mouseenter="pauseScroll" @mouseleave="resumeScroll">

        <!-- <div v-if="error" class="alarm-error">{{ error }}</div> -->
        <div class="alarm-list-wrapper" :style="scrollAnimationStyle">
          <div v-if="effectiveAlarmList.length === 0" class="alarm-loading">暂无报警数据</div>
          <el-row v-for="(alarm, index) in effectiveAlarmList" :key="index" class="alarm-item">
            <el-col :span="10" :offset="2" class="alarm-time">{{ alarm.time }}</el-col>
            <el-col :span="12" class="alarm-content">{{ alarm.content }}</el-col>
          </el-row>
          <template v-if="effectiveAlarmList.length > 5">
            <el-row v-for="(alarm, index) in effectiveAlarmList" :key="`duplicate-${index}`" class="alarm-item">
              <el-col :span="10" :offset="2" class="alarm-time">{{ alarm.time }}</el-col>
              <el-col :span="12" class="alarm-content">{{ alarm.content }}</el-col>
            </el-row>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue'
import { CreateData, ExecDatabase, type ParameterTuple } from '../../utils/webApiCall'
import type { AlarmInfo } from '@/types'

defineOptions({
  name: 'Warning',
})

interface Props {
  alarmList?: AlarmInfo[]
}

const props = withDefaults(defineProps<Props>(), {
  alarmList: () => [],
})

const alarmList = ref<AlarmInfo[]>([])
const loading = ref(false)
const error = ref('')

const scrollInterval = ref<ReturnType<typeof setInterval> | null>(null)
const refreshInterval = ref<ReturnType<typeof setInterval> | null>(null)
const isScrollingPaused = ref(false)
const scrollPosition = ref(0)
const scrollAnimationStyle = ref({})

const effectiveAlarmList = computed(() => {
  return alarmList.value.length > 0 ? alarmList.value : props.alarmList
})

const loadAlarmData = async (): Promise<void> => {
  try {
    loading.value = true
    error.value = ''
    const deviceCode = window.dt_Config?.mqttTopic?.replace('SCADAMain/', '')

    const param: ParameterTuple[] = []
    param.push(['TableName', '报警_记录_历史'])
    param.push(['PageNumber', 1])
    param.push(['PageSize', 10])
    param.push(['FieldsToSelect', '报警内容, 开始时间, 报警代码'])
    param.push(['WhereConditions', `工位号 = '${deviceCode}'`])
    param.push(['SortField', '开始时间'])
    param.push(['SortDirection', 'DESC'])
    param.push(['GroupByFields', null])

    const requestData = CreateData('11', param)
    const response = await ExecDatabase(requestData)

    if (response && response.data) {
      if (Array.isArray(response.data) && response.data.length > 0) {
        if (response.data[0].hasOwnProperty('result')) {
          error.value = '数据加载失败'
        } else {
          processAlarmData(response.data)
        }
      }
    } else {
      throw new Error('响应数据格式不正确')
    }
  } catch (err: any) {
    error.value = `数据加载失败: ${err.message}`
  } finally {
    loading.value = false
  }
}

//启动定时刷新
const startRefreshTimer = () => {
  const interval = window.dt_Config?.WarningRefreshInterval
  console.log('报警定时刷新间隔:', interval)
  stopRefreshTimer()
  refreshInterval.value = setInterval(() => {
    loadAlarmData()
  }, interval)
}
// 停止定时刷新
const stopRefreshTimer = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
    refreshInterval.value = null
  }
}
const processAlarmData = (data: any[]) => {
  const processedAlarms: Array<AlarmInfo & { originalTime: string }> = []

  data.forEach((item) => {
    const alarmTime = item.开始时间 || new Date().toISOString()
    const alarmContent = item.报警内容 || '未知报警'
    const formattedTime = formatAlarmTime(alarmTime)

    processedAlarms.push({
      time: formattedTime,
      content: alarmContent,
      originalTime: alarmTime,
    } as AlarmInfo & { originalTime: string })
  })

  processedAlarms.sort(
    (a, b) => new Date(b.originalTime).getTime() - new Date(a.originalTime).getTime()
  )

  alarmList.value = processedAlarms.slice(0, 20)

  nextTick(() => {
    updateScrollDisplay()
  })
}

const updateScrollDisplay = () => {
  scrollPosition.value = 0
  updateScrollAnimation()

  if (effectiveAlarmList.value.length > 5) {
    startAutoScroll()
  } else {
    stopAutoScroll()
  }
}

const formatAlarmTime = (timeString: string): string => {
  try {
    const date = new Date(timeString)
    if (isNaN(date.getTime())) return timeString

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}/${month}/${day} ${hours}:${minutes}`
  } catch {
    return timeString
  }
}

const startAutoScroll = () => {
  if (effectiveAlarmList.value.length <= 5) {
    return
  }

  stopAutoScroll()

  scrollInterval.value = setInterval(() => {
    if (!isScrollingPaused.value) {
      scrollPosition.value += 0.5
      updateScrollAnimation()

      const itemHeight = 30
      const totalHeight = effectiveAlarmList.value.length * itemHeight
      if (scrollPosition.value >= totalHeight) {
        scrollPosition.value = 0
      }
    }
  }, 50)
}

const stopAutoScroll = () => {
  if (scrollInterval.value) {
    clearInterval(scrollInterval.value)
    scrollInterval.value = null
  }
}

const updateScrollAnimation = () => {
  scrollAnimationStyle.value = {
    transform: `translateY(-${scrollPosition.value}px)`,
    transition: isScrollingPaused.value ? 'none' : 'transform 0.3s ease',
  }
}

const pauseScroll = () => {
  if (effectiveAlarmList.value.length > 5) {
    isScrollingPaused.value = true
  }
}

const resumeScroll = () => {
  if (effectiveAlarmList.value.length > 5) {
    isScrollingPaused.value = false
  }
}

watch(
  effectiveAlarmList,
  (newList) => {
    if (newList.length > 5) {
      startAutoScroll()
    } else {
      stopAutoScroll()
      scrollPosition.value = 0
      updateScrollAnimation()
    }
  },
  { deep: true }
)

onMounted(async () => {
  await nextTick()

  setTimeout(async () => {
    await loadAlarmData()
    startRefreshTimer() // 启动定时刷新
  }, 300)
})

onUnmounted(() => {
  stopAutoScroll()
  stopRefreshTimer() // 组件销毁时停止定时刷新
})

defineExpose({
  loadAlarmData,
})
</script>

<style scoped>
.warning-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.alarm-content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0 10px 10px 0px;
  min-height: 0;
}

.alarm-list-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 0;
}

.alarm-list-container::-webkit-scrollbar {
  display: none;
}

.alarm-list-container {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.alarm-list-wrapper {
  position: absolute;
  width: 100%;
}

.auto-scroll .alarm-list-wrapper {
  animation: scroll-animation 15s linear infinite;
}

.auto-scroll .alarm-list-wrapper:hover {
  animation-play-state: paused;
}

.alarm-item {
  height: 25px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.alarm-item:hover {
  background-color: rgba(0, 112, 192, 0.2);
}

.alarm-time {
  font-size: 12px;
  color: #F56C6C;

  line-height: 25px;
}

.alarm-content {
  font-size: 12px;
  color: #F56C6C;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 25px;
}

.alarm-header-time,
.alarm-header-content {
  font-size: 14px;
  color: #70d4ed;
  padding-bottom: 5px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.alarm-loading,
.alarm-error {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #ffffff;
  font-size: 14px;
  text-align: center;
  padding: 0 10px;
}

.alarm-error {
  color: #ff6b6b;
}

@keyframes scroll-animation {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-50%);
  }
}

/* 确保标题栏有固定高度 */
.warning-box ::v-deep(.ldb3-title-box) {
  flex-shrink: 0;
}
</style>
<script lang="ts">
export default {
  name: 'Warning',
}
</script>
