<template>
  <view class="device-section">
    <view class="section-title">{{ t('deviceOverview.title') }}</view>
    <!-- 设备状态统计 -->
    <view class="trend-stats">
      <view class="trend-stat-card">
        <text class="trend-stat-value">{{ deviceData.totalDevices }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.totalDevices') }}</text>
      </view>
      <view class="trend-stat-card">
        <text class="trend-stat-value running">{{ deviceData.runningCount }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.runningCount') }}</text>
      </view>
      <view class="trend-stat-card">
        <text class="trend-stat-value standby">{{ deviceData.standbyCount }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.standbyCount') }}</text>
      </view>
      <view class="trend-stat-card">
        <text class="trend-stat-value fault">{{ deviceData.faultCount }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.faultCount') }}</text>
      </view>
    </view>
    <!-- 设备比率统计 -->
    <view class="trend-stats">
      <view class="trend-stat-card">
        <text class="trend-stat-value offline">{{ deviceData.offlineCount }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.offlineCount') }}</text>
      </view>
      <view class="trend-stat-card">
        <text class="trend-stat-value">{{ deviceData.utilizationRate }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.utilizationRate') }}</text>
      </view>
      <view class="trend-stat-card">
        <text class="trend-stat-value running">{{ deviceData.bootRate }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.bootRate') }}</text>
      </view>
      <view class="trend-stat-card">
        <text class="trend-stat-value fault">{{ deviceData.faultRate }}</text>
        <text class="trend-stat-label">{{ t('deviceOverview.faultRate') }}</text>
      </view>
    </view>

    <!-- 稼动率/开机率趋势图 -->
    <view class="rate-trend-section">
      <view class="rate-trend-header">
        <text class="rate-trend-title">{{ t('deviceOverview.rateTrend') }}</text>
        <view class="trend-filter-icon" @click="openTrendFilterDrawer">
          <uni-icons type="settings" size="22" color="#7b8491"></uni-icons>
        </view>
      </view>
      <view class="chart-box">
        <qiun-data-charts type="line" :chartData="rateChartData" :canvas2d="false" :opts="rateChartOpts" />
      </view>
    </view>

    <uni-popup ref="trendFilterPopupRef" class="trend-filter-popup" type="right" background-color="transparent" :animation="false">
      <view class="filter-drawer">
        <view class="drawer-header">
          <text class="drawer-title">{{ t('functionCommon.moreFilter') }}</text>
        </view>
        <scroll-view scroll-y class="drawer-body">
          <view class="drawer-field">
            <text class="drawer-label">{{ t('deviceOverview.trendPeriod') }}</text>
            <picker mode="selector" :range="periodRange" range-key="text" :value="draftPeriodIndex" @change="onTrendFilterPeriodChange">
              <view class="drawer-picker">
                <text class="drawer-picker-text">{{ draftPeriodLabel }}</text>
                <uni-icons type="bottom" size="14" color="#9ca3af"></uni-icons>
              </view>
            </picker>
          </view>
          <view class="drawer-switch-field">
            <text class="drawer-label">{{ t('deviceOverview.onlyScheduled') }}</text>
            <up-switch v-model="draftTrendFilter.onlyScheduled" size="22" activeColor="#1a3a5c" />
          </view>
          <view class="drawer-switch-field">
            <text class="drawer-label">{{ t('deviceOverview.skipHoliday') }}</text>
            <up-switch v-model="draftTrendFilter.skipHoliday" size="22" activeColor="#1a3a5c" />
          </view>
        </scroll-view>
        <view class="drawer-actions">
          <view class="drawer-action reset" @click="resetTrendFilterDrawer">{{ t('functionCommon.reset') }}</view>
          <view class="drawer-action confirm" @click="confirmTrendFilterDrawer">{{ t('functionCommon.confirm') }}</view>
        </view>
      </view>
    </uni-popup>

    <!-- 近7日平均稼动率排名 -->
    <view class="rate-trend-section">
      <view class="rate-trend-header">
        <text class="rate-trend-title">{{ rankingTitle }}</text>
      </view>
      <scroll-view class="ranking-scroll" scroll-y :style="{ height: rankingScrollHeight }">
        <view :style="{ height: rankingChartHeight }">
          <qiun-data-charts type="bar" :chartData="rankingChartData" :canvas2d="false" :opts="rankingChartOpts" />
        </view>
      </scroll-view>
    </view>

    <!-- 单设备近7日稼动率/开机率趋势 -->
    <view class="rate-trend-section">
      <view class="rate-trend-header">
        <text class="rate-trend-title">{{ deviceTrendTitle }}</text>
        <picker mode="selector" :range="deviceRange" range-key="text" :value="deviceIndex" @change="onDeviceChange">
          <view class="filter-select">
            <text class="filter-text">{{ selectedDeviceName || t('deviceOverview.selectDevice') }}</text>
            <text class="filter-arrow">▼</text>
          </view>
        </picker>
      </view>
      <view class="device-trend-chart-box" v-if="selectedDeviceId">
        <qiun-data-charts type="line" :chartData="deviceTrendChartData" :canvas2d="false" :opts="deviceTrendChartOpts" />
      </view>
      <view class="empty-hint" v-else>
        <text class="empty-hint-text">{{ t('deviceOverview.selectDeviceHint') }}</text>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import request from '@/utils/request'

const { t } = useI18n()
const trendFilterPopupRef = ref(null)

const deviceData = reactive({
  totalDevices: 0,
  runningCount: 0,
  standbyCount: 0,
  faultCount: 0,
  offlineCount: 0,
  utilizationRate: '-',
  bootRate: '-',
  faultRate: '-'
})

const currentPeriod = ref('LAST_7_DAYS')
const onlyScheduled = ref(true)
const skipHoliday = ref(false)
const draftTrendFilter = reactive({
  period: 'LAST_7_DAYS',
  onlyScheduled: true,
  skipHoliday: false
})

const periodRange = computed(() => [
  { text: t('deviceOverview.periodLastWeek'), value: 'LAST_WEEK' },
  { text: t('deviceOverview.periodThisWeek'), value: 'THIS_WEEK' },
  { text: t('deviceOverview.periodLast7Days'), value: 'LAST_7_DAYS' },
  { text: t('deviceOverview.periodLastMonth'), value: 'LAST_MONTH' },
  { text: t('deviceOverview.periodThisMonth'), value: 'THIS_MONTH' }
])

const draftPeriodIndex = computed(() => {
  const idx = periodRange.value.findIndex(item => item.value === draftTrendFilter.period)
  return idx >= 0 ? idx : 0
})

const periodLabelMap = computed(() => ({
  LAST_WEEK: t('deviceOverview.periodLastWeek'),
  THIS_WEEK: t('deviceOverview.periodThisWeek'),
  LAST_7_DAYS: t('deviceOverview.periodLast7Days'),
  LAST_MONTH: t('deviceOverview.periodLastMonth'),
  THIS_MONTH: t('deviceOverview.periodThisMonth')
}))

const currentPeriodLabel = computed(() => {
  return periodLabelMap.value[currentPeriod.value] || t('deviceOverview.periodLast7Days')
})

const draftPeriodLabel = computed(() => {
  return periodLabelMap.value[draftTrendFilter.period] || t('deviceOverview.periodLast7Days')
})

const rankingTitle = computed(() => {
  const period = currentPeriodLabel.value
  return t('deviceOverview.utilizationRanking').replace('近7日', period)
})

const deviceTrendTitle = computed(() => {
  const period = currentPeriodLabel.value
  return t('deviceOverview.deviceRateTrend').replace('近7日', period)
})

const rateChartOpts = {
  color: ['#1a3a5c', '#18bc37'],
  dataLabel: false,
  dataPointShape: false,
  legend: { show: true, position: 'bottom' },
  xAxis: { disableGrid: true, labelCount: 5 },
  yAxis: { gridType: 'dash', dashLength: 2, data: [{ min: 0, max: 100 }] },
  extra: { line: { type: 'straight', width: 1, activeType: 'hollow' } }
}

const rateChartData = reactive({
  categories: [],
  series: [
    { name: '', data: [] },
    { name: '', data: [] }
  ]
})

const rankingChartOpts = {
  color: ['#1a3a5c'],
  dataLabel: true,
  legend: { show: false },
  xAxis: { disableGrid: true, max: 100, axisLabel: { padding: [0, 0, 0, 10] } },
  yAxis: { disableGrid: true, axisLabel: { padding: [0, 10, 0, 0], formatter: formatRankingAxisLabel } },
  extra: {
    bar: {
      type: 'group',
      width: 20,
      seriesGap: 4,
      categoryGap: 4,
      barBorderRadius: [4, 4, 0, 0],
      linearType: 'custom',
      linearOpacity: 0.6,
      activeBgColor: '#1a3a5c',
      activeBgOpacity: 0.08
    }
  }
}

const rankingChartData = reactive({
  categories: [],
  series: [{ name: '', data: [] }]
})

function formatRankingAxisLabel(value) {
  return truncateByDisplayWidth(value, 6)
}

function truncateByDisplayWidth(value, maxWidth) {
  const text = String(value || '')
  let width = 0
  let result = ''
  for (const char of text) {
    const charWidth = /[^\x00-\xff]/.test(char) ? 1 : 0.5
    if (width + charWidth > maxWidth) return result + '...'
    width += charWidth
    result += char
  }
  return text
}

const ITEM_HEIGHT_PX = 30
const MAX_VISIBLE = 6
const rankingScrollHeight = computed(() => {
  const count = rankingChartData.categories.length || 1
  const visible = Math.min(count, MAX_VISIBLE)
  return `${visible * ITEM_HEIGHT_PX + 30}px`
})
const rankingChartHeight = computed(() => {
  const count = rankingChartData.categories.length || 1
  return `${count * ITEM_HEIGHT_PX + 30}px`
})

const deviceList = ref([])
const selectedDeviceId = ref(null)
const selectedDeviceName = ref('')
const isInitialLoad = ref(true)

const deviceRange = computed(() =>
  deviceList.value.map((d) => ({ text: d.deviceName || d.name || '', value: d.id }))
)

const deviceIndex = computed(() => {
  const idx = deviceRange.value.findIndex(item => item.value === selectedDeviceId.value)
  return idx >= 0 ? idx : 0
})

const deviceTrendChartOpts = {
  color: ['#1a3a5c', '#18bc37'],
  dataLabel: false,
  dataPointShape: false,
  legend: { show: true, position: 'bottom' },
  xAxis: { disableGrid: true, labelCount: 5 },
  yAxis: { gridType: 'dash', dashLength: 2, data: [{ min: 0, max: 100 }] },
  extra: { line: { type: 'straight', width: 1, activeType: 'hollow' } }
}

const deviceTrendChartData = reactive({
  categories: [],
  series: [
    { name: '', data: [] },
    { name: '', data: [] }
  ]
})

async function loadDeviceOverview() {
  const res = await request({ url: '/admin-api/iot/device/getDeviceOverview', method: 'get', showLoading: !isInitialLoad.value })
  const data = res?.data || {}
  deviceData.totalDevices = data.totalDevices ?? 0
  deviceData.runningCount = data.runningCount ?? 0
  deviceData.standbyCount = data.standbyCount ?? 0
  deviceData.faultCount = data.faultCount ?? 0
  deviceData.offlineCount = data.offlineCount ?? 0
  deviceData.utilizationRate = data.utilizationRate ?? '-'
  deviceData.bootRate = data.bootRate ?? '-'
  deviceData.faultRate = data.faultRate ?? '-'
}

async function loadRateTrend() {
  const params = {
    period: currentPeriod.value,
    onlyScheduled: onlyScheduled.value,
    skipHoliday: skipHoliday.value
  }
  const res = await request({ url: '/admin-api/iot/device/deviceRateTrend', method: 'get', params, showLoading: !isInitialLoad.value })
  const list = res?.data || []
  const categories = list.map((item) => (item.day || '').substring(5))
  const utilizationData = list.map((item) => {
    const v = parseFloat(item.utilizationRate)
    return isNaN(v) ? 0 : Math.round(v * 100) / 100
  })
  const powerOnData = list.map((item) => {
    const v = parseFloat(item.powerOnRate)
    return isNaN(v) ? 0 : Math.round(v * 100) / 100
  })
  rateChartData.categories = categories
  rateChartData.series = [
    { name: t('deviceOverview.utilizationRateTrend'), data: utilizationData },
    { name: t('deviceOverview.bootRate'), data: powerOnData }
  ]
}

async function loadUtilizationRanking() {
  const params = { period: currentPeriod.value }
  const res = await request({ url: '/admin-api/iot/device-operation-record/deviceOperationPageList', method: 'get', params, showLoading: !isInitialLoad.value })
  const list = res?.data || []
  const sorted = [...list].sort((a, b) => {
    const va = parseFloat(a.utilizationRate) || 0
    const vb = parseFloat(b.utilizationRate) || 0
    return vb - va
  })
  const categories = sorted.map((item) => formatRankingAxisLabel(item.deviceName || ''))
  const data = sorted.map((item) => {
    const v = parseFloat(item.utilizationRate)
    return isNaN(v) ? 0 : Math.round(v * 100) / 100
  })
  const total = sorted.length
  const colors = sorted.map((_, index) => {
    const ratio = total > 1 ? index / (total - 1) : 0
    const r = Math.round(26 + ratio * (74 - 26))
    const g = Math.round(58 + ratio * (144 - 58))
    const b = Math.round(92 + ratio * (194 - 92))
    return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
  })
  rankingChartData.categories = categories
  rankingChartData.series = [{
    name: t('deviceOverview.utilizationRateTrend'),
    data,
    linearColor: colors.map((c) => ['#e8f0f8', c])
  }]
}

async function loadDeviceList() {
  const res = await request({ url: '/admin-api/iot/device/deviceList', method: 'get', showLoading: !isInitialLoad.value })
  deviceList.value = res?.data || []
  if (deviceList.value.length > 0 && !selectedDeviceId.value) {
    const first = deviceList.value[0]
    selectedDeviceId.value = first.id
    selectedDeviceName.value = first.deviceName || first.name || ''
    loadDeviceRateTrend()
  }
}

async function loadDeviceRateTrend() {
  if (!selectedDeviceId.value) return
  const params = { deviceId: selectedDeviceId.value, period: currentPeriod.value }
  const res = await request({
    url: '/admin-api/iot/device-operation-record/deviceRateTrendByDeviceId',
    method: 'get',
    params,
    showLoading: !isInitialLoad.value
  })
  const list = res?.data || []
  const categories = list.map((item) => (item.day || '').substring(5))
  const utilizationData = list.map((item) => {
    const v = parseFloat(item.utilizationRate)
    return isNaN(v) ? 0 : Math.round(v * 100) / 100
  })
  const powerOnData = list.map((item) => {
    const v = parseFloat(item.powerOnRate)
    return isNaN(v) ? 0 : Math.round(v * 100) / 100
  })
  deviceTrendChartData.categories = categories
  deviceTrendChartData.series = [
    { name: t('deviceOverview.utilizationRateTrend'), data: utilizationData },
    { name: t('deviceOverview.bootRate'), data: powerOnData }
  ]
}

function onDeviceChange(e) {
  const idx = e.detail.value
  const item = deviceRange.value[idx]
  if (!item) return
  selectedDeviceId.value = item.value
  selectedDeviceName.value = item.text
  loadDeviceRateTrend()
}

function syncDraftTrendFilter() {
  draftTrendFilter.period = currentPeriod.value
  draftTrendFilter.onlyScheduled = onlyScheduled.value
  draftTrendFilter.skipHoliday = skipHoliday.value
}

function openTrendFilterDrawer() {
  syncDraftTrendFilter()
  trendFilterPopupRef.value?.open()
}

function closeTrendFilterDrawer() {
  trendFilterPopupRef.value?.close()
}

function onTrendFilterPeriodChange(e) {
  const idx = Number(e?.detail?.value || 0)
  const val = periodRange.value[idx]?.value
  if (!val) return
  draftTrendFilter.period = val
}

async function refreshTrendData() {
  await Promise.all([
    loadRateTrend(),
    loadUtilizationRanking(),
    loadDeviceRateTrend()
  ])
}

async function confirmTrendFilterDrawer() {
  const changed = currentPeriod.value !== draftTrendFilter.period ||
    onlyScheduled.value !== draftTrendFilter.onlyScheduled ||
    skipHoliday.value !== draftTrendFilter.skipHoliday
  currentPeriod.value = draftTrendFilter.period
  onlyScheduled.value = draftTrendFilter.onlyScheduled
  skipHoliday.value = draftTrendFilter.skipHoliday
  closeTrendFilterDrawer()
  if (changed) await refreshTrendData()
}

async function resetTrendFilterDrawer() {
  draftTrendFilter.period = 'LAST_7_DAYS'
  draftTrendFilter.onlyScheduled = true
  draftTrendFilter.skipHoliday = false
  currentPeriod.value = draftTrendFilter.period
  onlyScheduled.value = draftTrendFilter.onlyScheduled
  skipHoliday.value = draftTrendFilter.skipHoliday
  closeTrendFilterDrawer()
  await refreshTrendData()
}

onMounted(async () => {
  await Promise.all([
    loadDeviceOverview(),
    loadRateTrend(),
    loadUtilizationRanking(),
    loadDeviceList()
  ])
  isInitialLoad.value = false
})

defineExpose({ loadDeviceOverview, loadRateTrend, loadUtilizationRanking, loadDeviceRateTrend })
</script>

<style lang="scss" scoped>
.device-section {
  margin-top: 20rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 28rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1a3a5c;
  margin-bottom: 24rpx;
}

.trend-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.trend-stat-card {
  flex: 1;
  background: #f8fafc;
  border-radius: 12rpx;
  padding: 20rpx 12rpx;
  margin: 0 6rpx;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;

  &:first-child {
    margin-left: 0;
  }

  &:last-child {
    margin-right: 0;
  }
}

.trend-stat-value {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #1a3a5c;
  margin-bottom: 6rpx;

  &.running {
    color: #18bc37;
  }

  &.standby {
    color: #4a90c2;
  }

  &.fault {
    color: #ff4d4f;
  }

  &.offline {
    color: #999999;
  }
}

.trend-stat-label {
  display: block;
  font-size: 22rpx;
  color: #999999;
}

.rate-trend-section {
  margin-top: 28rpx;
  padding-top: 24rpx;
  border-top: 2rpx solid #f0f2f5;
}

.rate-trend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.rate-trend-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #1a3a5c;
}

.filter-select {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  background: #f0f2f5;
  border-radius: 12rpx;

  &:active {
    background: #e8ecf0;
  }
}

.filter-text {
  font-size: 24rpx;
  color: #1a3a5c;
  font-weight: 500;
  margin-right: 8rpx;
}

.filter-arrow {
  font-size: 18rpx;
  color: #999999;
}

.trend-filter-icon {
  width: 56rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  background: #f0f2f5;

  &:active {
    background: #e8ecf0;
  }
}

:deep(.trend-filter-popup.right .uni-popup__content-transition) {
  transform: none !important;
}

.filter-drawer {
  width: 630rpx;
  height: calc(100vh - var(--status-bar-height));
  margin-top: var(--status-bar-height);
  background: #f5f5f7;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 28rpx 0 0 28rpx;
}

.drawer-header {
  height: 104rpx;
  padding: 18rpx 34rpx 0;
  background: #ffffff;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.drawer-title {
  color: #1f2937;
  font-size: 34rpx;
  line-height: 1.3;
  font-weight: 700;
}

.drawer-body {
  flex: 1;
  min-height: 0;
  padding: 28rpx 28rpx 0;
  box-sizing: border-box;
}

.drawer-field,
.drawer-switch-field {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx 26rpx;
  margin-bottom: 22rpx;
  box-sizing: border-box;
}

.drawer-field {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.drawer-switch-field {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
}

.drawer-label {
  font-size: 26rpx;
  color: #374151;
  font-weight: 500;
}

.drawer-picker {
  height: 72rpx;
  border: 1rpx solid #d9dde5;
  border-radius: 10rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.drawer-picker-text {
  min-width: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 26rpx;
  color: #1f2937;
}

.drawer-actions {
  flex: 0 0 auto;
  padding: 22rpx 28rpx calc(22rpx + env(safe-area-inset-bottom));
  background: #ffffff;
  display: flex;
  gap: 18rpx;
  box-sizing: border-box;
}

.drawer-action {
  flex: 1;
  height: 76rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: 600;
}

.drawer-action.reset {
  color: #4b5563;
  background: #f3f4f6;
}

.drawer-action.confirm {
  color: #ffffff;
  background: #1a3a5c;
}
.chart-box {
  width: 100%;
  height: 450rpx;
  min-width: 100%;
}

.ranking-scroll {
  width: 100%;
  min-width: 100%;
}

.device-trend-chart-box {
  width: 100%;
  min-width: 100%;
}

.empty-hint {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
}

.empty-hint-text {
  font-size: 26rpx;
  color: #999999;
}
</style>
