<template>
  <div class="left-data-box4">
    <LDBTitleBox title="7日工作时长统计" align="left" />
    <div class="ldb4-chart-box">
      <div v-show="error != ''" class="chart-error">{{ error }}</div>
      <div id="ldb4-chart" class="ldb4-chart" v-show="!loading && error == ''"></div>
    </div>
  </div>
</template>

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

// ==================== 数据定义 ====================
const equipmentStatusData = ref({
  dates: [] as string[],
  workHours: [] as number[],
  standbyHours: [] as number[],
  alarmHours: [] as number[],
  shutdownHours: [] as number[],
})

const loading = ref(false)
const error = ref('')
const chartInitialized = ref(false)

let ldb4Chart: echarts.ECharts | null = null

// ==================== 数据获取与处理 ====================
// 加载设备状态数据
const loadEquipmentStatusData = async (): Promise<void> => {
  try {
    loading.value = true
    error.value = ''

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

    // 构造查询参数
    const param: ParameterTuple[] = [
      ['TableName', '历史_工位设备状态每分钟记录'],
      ['PageNumber', '1'],
      ['PageSize', '1000'],
      ['FieldsToSelect', '*'],
      ['whereConditions', `deviceCode = '${deviceCode}' `],
      ['SortField', '创建时间'],
      ['SortDirection', 'DESC'],
      ['GroupByFields', ''],
    ]

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

    if (response && response.data) {
      const dataRows = response.data.rows || response.data

      if (Array.isArray(dataRows) && dataRows.length > 0) {
        processEquipmentStatusData(dataRows)
      } else {
        console.warn('没有查询到数据，使用空数据')
        clearData()
      }
    } else {
      throw new Error('响应数据格式不正确')
    }
  } catch (err: any) {
    console.error('加载设备状态数据失败:', err)
    error.value = `数据加载失败: ${err.message}`
    clearData()
  } finally {
    loading.value = false
  }
}

// 处理设备状态数据
const processEquipmentStatusData = (rawData: any[]) => {
  // 创建一个对象来存储每天每种状态的分钟计数
  const dailyStatusCount: Record<string, Record<string, number>> = {}

  // 初始化近7天的日期
  const today = new Date()
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    const dateStr = date.toISOString().split('T')[0] // YYYY-MM-DD格式
    dailyStatusCount[dateStr] = {
      '1': 0,  // 运行
      '0': 0,  // 待机
      '-1': 0, // 关机
      '2': 0   // 报警
    }
  }

  // 处理原始数据，按天统计状态
  rawData.forEach((record) => {
    // 从创建时间提取日期部分
    const createTime = record.创建时间
    if (createTime) {
      const dateStr = createTime.split(' ')[0] // 提取 YYYY-MM-DD 部分

      // 如果日期在我们的统计范围内
      if (dailyStatusCount[dateStr]) {
        const status = record.设备状态?.toString() || '0'
        // 增加对应状态的计数（每条记录代表一分钟）
        if (dailyStatusCount[dateStr][status] !== undefined) {
          dailyStatusCount[dateStr][status]++
        }
      }
    }
  })

  // 准备图表数据
  const resultDates: string[] = []
  const workHours: number[] = []
  const standbyHours: number[] = []
  const alarmHours: number[] = []
  const shutdownHours: number[] = []

  // 遍历统计数据生成图表数据
  Object.keys(dailyStatusCount).forEach(date => {
    // 格式化日期显示 (MM-DD)
    const formattedDate = new Date(date).toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
    })

    resultDates.push(formattedDate)

    // 转换分钟到小时并保留一位小数
    workHours.push(parseFloat((dailyStatusCount[date]['1'] / 60).toFixed(1)))
    standbyHours.push(parseFloat((dailyStatusCount[date]['0'] / 60).toFixed(1)))
    alarmHours.push(parseFloat((dailyStatusCount[date]['2'] / 60).toFixed(1)))
    shutdownHours.push(parseFloat((dailyStatusCount[date]['-1'] / 60).toFixed(1)))
  })

  equipmentStatusData.value = {
    dates: resultDates,
    workHours,
    standbyHours,
    alarmHours,
    shutdownHours,
  }
}

// 清空数据
const clearData = () => {
  equipmentStatusData.value = {
    dates: [],
    workHours: [],
    standbyHours: [],
    alarmHours: [],
    shutdownHours: [],
  }
}

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

  const chartDom = document.getElementById('ldb4-chart')
  if (!chartDom) {
    return
  }

  // 确保DOM元素已渲染
  if (chartDom.offsetWidth === 0 || chartDom.offsetHeight === 0) {
    setTimeout(initChart, 100)
    return
  }

  try {
    // 销毁已存在的实例
    const existingInstance = echarts.getInstanceByDom(chartDom)
    if (existingInstance) {
      existingInstance.dispose()
    }

    // 初始化新的图表实例
    ldb4Chart = echarts.init(chartDom)
    chartInitialized.value = true

    // 设置基础配置
    const baseOption = {
      backgroundColor: 'transparent',
      animation: false,
      legend: {
        data: ['运行', '待机', '报警', '关机'],
        textStyle: {
          color: '#ffffff',
          fontWeight: 500
        },
        top: 10,
        right: 20,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '20%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          color: '#ffffff',
          fontSize: 10,
        },
        axisLine: {
          lineStyle: {
            color: '#fff',
          },
        },
      },
      yAxis: {
        type: 'value',
        name: '小时(h)',
        nameTextStyle: {
          color: '#ffffff',
        },
        axisLabel: {
          color: '#ffffff',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#fff',
          },
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255,255,255,0.1)',
          },
        },
      },
      series: [
        {
          name: '运行',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#67C23A',
          },
          label: {
            show: false,
          },
        },
        {
          name: '待机',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#E6A23C',
          },
          label: {
            show: false,
          },
        },
        {
          name: '报警',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#F56C6C',
          },
          label: {
            show: false,
          },
        },
        {
          name: '关机',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#909399',
          },
          label: {
            show: false,
          },
        },
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#555',
        borderWidth: 1,
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
        confine: true,
        position: function (point, params, dom, rect, size) {
          // 鼠标位置
          const x = point[0];
          const y = point[1];

          // tooltip尺寸
          const tooltipWidth = size.contentSize[0];
          const tooltipHeight = size.contentSize[1];

          // 图表尺寸
          const chartWidth = size.viewSize[0];
          const chartHeight = size.viewSize[1];

          let posX = x;
          let posY = y;

          // 水平方向调整
          if (x + tooltipWidth > chartWidth) {
            posX = x - tooltipWidth - 10;
          } else {
            posX = x + 10;
          }

          // 垂直方向调整
          if (y + tooltipHeight > chartHeight) {
            posY = y - tooltipHeight - 10;
          } else {
            posY = y + 10;
          }

          return [posX, posY];
        },
        formatter: function (params: any) {
          let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
          let total = 0;

          params.forEach((param: any) => {
            const value = param.value || 0;
            total += value;
            const color = param.color;
            result += `
              <div style="display: flex; justify-content: space-between; align-items: center; margin: 2px 0;">
                <div style="display: flex; align-items: center;">
                  <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; margin-right: 5px; border-radius: 2px;"></span>
                  <span>${param.seriesName}</span>
                </div>
                <span style="margin-left: 20px; font-weight: bold;">${value.toFixed(1)}h</span>
              </div>
            `;
          });

          result += `
            <div style="border-top: 1px solid #666; margin: 5px 0; padding-top: 5px; display: flex; justify-content: space-between; font-weight: bold;">
              <span>总计</span>
              <span>${total.toFixed(1)}h</span>
            </div>
          `;

          return result;
        }
      },
    }

    ldb4Chart.setOption(baseOption)
    window.addEventListener('resize', handleResize)
  } catch (err) {
    console.error('ECharts初始化失败:', err)
  }
}

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

// 更新图表
const updateChart = () => {
  if (!ldb4Chart || !chartInitialized.value) {
    return
  }

  const { dates, workHours, standbyHours, alarmHours, shutdownHours } = equipmentStatusData.value

  if (!dates || dates.length === 0) {
    showNoDataState()
    return
  }

  try {
    const option = {
      xAxis: {
        data: dates,
      },
      series: [
        {
          name: '运行',
          data: workHours,
        },
        {
          name: '待机',
          data: standbyHours,
        },
        {
          name: '报警',
          data: alarmHours,
        },
        {
          name: '关机',
          data: shutdownHours,
        },
      ],
    }

    ldb4Chart.setOption(option)
  } catch (err) {
    console.error('图表更新失败:', err)
  }
}

// 显示无数据状态
const showNoDataState = () => {
  if (!ldb4Chart) return

  const noDataOption = {
    title: {
      text: '暂无数据',
      textStyle: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'normal',
      },
      left: 'center',
      top: 'center',
    },
    xAxis: { show: false },
    yAxis: { show: false },
    series: [],
  }
  ldb4Chart.setOption(noDataOption, true)
}

// ==================== 监听器 ====================
// 监听数据变化，自动更新图表
watch(
  () => equipmentStatusData.value,
  (newVal) => {
    if (chartInitialized.value && newVal) {
      updateChart()
    }
  },
  { deep: true }
)

// ==================== 生命周期 ====================
onMounted(async () => {
  await nextTick()
  await initChart()
  await loadEquipmentStatusData()
})

onUnmounted(() => {
  if (ldb4Chart) {
    ldb4Chart.dispose()
    ldb4Chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.ldb4-chart-box {
  width: 100%;
  height: calc(100% - 40px);
  box-sizing: border-box;
  position: relative;
  min-height: 180px;
  overflow: hidden;
}

.ldb4-chart {
  width: 100% !important;
  height: 100% !important;
  min-height: 180px;
}

.chart-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #ff6b6b;
  font-size: 12px;
}
</style>

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