<template>
  <div class="bottom-box">
    <LDBTitleBox title="设备运行履历" align="left" style="left: 80px" />
    <div class="bb-chart-container">
      <!-- <div v-show="loading" class="chart-loading">加载中...</div> -->
      <div v-show="!loading && error" class="chart-error">{{ error }}</div>
      <div id="bb-chart" class="bb-chart" v-show="!loading && !error"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { CreateData, ExecDatabase, type ParameterTuple } from '../../utils/webApiCall'

defineOptions({
  name: 'EquipmentRuntimeHistory',
})

// ==================== 数据定义 ====================
// 设备状态配置
const deviceStatusList = ref([
  { value: -1, label: '关机', color: '#909399' },
  { value: 0, label: '待机', color: '#E6A23C' },
  { value: 1, label: '运行', color: '#67C23A' },
  { value: 2, label: '报警', color: '#F56C6C' },
])

const loading = ref(false)
const error = ref('')
const deviceStatusTable = ref<any[]>([])
const chartInitialized = ref(false)

let bbChart: echarts.ECharts | null = null
let refreshTimer: ReturnType<typeof setInterval> | null = null
// ==================== 工具函数 ====================
// 格式化日期时间
const formatDateTime = (date: Date): string => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 启动定时刷新
const startRefreshTimer = () => {
  stopRefreshTimer() // 先清除已存在的定时器
  const interval = window.dt_Config?.equipmentRuntimeHistoryRefreshInterval
  console.log('设备运行履历定时刷新间隔:', interval)
  refreshTimer = setInterval(() => {
    loadDeviceStatusData()
  }, interval) // 每一分钟刷新一次
}

// 停止定时刷新
const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}
// ==================== 数据获取与处理 ====================
// 加载设备状态数据
const loadDeviceStatusData = async (): Promise<void> => {
  try {
    loading.value = true
    error.value = ''

    // 设置时间范围为最近24小时
    const endTime = new Date()
    const startTime = new Date()
    startTime.setDate(startTime.getDate() - 1)

    // 获取设备编码
    const deviceCode = window.dt_Config?.mqttTopic?.replace('SCADAMain/', '') || 'Device001'

    // 构造查询参数
    const param: ParameterTuple[] = [
      ['TableName', '历史_工位设备状态每分钟记录'],
      ['PageNumber', 1],
      ['PageSize', 5000],
      ['FieldsToSelect', '*'],
      [
        'WhereConditions',
        `deviceCode = '${deviceCode}' AND 创建时间 >= '${formatDateTime(startTime)}' AND 创建时间 <= '${formatDateTime(endTime)}'`,
      ],
      ['SortField', '创建时间'],
      ['SortDirection', 'ASC'],
      ['GroupByFields', ''],
    ]

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

    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      deviceStatusTable.value = response.data
      updateBbChart()
    } else {
      setDefaultData()
    }
  } catch (err: any) {
    error.value = `数据加载失败: ${err.message}`
    setDefaultData()
  } finally {
    loading.value = false
  }
}

// 设置默认数据
const setDefaultData = () => {
  const now = new Date()
  const baseTime = now.getTime() - 2 * 60 * 60 * 1000

  deviceStatusTable.value = [
    { 工位号: 'CNCKND_1', 设备状态: -1, 创建时间: new Date(baseTime).toISOString() },
    { 工位号: 'CNCKND_1', 设备状态: 0, 创建时间: new Date(baseTime + 30 * 60 * 1000).toISOString() },
    { 工位号: 'CNCKND_1', 设备状态: 1, 创建时间: new Date(baseTime + 60 * 60 * 1000).toISOString() },
    { 工位号: 'CNCKND_1', 设备状态: 2, 创建时间: new Date(baseTime + 90 * 60 * 1000).toISOString() },
    { 工位号: 'CNCKND_1', 设备状态: 1, 创建时间: new Date(baseTime + 120 * 60 * 1000).toISOString() },
  ]

  updateBbChart()
}

// ==================== 图表操作 ====================
// 初始化图表
const initChart = async () => {
  await nextTick()

  const chartDom = document.getElementById('bb-chart')
  if (!chartDom) {
    error.value = '图表容器不存在'
    return
  }

  // 检查容器尺寸
  if (chartDom.offsetWidth === 0 || chartDom.offsetHeight === 0) {
    setTimeout(initChart, 100)
    return
  }

  try {
    // 清理现有实例
    const existingInstance = echarts.getInstanceByDom(chartDom)
    if (existingInstance) {
      existingInstance.dispose()
    }

    bbChart = echarts.init(chartDom)
    chartInitialized.value = true

    // 窗口调整大小事件
    window.addEventListener('resize', handleResize)

    // 如果有数据，立即更新图表
    if (deviceStatusTable.value.length > 0) {
      updateBbChart()
    }

  } catch (err) {
    error.value = '图表初始化失败'
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (bbChart) {
    bbChart.resize()
  }
}

// 更新设备运行履历图表
const updateBbChart = () => {
  if (!bbChart || !chartInitialized.value) {
    return
  }

  // 设备状态映射
  const statusMap: { [key: number]: { name: string; color: string } } = {
    [-1]: { name: '关机', color: '#909399' },
    [0]: { name: '待机', color: '#E6A23C' },
    [1]: { name: '运行', color: '#67C23A' },
    [2]: { name: '报警', color: '#F56C6C' },
  }

  // 处理数据，按工位号分组并按时间排序
  const groupedData: { [key: string]: any[] } = {}
  deviceStatusTable.value.forEach((item) => {
    const workstation = item.工位号 || '设备'
    if (!groupedData[workstation]) {
      groupedData[workstation] = []
    }
    groupedData[workstation].push(item)
  })

  // 对每组数据按时间排序
  Object.keys(groupedData).forEach((workstation) => {
    groupedData[workstation].sort(
      (a, b) => new Date(a.创建时间).getTime() - new Date(b.创建时间).getTime()
    )
  })

  // 构建图表数据 - 为每个状态创建一个系列
  const seriesData: any[] = []
  const yAxisData: string[] = Object.keys(groupedData)

  // 为每个工位和状态创建数据
  yAxisData.forEach((workstation, yIndex) => {
    const records = groupedData[workstation]

    records.forEach((record, index) => {
      const statusInfo = statusMap[record.设备状态] || { name: '未知', color: 'blue' }

      // 计算结束时间
      let endTime: Date
      if (index === records.length - 1) {
        const startTime = new Date(record.创建时间)
        endTime = new Date(startTime.getTime() + 60000) // 默认1分钟
      } else {
        endTime = new Date(records[index + 1].创建时间)
      }

      const startTime = new Date(record.创建时间)

      // 确保开始时间小于结束时间
      if (startTime.getTime() < endTime.getTime()) {
        seriesData.push({
          name: statusInfo.name,
          value: [
            workstation, // y轴类别
            startTime.getTime(), // 开始时间
            endTime.getTime(), // 结束时间
            statusInfo.name // 状态名称
          ],
          itemStyle: {
            color: statusInfo.color
          }
        })
      }
    })
  })

  // 创建配置选项
  const option = {
    backgroundColor: 'transparent',
    animation: false,
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const data = params.value
        const startTime = new Date(data[1])
        const endTime = new Date(data[2])
        const startStr = `${startTime.getHours().toString().padStart(2, '0')}:${startTime.getMinutes().toString().padStart(2, '0')}`
        const endStr = `${endTime.getHours().toString().padStart(2, '0')}:${endTime.getMinutes().toString().padStart(2, '0')}`
        return `${data[3]}<br/>${data[0]}<br/>${startStr} ~ ${endStr}`
      },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      textStyle: { color: '#fff' },
      borderColor: 'rgba(255, 255, 255, 0.3)',
      borderWidth: 1,
      // 防止tooltip超出图表
      confine: true,
      position: (point: number[], params: any, dom: any, rect: any, size: any) => {
        // 自定义位置，确保tooltip在图表区域内
        let x = point[0]
        let y = point[1]

        // 如果tooltip太靠右，向左偏移
        if (x > size.viewSize[0] * 0.7) {
          x = x - size.contentSize[0] - 10
        }

        // 如果tooltip太靠下，向上偏移
        if (y > size.viewSize[1] * 0.7) {
          y = y - size.contentSize[1] - 10
        }

        return [x, y]
      }
    },
    grid: {
      left: '3%',
      right: '5%', // 为图例留出空间
      bottom: '10%',
      top: '10%',
      containLabel: true
    },

    xAxis: {
      type: 'time',
      axisLine: { lineStyle: { color: '#ffffff' } },
      axisLabel: {
        color: '#ffffff',
        fontSize: 10,
        formatter: (value: number) => {
          const date = new Date(value)
          return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
        }
      },
      splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } }
    },
    yAxis: {
      type: 'category',
      data: yAxisData,
      axisLine: { lineStyle: { color: '#ffffff' } },
      axisLabel: { color: '#ffffff', fontSize: 12, show: false },
      splitLine: { show: false }
    },
    series: [
      {
        type: 'custom',
        name: '设备状态',
        renderItem: (params: any, api: any) => {
          try {
            const categoryIndex = api.value(0)
            const start = api.coord([api.value(1), categoryIndex])
            const end = api.coord([api.value(2), categoryIndex])

            if (!start || !end || start[0] === end[0]) {
              return null
            }

            const height = api.size([0, 1])[1] * 0.6

            return {
              type: 'rect',
              shape: {
                x: start[0],
                y: start[1] - height / 2,
                width: Math.max(end[0] - start[0], 1),
                height: height
              },
              style: api.style()
            }
          } catch (error) {
            return null
          }
        },
        encode: {
          x: [1, 2],
          y: 0
        },
        data: seriesData
      }
    ]
  }

  // 安全地更新图表
  try {
    bbChart.setOption(option, true)

    // 强制重绘
    setTimeout(() => {
      if (bbChart) {
        bbChart.resize()
      }
    }, 50)

  } catch (err) {
    // 如果更新失败，尝试重新初始化图表
    recoverChart()
  }
}

// 恢复图表
const recoverChart = async () => {
  chartInitialized.value = false
  if (bbChart) {
    bbChart.dispose()
    bbChart = null
  }

  await initChart()

  if (chartInitialized.value && deviceStatusTable.value.length > 0) {
    setTimeout(updateBbChart, 200)
  }
}

// ==================== 生命周期 ====================
onMounted(() => {
  // 初始化图表
  initChart()

  // 延迟加载数据
  setTimeout(() => {
    loadDeviceStatusData()
    startRefreshTimer() // 启动定时刷新
  }, 500)
})

onUnmounted(() => {
  if (bbChart) {
    bbChart.dispose()
    bbChart = null
  }
  window.removeEventListener('resize', handleResize)
  stopRefreshTimer() // 清除定时器
})

// ==================== 暴露方法 ====================
// 暴露方法用于外部调用
defineExpose({
  loadDeviceStatusData,
})
</script>

<style scoped>
.bb-chart-container {
  width: 100%;
  height: 130px;
  box-sizing: border-box;
  padding: 5px;
  position: relative;
  min-height: 130px;
  overflow: hidden;
  background: rgba(0, 0, 0, 0.3);
}

.bb-chart {
  width: 100% !important;
  height: 100% !important;
  min-height: 130px;
}

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

.chart-error {
  color: #ff6b6b;
}
</style>

<script lang="ts">
export default {
  name: 'EquipmentRuntimeHistory',
}
</script>
