<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.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 v-for="section in sections" :key="section.id" class="form-section">
              <h3 v-if="section.title" class="section-title">{{ section.title }}</h3>

              <div class="form-grid">
                <div
                  v-for="item in section.items"
                  :key="item.prop"
                  class="form-item"
                >
                  <div class="form-label">{{ item.label }}:</div>
                  <div class="form-value">{{ formatCellTwo(item.value) }}</div>
                </div>
              </div>
            </div>
<!--          </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 = {
  id: number
  title?: string
  items: FormItem[]
}
interface FormItem {
  prop: string
  label: string
  value: any
}

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[]>([
  {
    id: 1,
    title: '工艺参数监控',
    items: [
      { prop: 'addressValue', label: '系统运行', value: 1, unit: '℃' },
      { prop: 'attributeName', label: '烘干湿度', value: 2, unit: '%' },
      { prop: 'attributeName', label: '输送速度', value: 3, unit: 'm/min' },
      { prop: 'attributeName', label: '回风温度', value: 4, unit: '℃' },
      { prop: 'attributeName', label: '排风温度', value: 5, unit: '℃' },
      { prop: 'attributeName', label: '呼叫状态', value: 6 },
      { prop: 'attributeName', label: '在线状态', value: 7 },
      { prop: 'attributeName', label: '运行状态', value: 3 },
      { prop: 'attributeName', label: '主缸速度', value: 0, unit: '%' },
      { prop: 'attributeName', label: '提布辊速度', value: 0 },
      { prop: 'fanSpeed', label: '风机速度', value: '暂无数据' },
      { prop: 'mainLevel', label: '主缸水位', value: 1, unit: '%' },
      { prop: 'mainWater', label: '主缸水量', value: 145, unit: 'L' },
      { prop: 'setTemp', label: '设定温度', value: 0.0, unit: '℃' },
      { prop: 'actualTemp', label: '实际温度', value: 0.0, unit: '℃' },
    ],
  },
])

const formatValue = (item: FormItem) => {
  let value = item.value
  if (value === null || value === undefined) return '--'

  if (typeof value === 'number') {
    value = Number.isInteger(value) ? value.toString() : value.toFixed(2)
  }

  if (item.unit) {
    value += ` ${item.unit}`
  }

  return value
}
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 formatCellTwo = (value: any) => {
  // 示例：如果是数字保留两位小数，否则原样返回
  if (typeof value === 'number') {
    return value.toFixed(2)
  }
  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.getSingleDeviceFrom({ 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)*/
    sections.value = res
  } 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;
}

/* 表单容器 */
.form-section {
  margin-bottom: 24px;
}

/* 标题样式 */
.section-title {
  font-size: 13px;
  font-weight: bold;
  margin-bottom: 12px;
  color: var(--el-text-color-primary);
}

/* 三列网格容器 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 三列等宽 */
  /*gap: 16px;*/ /* 列间距和行间距 */
 /* padding: 8px;*/
  background-color: #fff;
/*  border: 1px solid #dcdfe6; !* 外边框 *!*/
  border-radius: 4px;
  min-height: 35px;
}

/* 表单项：标签 + 值 */
.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  min-height: 35px;
 /* padding: 8px 0;*/
  border: 1px solid #dcdfe6;
 /* border-right: 1px solid #dcdfe6; !* 右边框 *!
  border-bottom: 1px solid #dcdfe6; !* 下边框 *!*/
}

/* 标签样式 */
.form-label {
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  height: 100%;
  min-height: 35px;
  width: 150px; /* 固定标签宽度，避免错位 */
  background-color: #f5f7fa; /* 背景色 */
}

/* 值样式 */
.form-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 6px 12px;
  background: white;
  min-height: 35px;
  box-sizing: border-box;
  overflow: hidden;
  cursor: default;
  transition: all 0.2s;
}

/* 响应式：小屏幕下改为两列或单列 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: repeat(2, 1fr); /* 平板改为两列 */
  }
}

@media (max-width: 480px) {
  .form-grid {
    grid-template-columns: 1fr; /* 手机改为单列 */
  }
}
</style>
