<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200">
    <div class="single-device-dialog">
      <div class="single-device-dialog__header">
        <div>{{ t('DataCollection.RealTimeMonitoring.dialogDeviceNameLabel') }}{{ deviceName || '-' }}</div>
        <div>{{ t('DataCollection.RealTimeMonitoring.dialogCollectionTimeLabel') }}{{ displayTime }}</div>
      </div>
      <ContentWrap v-loading="loading">
        <div v-if="sections.length" class="single-device-dialog__table-grid">
          <div v-for="section in sections" :key="section.key" class="single-device-dialog__section">
            <div class="single-device-dialog__section-title">
              {{ section.title }}
            </div>
            <el-empty
              v-if="!section.columns.length"
              :description="t('DataCollection.RealTimeMonitoring.emptyDescription')"
            />
            <el-table
v-else :data="section.rows" :border="true" :header-cell-style="headerCellStyle"
              :cell-style="bodyCellStyle" size="small">
              <el-table-column
v-for="col in section.columns" :key="col.prop" :prop="col.prop" :label="col.label"
                align="center">
                <template #default="scope">
                  <span>{{ formatCell(scope.row[col.prop]) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <el-empty
          v-else
          :description="t('DataCollection.RealTimeMonitoring.emptyDescription')"
        />
      </ContentWrap>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import { DeviceApi } from '@/api/iot/device'

type SectionColumn = {
  prop: string
  label: string
}

type SectionRow = Record<string, string | number | null>

type Section = {
  key: string
  title: string
  columns: SectionColumn[]
  rows: SectionRow[]
}

const { t } = useI18n()

const props = defineProps<{
  modelValue: boolean
  deviceId?: string | number
  deviceName?: string
  collectionTime?: string | number
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const dialogVisible = computed({
  get() {
    return props.modelValue
  },
  set(value: boolean) {
    emit('update:modelValue', value)
  }
})

const dialogTitle = computed(() => {
  return t('DataCollection.RealTimeMonitoring.dialogTitle')
})

const loading = ref(false)
const deviceName = computed(() => props.deviceName)
const sections = ref<Section[]>([])

const toGroupMap = (value: any): Record<string, any[]> => {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return {}
  }
  const entries = Object.entries(value).filter(([, v]) => Array.isArray(v))
  if (!entries.length) {
    return {}
  }
  const map: Record<string, any[]> = {}
  for (const [k, v] of entries) {
    map[k] = v as any[]
  }
  return map
}

const displayTime = computed(() => {
  if (!props.collectionTime) {
    return '-'
  }
  const value = props.collectionTime
  if (typeof value === 'number') {
    return formatDate(new Date(value))
  }
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return value
  }
  return formatDate(date)
})

const headerCellStyle = () => {
  return {
    fontWeight: 500,
    padding: '6px 4px',
    background: '#f5f7fa'
  }
}

const bodyCellStyle = () => {
  return {
    padding: '4px 4px'
  }
}

const formatCell = (value: string | number | null | undefined) => {
  if (value === null || value === undefined) {
    return ''
  }
  return value
}

const buildSectionsFromGroups = (groups: Record<string, any[]>): Section[] => {
  const result: Section[] = []
  for (const [key, list] of Object.entries(groups)) {
    const columns: SectionColumn[] = []
    const row: SectionRow = {}
    if (Array.isArray(list) && list.length) {
      list.forEach((item: any, index: number) => {
        const prop = `col${index}`
        const label =
          item?.attributeName ?? `${t('DataCollection.RealTimeMonitoring.defaultFieldLabelPrefix')}${index + 1}`
        columns.push({ prop, label })
        row[prop] = item?.addressValue ?? ''
      })
    }
    result.push({
      key,
      title: key,
      columns,
      rows: columns.length ? [row] : []
    })
  }
  return result
}

const fetchList = async () => {
  if (props.deviceId === undefined || props.deviceId === null || props.deviceId === '') {
    sections.value = []
    return
  }
  loading.value = true
  try {
    const res: any = await DeviceApi.getSingleDevice({ deviceId: props.deviceId })
    const groups = Array.isArray(res)
      ? { [t('DataCollection.RealTimeMonitoring.defaultGroupName')]: res }
      : {
          ...toGroupMap(res?.data),
          ...toGroupMap(res?.data?.data),
          ...toGroupMap(res)
        }
    sections.value = buildSectionsFromGroups(groups)
  } finally {
    loading.value = false
  }
}

watch(
  () => [props.modelValue, props.deviceId],
  ([visible]) => {
    if (!visible) {
      return
    }
    fetchList()
  }
)
</script>

<style scoped>
.single-device-dialog {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.single-device-dialog__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.single-device-dialog__table-grid {
  display: grid;
  grid-template-columns: repeat(1, minmax(0, 1fr));
  gap: 12px;
}

.single-device-dialog__section-title {
  margin-bottom: 4px;
  font-size: 13px;
  color: var(--el-text-color-primary);
}

.single-device-dialog__section :deep(.el-table__inner-wrapper) {
  border-radius: 0;
}
</style>
