<template>
  <div class="oee-container">
    <h2>设备OEE综合效率分析</h2>
    <el-row :gutter="20" class="mb-20">
      <el-col :span="14">
        <el-form label-width="80px" inline>
          <el-form-item label="选择设备">
            <el-select v-model="selectedDeviceId" placeholder="请选择设备" class="!w-300px" @change="onDeviceChange">
              <el-option v-for="item in deviceList" :key="item.id" :label="item.deviceName" :value="item.id"
                :data-product-id="item.productId" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" @change="onSearch" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mb-20">
      <el-col :span="8">
        <el-card>
          <div class="oee-metric-title">总体可用率</div>
          <div class="oee-metric-value">{{ formatPercent(dashboardData?.availableRate) }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div class="oee-metric-title">运行时长(分钟)</div>
          <div class="oee-metric-value">{{ dashboardData?.runTime ?? '-' }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div class="oee-metric-title">停机时长(分钟)</div>
          <div class="oee-metric-value">{{ dashboardData?.stopTime ?? '-' }}</div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mb-20">
      <el-col :span="24">
        <el-card>
          <div class="oee-metric-title mb-10">可用率趋势</div>
          <Echart :options="oeeTrendOption" height="300px" />
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div class="oee-metric-title mb-10">基础采集数据</div>
          <el-table :data="baseData.list" border stripe>
            <el-table-column prop="collectedAt" label="采集时间" width="180" />
            <el-table-column prop="powerW" label="功率(W)" width="120" />
            <el-table-column prop="currentValue" label="电流" width="120" />
            <el-table-column prop="temperatureC" label="温度(℃)" width="120" />
            <el-table-column prop="isOn" label="开启" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isOn ? 'success' : 'info'">{{ scope.row.isOn ? '是' : '否' }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-10" style="text-align: right">
            <el-pagination v-model:current-page="basePage.pageNo" v-model:page-size="basePage.pageSize"
              :total="baseData.total" layout="total, prev, pager, next, sizes" @current-change="fetchBaseData"
              @size-change="onPageSizeChange" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DeviceApi } from '@/api/iot/device/device/index'
import { ProductApi } from '@/api/iot/product/product/index'
import { Echart } from '@/components/Echart'
import type { EChartsOption } from 'echarts'
import dayjs from 'dayjs'

const deviceList = ref<any[]>([])
const selectedDeviceId = ref<number>(0)
const selectedProductId = ref<number>(0)
const dashboardData = ref<any>(null)
const timeRange = ref<[string, string]>(['', ''])
const baseData = ref<{ list: any[]; total: number }>({ list: [], total: 0 })
const basePage = ref<{ pageNo: number; pageSize: number }>({ pageNo: 1, pageSize: 10 })

const fetchDeviceList = async () => {
  // 获取监测的产品列表，仅含 id 和 name
  const res = await ProductApi.getMonitoredProductList()
  const data = (res as any)?.data ?? (res as any) ?? []
  // 兼容下游使用：把产品列表映射为设备下拉的通用结构
  deviceList.value = data.map((p: any) => ({ id: p.id, deviceName: p.name, productId: p.id }))
  if (deviceList.value.length > 0) {
    selectedDeviceId.value = deviceList.value[0].id
    selectedProductId.value = deviceList.value[0].productId
    await fetchAll()
  }
}

const onDeviceChange = async () => {
  const selectedDevice = deviceList.value.find(item => item.id === selectedDeviceId.value)
  if (selectedDevice) {
    selectedProductId.value = selectedDevice.productId
  }
  await onSearch()
}

const onSearch = async () => {
  await fetchAll()
}

const fetchAll = async () => {
  if (!selectedProductId.value || !timeRange.value?.[0] || !timeRange.value?.[1]) return
  await Promise.all([fetchDashboard(), fetchBaseData()])
}

const fetchDashboard = async () => {
  dashboardData.value = null
  try {
    const res = await DeviceApi.getOeeDashboard({
      deviceId: selectedProductId.value,
      startTime: timeRange.value![0],
      endTime: timeRange.value![1]
    })
    const data = (res as any)?.data ?? (res as any)
    dashboardData.value = {
      ...data,
      trend: (data?.trend || []).map((item: any) => ({
        ...item,
        time: formatTimestamp(item?.time)
      }))
    }
  } catch (e) {
    ElMessage.error('获取仪表盘数据失败')
  }
}

const fetchBaseData = async () => {
  if (!timeRange.value?.[0] || !timeRange.value?.[1]) return
  try {
    const res = await DeviceApi.getOeeBaseDataPage({
      deviceId: selectedProductId.value,
      startTime: timeRange.value[0],
      endTime: timeRange.value[1],
      pageNo: basePage.value.pageNo,
      pageSize: basePage.value.pageSize
    })
    const data = (res as any)?.data ?? (res as any) ?? { list: [], total: 0 }
    baseData.value = {
      list: (data.list || []).map((row: any) => ({
        ...row,
        collectedAt: formatTimestamp(row?.collectedAt)
      })),
      total: data.total || 0
    }
  } catch (e) {
    ElMessage.error('获取基础数据失败')
  }
}

const onPageSizeChange = async () => {
  basePage.value.pageNo = 1
  await fetchBaseData()
}

const oeeTrendOption = computed<EChartsOption>(() => {
  if (!dashboardData.value) return {}
  return {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: (dashboardData.value.trend || []).map((item: any) => item.time)
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 1,
      axisLabel: { formatter: (val: number) => (val * 100).toFixed(0) + '%' }
    },
    series: [
      {
        name: '可用率',
        type: 'line',
        data: (dashboardData.value.trend || []).map((item: any) => item.availableRate),
        smooth: true,
        areaStyle: {}
      }
    ]
  }
})

onMounted(() => {
  // 默认最近 7 天
  const end = dayjs()
  const start = end.subtract(7, 'day')
  timeRange.value = [start.format('YYYY-MM-DD 00:00:00'), end.format('YYYY-MM-DD 23:59:59')]
  fetchDeviceList()
})

const formatPercent = (val?: number) => {
  if (val === undefined || val === null) return '-'
  return (val * 100).toFixed(2) + '%'
}

const toMilliseconds = (value: any): number | undefined => {
  if (value === undefined || value === null) return undefined
  if (typeof value === 'number') return value < 1e12 ? value * 1000 : value
  if (typeof value === 'string') {
    if (/^\d+$/.test(value)) {
      const num = Number(value)
      return value.length === 10 ? num * 1000 : num
    }
    const parsed = Date.parse(value)
    return isNaN(parsed) ? undefined : parsed
  }
  return undefined
}

const formatTimestamp = (value: any): string => {
  const ms = toMilliseconds(value)
  if (!ms) return value != null ? String(value) : '-'
  const d = dayjs(ms)
  return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : String(value)
}
</script>

<style scoped>
.oee-container {
  padding: 24px;
}

.oee-metric-title {
  margin-bottom: 8px;
  font-size: 16px;
  color: #666;
}

.oee-metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
}

.oee-metric-value.oee-main {
  color: #67c23a;
}

.mb-10 {
  margin-bottom: 10px;
}

.mb-20 {
  margin-bottom: 20px;
}
</style>
