<template>
  <view class="page">
    <view ref="header" class="detail-header">
      <uni-row>
        <uni-col :span="12" class="flex-row align-center">
          <view class="detail-label">{{ $t('realTimeData.detail.assetCode') }}</view>
          <view>{{ info.deviceCode }}</view>
        </uni-col>
        <uni-col :span="12" class="flex-row align-center">
          <view class="detail-label">{{ $t('realTimeData.detail.isOnline') }}</view>
          <view v-if="info.ifInline === 3" class="flex-row align-center" style="color: #9CFFE6">
            <view class="dot-green" />
            {{ $t('realTimeData.status.online') }}
          </view>
          <view v-else class="flex-row align-center" style="margin-left: 10px; color: #FB0000">
            <view class="dot-red" />
            {{ $t('realTimeData.status.offline') }}
          </view>
        </uni-col>
      </uni-row>
      <uni-row style="margin-top: 10px">
        <uni-col :span="24" class="flex-row">
          <view class="detail-label">{{ $t('realTimeData.detail.deviceType') }}</view>
          <view style="flex: 1">{{ info.deviceName }}</view>
        </uni-col>
<!--        <uni-col :span="12" class="flex-row align-center">-->
<!--          <view class="detail-label">{{ $t('realTimeData.detail.lastUpdateTime') }}</view>-->
<!--          <view>{{ dayjs(info.lastInlineTime).format('HH:mm:ss') }}</view>-->
<!--        </uni-col>-->
      </uni-row>
      <uni-row style="margin-top: 10px">
        <uni-col :span="24" class="flex-row">
          <view class="detail-label">{{ $t('realTimeData.detail.lastUpdateTime') }}</view>
          <view>{{ info.lastInlineTime ? dayjs(info.lastInlineTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}</view>
        </uni-col>
      </uni-row>
    </view>
    <scroll-view scroll-y="true" style="margin-top: 10px; height: calc(100% - 150px)">
      <view
        v-for="item of list"
        class="item"
        :class="clickItem.identifier === item.identifier ? 'selected' : undefined"
        :key="item.id"
        @click="loadChartData(item)"
      >
        <view>{{ item.modelName }}</view>
        <view>{{ item.value }}</view>
      </view>
      <uni-card>
        <uni-section :title="(clickItem?.modelName || '') + $t('realTimeData.detail.chartTitle')" @click="viewChart">
          <template #right>
            <image src="~@/static/realTimeData/expand.svg" style="width: 16px; height: 16px" />
          </template>
        </uni-section>
        <view class="charts-box">
          <qiun-data-charts
            type="area"
            :ontouch="true"
            :opts="opts"
            :chartData="chartData"
          />
        </view>
      </uni-card>
    </scroll-view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { getDeviceRealTimeChartData, getDeviceRealTimeDataDetail } from "@/api/realTimeData"
import { onMounted, reactive, ref } from "vue"
import dayjs from "dayjs";

const info = ref()
const list = ref([])
const clickItem = ref()

const opts = reactive({
  color: ['#0876C3'],
  padding: [15, 0, 0, 0],
  legend: {
    show: false,
  },
  enableScroll: true,
  xAxis: {
    disableGrid: true,
    rotateLabel: true, // 旋转x轴文字
    rotateAngle: 90, // x轴文字旋转角度
    enableScroll: true,
    itemCount: 10,
    marginTop: 5,
    fontColor: '#666666',
    fontSize: 12,
  },
  yAxis: {
    gridColor: '#BABABA',
    gridType: "dash",
    dashLength: 10,
    data: [{
      fontSize: 12,
      fontColor: '#666666',
    }]
  },
  extra: {
    area: {
      type: "curve",
      opacity: 0.8, // 区域图透明度
      addLine: true,
      width: 2,
      gradient: true,
      activeType: "hollow"
    }
  }
})
const chartData = reactive({
  categories: [],
  series: [],
})

// 跳转查看横版图表
const viewChart = () => {
  uni.navigateTo({ url: `/pages/realTimeData/chart/index?deviceCode=${info.value.deviceCode}&type=${clickItem.value.identifier}&name=${clickItem.value.modelName}` })
}

// 加载图表数据，并转换格式
const loadChartData = async (item) => {
  clickItem.value = item

  const source = (await getDeviceRealTimeChartData(info.value.deviceCode, item.identifier, {
    // beginTime: dayjs().add(-10, 'minute').format('YYYY-MM-DD HH:mm:ss'),
    beginTime: dayjs().add(-1, 'day').format('YYYY-MM-DD HH:mm:ss'), // 获取过去一天的数据 08/04修改
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })).data

  // 1. 提取x轴时间
  const categories = source
      .map(item =>  dayjs(item.timestamp).format('YYYY-MM-DD HH:mm:ss'))
      // .sort((a, b) => new Date(a) - new Date(b)); // 按时间升序排列
  // console.log("🚀 ~ loadChartData ~ categories:", categories) 

  // 2. 提取y轴数据
  const seriesData = source.map(item => item?.value ? item.value.toFixed(2) : 0); // 确保数值为数字，避免 NaN
  // console.log("🚀 ~ loadChartData ~ seriesData:", seriesData)
  chartData.categories = categories
  chartData.series = [{
    name: item.modelName,
    data: seriesData,
    textColor: '#333333',
    textSize: 10,
  }]
}

onLoad(async (params) => {
  // 根据导航传递的id加载设备详情
  info.value = JSON.parse(params.info)
  const id = info.value.id
  const data = (await getDeviceRealTimeDataDetail(id)).data
  // 按 modelOrder 降序排序
  data.sort((a, b) => b.modelOrder - a.modelOrder)

  // 提取“累计运行时间”和其余项
  //const cumulativeItem = data.filter(item => item.modelName === '累计运行时间')
  // const otherItems = data.filter(item => item.modelName !== '累计运行时间')

  // 合并：累计运行时间在前
  // list.value = [...cumulativeItem, ...otherItems]
  list.value = data

  if (list.value.length > 0) {
    await loadChartData(list.value[0])
  }
})

// 当顶部内容超过一行时，缩小滚动部分的高度
const style = ref({
  transform: 'translateY(92px)',
  height: 'calc(100% - 102px)'
})
const header = ref()
onMounted(() => {
  if (header.value.$el.offsetHeight > 130) {
    style.value = {
      transform: 'translateY(112px)',
      height: 'calc(100% - 122px)'
    }
  }
})
</script>

<style scoped lang="scss">
.page {
  width: 100%;
  height: 100%;
  padding: 0;
}

.detail-header {
  width: 100%;
  padding: 20px;
  background-color: #004098;
  color: white;
  font-size: 16px;
  font-weight: 500;
  // position: fixed;
}

.item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-radius: 5px;
  padding: 12px 20px;
  font-size: 14px;
  color: #333333;
  margin: 0 10px 10px 10px;
}

.dot-red {
  width: 6px;
  height: 6px;
  background: #FB0000;
  border-radius: 3px;
  margin-right: 5px;
}

.dot-green {
  width: 6px;
  height: 6px;
  background: #9CFFE6;
  border-radius: 3px;
  margin-right: 5px;
}

:deep(.uni-card) {
  padding: 0 !important;

  .uni-section-header {
    padding-right: 30px;
  }

  .uni-section__content-title {
    font-size: 16px !important;
    color: #333333 !important;
    font-weight: 600;
  }
}

.charts-box {
  width: 100%;
  height: 300px;
}

.detail-label {
  width: 80px !important;
}

.selected {
  border: 2px solid #0087D3;
  border-radius: 5px;
  padding: 10px 18px;
}
</style>