<template>
  <div class="right-data-box-oee">
    <LDBTitleBox title="OEE分析" align="right" />
    <div class="oee-content">
      <!-- 图表容器 -->
      <div class="charts-container active">
        <div class="chart-group">
          <!-- OEE仪表盘 - 取消交互 -->
          <div class="chart-item">
            <div id="chart1" class="oee-chart no-interaction"></div>
            <div class="chart-title">OEE</div>
            <div class="chart-value">{{ oeeValue }}%</div>
          </div>
          <!-- 性能利用率仪表盘 - 取消交互 -->
          <div class="chart-item">
            <div id="chart3" class="oee-chart no-interaction"></div>
            <div class="chart-title">性能利用率</div>
            <div class="chart-value">{{ performanceUtilization }}%</div>
          </div>
          <!-- 时间利用率仪表盘 - 增加交互 -->
          <div class="chart-item">
            <div id="chart2" class="oee-chart interactive" @click="handleChartClick('time')"></div>
            <div class="chart-title">时间利用率</div>
            <div class="chart-value">
              <input v-if="editingChart === 'time'" ref="timeInputRef" class="chart-input"
                v-model.number="tempTimeUtilization" @blur="saveTimeUtilization" @keyup.enter="saveTimeUtilization"
                type="number" min="0" max="100" />
              <span v-else>{{ timeUtilization }}%</span>
            </div>
          </div>



          <!-- 良品率仪表盘 - 增加交互 -->
          <div class="chart-item">
            <div id="chart4" class="oee-chart interactive" @click="handleChartClick('quality')"></div>
            <div class="chart-title">良品率</div>
            <div class="chart-value">
              <input v-if="editingChart === 'quality'" ref="qualityInputRef" class="chart-input"
                v-model.number="tempQualityRate" @blur="saveQualityRate" @keyup.enter="saveQualityRate" type="number"
                min="0" max="100" />
              <span v-else>{{ qualityRate }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue'
import * as echarts from 'echarts'
import { CreateData, ExecDatabase, type ParameterTuple } from '../../utils/webApiCall'

defineOptions({
  name: 'OEEAnalysis',
})

const oeeCharts = ref<echarts.ECharts[]>([])

// 用户输入的时间利用率和良品率
const timeUtilization = ref(100) // 时间利用率，默认100%
const qualityRate = ref(100) // 良品率，默认100%
const performanceUtilization = ref(88) // 性能利用率，从数据库读取

// 编辑状态管理
const editingChart = ref('') // 'time', 'quality', ''
const tempTimeUtilization = ref(100)
const tempQualityRate = ref(100)
const timeInputRef = ref<HTMLInputElement>()
const qualityInputRef = ref<HTMLInputElement>()

let refreshTimer: ReturnType<typeof setInterval> | null = null
// 计算OEE值
const oeeValue = computed(() => {
  return Math.round((timeUtilization.value * performanceUtilization.value * qualityRate.value) / 10000)
})

// 处理仪表盘点击
const handleChartClick = (type: string) => {
  switch (type) {
    case 'time':
      // 时间利用率 - 可编辑
      editingChart.value = 'time'
      tempTimeUtilization.value = timeUtilization.value
      nextTick(() => {
        timeInputRef.value?.focus()
        timeInputRef.value?.select()
      })
      break
    case 'quality':
      // 良品率 - 可编辑
      editingChart.value = 'quality'
      tempQualityRate.value = qualityRate.value
      nextTick(() => {
        qualityInputRef.value?.focus()
        qualityInputRef.value?.select()
      })
      break
    // OEE和性能利用率不再处理点击事件
  }
}

// 保存时间利用率
const saveTimeUtilization = () => {
  const value = Math.max(0, Math.min(100, tempTimeUtilization.value))
  timeUtilization.value = value
  editingChart.value = ''
  saveData()
}

// 保存良品率
const saveQualityRate = () => {
  const value = Math.max(0, Math.min(100, tempQualityRate.value))
  qualityRate.value = value
  editingChart.value = ''
  saveData()
}

// 保存数据到localStorage
const saveData = () => {
  const dataToSave = {
    timeUtilization: timeUtilization.value,
    qualityRate: qualityRate.value,
    performanceUtilization: performanceUtilization.value
  }

  try {
    localStorage.setItem('oeeData', JSON.stringify(dataToSave))
  } catch (e) {
    console.error('保存OEE数据失败:', e)
  }
}

// 加载保存的数据
const loadSavedData = () => {
  try {
    const savedData = localStorage.getItem('oeeData')
    if (savedData) {
      const data = JSON.parse(savedData)
      timeUtilization.value = data.timeUtilization || timeUtilization.value
      qualityRate.value = data.qualityRate || qualityRate.value
      performanceUtilization.value = data.performanceUtilization || performanceUtilization.value
    }
  } catch (e) {
    console.error('加载保存的OEE数据失败:', e)
  }
}
const startRefreshTimer = () => {
  stopRefreshTimer()
  const interval = window.dt_Config?.OEEAnalysisRefreshInterval
  console.log('OEE定时刷新间隔:', interval)
  refreshTimer = setInterval(() => {
    loadPerformanceData()
  }, interval)
}
const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}
// 从数据库读取性能利用率数据
const loadPerformanceData = async (): Promise<void> => {
  try {
    // 获取设备编码
    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', null])
    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')) {
          console.error('存储过程执行错误:', response.data[0].result)
          // 使用默认值
          performanceUtilization.value = 88
        } else {
          // 处理性能数据
          processPerformanceData(response.data)
        }
      } else {
        // 没有数据时使用默认值
        console.warn('没有找到性能数据，使用默认值')
        performanceUtilization.value = 88
      }
    } else {
      throw new Error('响应数据格式不正确')
    }
  } catch (err: any) {
    console.error('加载性能数据失败:', err)
    performanceUtilization.value = 88 // 出错时使用默认值
  } finally {
    saveData() // 加载数据库数据后保存
  }
}

// 处理性能数据
const processPerformanceData = (data: any[]) => {
  // 根据实际数据结构调整字段名
  // 这里需要根据实际的数据库表结构来解析性能利用率数据
  if (data && data.length > 0) {
    const latestData = data[0]
    // 根据实际字段名调整
    let performanceValue = parseFloat(latestData.性能开动率 || '0.88')
    performanceValue = Math.round(performanceValue * 100)
    performanceUtilization.value = isNaN(performanceValue) ? 88 : performanceValue
  } else {
    performanceUtilization.value = 88
  }
}

// 仪表盘配置
const getGaugeOption = (value: number, title: string = '') => {
  return {
    series: [
      {
        name: 'OEE',
        type: 'gauge',
        radius: '100%',
        center: ['50%', '50%'],
        startAngle: 225,
        endAngle: -45,
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.3, '#91c7ae'],
              [0.7, '#63869e'],
              [1, '#c23531']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '70%',
          width: 6,
          offsetCenter: [0, '0%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#fff',
          fontSize: 7,
          distance: -10,
        },
        title: {
          show: false
        },
        detail: {
          show: false // 不在仪表盘内显示数值
        },
        data: [
          {
            value: value,
            name: title
          }
        ]
      }
    ]
  }
}

// 初始化所有图表
const initAllCharts = async () => {
  await nextTick()

  // 初始化四个图表
  const chartConfigs = [
    { id: 'chart1', title: 'OEE', value: oeeValue.value },
    { id: 'chart2', title: '时间利用率', value: timeUtilization.value },
    { id: 'chart3', title: '性能利用率', value: performanceUtilization.value },
    { id: 'chart4', title: '良品率', value: qualityRate.value }
  ]

  chartConfigs.forEach((config, index) => {
    const chartDom = document.getElementById(config.id)
    if (chartDom) {
      const chart = echarts.init(chartDom)
      const option = getGaugeOption(config.value, config.title)
      chart.setOption(option)
      oeeCharts.value[index] = chart
    }
  })
}

// 更新所有图表
const updateAllCharts = () => {
  const chartConfigs = [
    { chartIndex: 0, value: oeeValue.value, title: 'OEE' },
    { chartIndex: 1, value: timeUtilization.value, title: '时间利用率' },
    { chartIndex: 2, value: performanceUtilization.value, title: '性能利用率' },
    { chartIndex: 3, value: qualityRate.value, title: '良品率' }
  ]

  chartConfigs.forEach(config => {
    const chart = oeeCharts.value[config.chartIndex]
    if (chart) {
      const option = getGaugeOption(config.value, config.title)
      chart.setOption(option)
    }
  })
}

// 监听数据变化，自动更新图表
watch([timeUtilization, qualityRate, performanceUtilization], () => {
  updateAllCharts()
})

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

// 清理资源
const cleanup = () => {
  oeeCharts.value.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
  oeeCharts.value = []
  stopRefreshTimer()
}

onMounted(() => {
  loadSavedData() // 先加载本地保存的数据
  initAllCharts()
  loadPerformanceData() // 然后从数据库加载性能利用率
  window.addEventListener('resize', handleResize)
  startRefreshTimer()
})

onUnmounted(() => {
  cleanup()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.oee-content {
  width: 100%;
  height: calc(100% - 40px);
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 图表容器样式 */
.charts-container {
  display: none;
  height: 160px;
}

.charts-container.active {
  display: block;
}

.chart-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  width: 100%;
}

.chart-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  margin: 0 2px;
  position: relative;
}

/* 可交互图表样式 */
.oee-chart.interactive {

  transition: all 0.3s;
}

.oee-chart.interactive:hover {
  transform: scale(1.05);
}

/* 不可交互图表样式 */
.oee-chart.no-interaction {
  cursor: default;
}

.oee-chart.no-interaction:hover {
  transform: none;
}

.chart-title {
  color: #fff;
  font-size: 12px;
  text-align: center;
  position: absolute;
  top: 85px;
}

.chart-value {
  color: #409EFF;
  font-size: 14px;
  text-align: center;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 100px;
}

/* 可交互的数值区域样式 */
.chart-item .interactive+.chart-title+.chart-value {

  transition: color 0.3s;
}


/* 输入框样式 */
.chart-input {
  background: transparent;
  border: 1px solid #0070c0;
  color: #409EFF;
  font-size: 14px;
  text-align: center;
  width: 50px;
  outline: none;
  padding: 2px 4px;
  border-radius: 2px;
  background-color: rgba(255, 255, 255, 0.1);
  box-sizing: border-box;
  cursor: text;
}

.chart-input:focus {
  border-color: #67C23A;
  background-color: rgba(255, 255, 255, 0.2);
}

.oee-chart {
  width: 100%;
  height: 100px;
}
</style>

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