<template>
  <Dialog
    v-model="dialogVisible"
    :title="t('monitor.details')"
    :width="dialogWidth"
    class="device-alarm-detail-dialog"
    @close="handleClose">
    <template #title>
      <div class="dialog-title">
        <div class="dialog-title__icon"><Icon icon="ep:calendar" /></div>
        <div>
          <div class="dialog-title__text">{{ t('monitor.details') }}</div>
          <div class="dialog-title__subtitle">查看设备保养项目及各维度保养里程</div>
        </div>
      </div>
    </template>

    <div class="dialog-content">
      <section v-if="deviceInfo" class="device-info-section">
        <div class="section-heading"><span></span>设备信息</div>
        <div class="device-info-grid">
          <div class="info-item">
            <span class="info-label">{{ t('iotDevice.code') }}</span>
            <span class="info-value">{{ deviceInfo.deviceCode }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">{{ t('iotDevice.name') }}</span>
            <span class="info-value">{{ deviceInfo.deviceName }}</span>
          </div>
          <div class="info-item" v-if="deviceInfo.model">
            <span class="info-label">{{ t('deviceForm.model') }}</span>
            <span class="info-value">{{ deviceInfo.model }}</span>
          </div>
        </div>
      </section>

      <section class="maintenance-section">
        <div class="section-heading"><span></span>保养项目</div>
        <div class="table-container">
          <ZmTable
            :loading="loading"
            :data="paginatedList"
            :show-border="true"
            settings-cache-key="pms-device-maintenance-alarm-detail">
            <ZmTableColumn
              :label="t('iotDevice.code')"
              align="center"
              prop="deviceCode"
              v-if="false" />
            <ZmTableColumn
              :label="t('iotDevice.name')"
              align="center"
              prop="deviceName"
              v-if="false" />
            <ZmTableColumn :label="t('mainPlan.MaintItems')" align="center" prop="name" />

            <ZmTableColumn
              :label="t('operationFillForm.sumTime')"
              align="center"
              prop="totalRunTime">
              <template #default="{ row }">
                {{ row.totalRunTime ?? row.tempTotalRunTime }}
              </template>
            </ZmTableColumn>
            <ZmTableColumn
              :label="t('operationFillForm.sumKil')"
              align="center"
              prop="totalMileage">
              <template #default="{ row }">
                {{ row.totalMileage ?? row.tempTotalMileage }}
              </template>
            </ZmTableColumn>

            <!-- 时间分组列 -->
            <ZmTableColumn v-if="showTimeColumns" label="保养时长" align="center">
              <ZmTableColumn
                :label="t('mainPlan.lastMaintenanceOperationTime')"
                align="center"
                prop="lastRunningTime" />
              <ZmTableColumn
                :label="t('mainPlan.RunTimeCycle')"
                align="center"
                prop="nextRunningTime" />
              <ZmTableColumn :label="t('mainPlan.nextMaintTime')" align="center" prop="timePeriod">
                <template #default="{ row }">
                  <span :class="{ 'negative-value': isNegative(row.timePeriod) }">
                    {{ row.timePeriod }}
                  </span>
                </template>
              </ZmTableColumn>
            </ZmTableColumn>

            <!-- 里程分组列 -->
            <ZmTableColumn v-if="showMileageColumns" label="保养里程" align="center">
              <ZmTableColumn
                :label="t('mainPlan.lastMaintenanceMileage')"
                align="center"
                prop="lastRunningKilometers" />
              <ZmTableColumn
                :label="t('mainPlan.operatingMileageCycle')"
                align="center"
                prop="nextRunningKilometers" />
              <ZmTableColumn
                :label="t('mainPlan.nextMaintKil')"
                align="center"
                prop="kilometerCycle">
                <template #default="{ row }">
                  <span :class="{ 'negative-value': isNegative(row.kilometerCycle) }">
                    {{ row.kilometerCycle }}
                  </span>
                </template>
              </ZmTableColumn>
            </ZmTableColumn>

            <!-- 日期分组列 -->
            <ZmTableColumn v-if="showNaturalDateColumns" label="保养日期" align="center">
              <ZmTableColumn
                :label="t('mainPlan.lastMaintenanceNaturalDate')"
                align="center"
                prop="lastNaturalDate"
                min-width="160">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.lastNaturalDate"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    :disabled="true" />
                </template>
              </ZmTableColumn>
              <ZmTableColumn
                :label="t('mainPlan.NaturalDailyCycle')"
                align="center"
                prop="nextNaturalDate" />
              <ZmTableColumn
                :label="t('mainPlan.nextMaintDate')"
                align="center"
                prop="naturalDatePeriod" />
            </ZmTableColumn>
          </ZmTable>
        </div>
        <Pagination
          class="mr-4"
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination" />
      </section>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { DictDataVO } from '@/api/system/dict/dict.data'
import dayjs from 'dayjs'
import { IotMainWorkOrderBomApi } from '@/api/pms/iotmainworkorderbom'
import { IotMaintenanceBomApi, IotMaintenanceBomVO } from '@/api/pms/iotmaintenancebom'
import { propTypes } from '@/utils/propTypes'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { t } = useI18n() // 国际化
const { ZmTable, ZmTableColumn } = useTableComponents<IotMaintenanceBomVO>()
const emit = defineEmits(['close']) // 定义 success 事件，用于操作成功后的回调
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<IotMaintenanceBomVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// 分页重置标志
const shouldResetPagination = ref(false)

// 添加外部传入的设备信息
const externalDeviceInfo = ref(null)

const dialogWidth = 'min(1200px, 92vw)'

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  workOrderId: undefined,
  planId: undefined,
  deviceId: undefined
})

const props = defineProps({
  flag: propTypes.oneOfType<string | string[]>([String, Array<String>]).isRequired
})

const selectedRow = ref(null)

// 处理单选逻辑
const selectRow = (row) => {
  selectedRow.value = selectedRow.value?.id === row.id ? null : row
  emit('choose', row)
  dialogVisible.value = false
}

// 分页事件处理
const handlePagination = () => {
  console.log('分页变化，当前页：', queryParams.pageNo)
}

// 分页计算属性
const paginatedList = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize
  const end = start + queryParams.pageSize
  return list.value.slice(start, end)
})

const open = async (id?: number, flag?: string, deviceInfo?: any) => {
  // 重置分页参数
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  list.value = [] // 清空列表避免显示旧数据
  total.value = 0

  await nextTick() // 确保DOM更新完成
  if (deviceInfo) {
    externalDeviceInfo.value = deviceInfo
    queryParams.deviceId = deviceInfo.deviceId // 如果需要的话
  }
  if ('workOrder' === flag) {
    // 加载保养工单 BOM
    queryParams.workOrderId = id
    queryParams.planId = undefined
    await getWorkOrderList()
  } else if ('plan' === flag) {
    queryParams.planId = id
    queryParams.workOrderId = undefined
    await getPlanList()
  }
  dialogVisible.value = true
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const getWorkOrderList = async () => {
  loading.value = true
  try {
    const data = await IotMainWorkOrderBomApi.getWorkOrderBOMs(queryParams)
    // 格式化日期字段
    data.forEach((item) => {
      if (item.lastNaturalDate) {
        // 将时间戳转换为 YYYY-MM-DD 格式
        item.lastNaturalDate = dayjs(item.lastNaturalDate).format('YYYY-MM-DD')
      } else {
        // 处理空值情况
        item.lastNaturalDate = ''
      }
      // 计算下次保养运行时长 H
      item.timePeriod = calculateTimePeriod(item)
      // 计算下次保养公里数 KM
      item.kilometerCycle = calculateKiloPeriod(item)
      // 计算下次保养日期
      item.naturalDatePeriod = calculateNextNaturalDate(item)
    })
    list.value = data
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getPlanList = async () => {
  loading.value = true
  try {
    const data = await IotMaintenanceBomApi.getMainPlanBOMs(queryParams)
    // 格式化日期字段
    data.forEach((item) => {
      if (item.lastNaturalDate) {
        // 将时间戳转换为 YYYY-MM-DD 格式
        item.lastNaturalDate = dayjs(item.lastNaturalDate).format('YYYY-MM-DD')
      } else {
        // 处理空值情况
        item.lastNaturalDate = ''
      }
      // 计算下次保养运行时长 H
      item.timePeriod = calculateTimePeriod(item)
      // 计算下次保养公里数 KM
      item.kilometerCycle = calculateKiloPeriod(item)
      // 计算下次保养日期
      item.naturalDatePeriod = calculateNextNaturalDate(item)
    })
    list.value = data
    total.value = data.length
  } finally {
    loading.value = false
  }
}

// 添加设备信息计算属性
const deviceInfo = computed(() => {
  // 优先使用外部传入的设备信息
  if (externalDeviceInfo.value) {
    return externalDeviceInfo.value
  }
  if (list.value.length > 0) {
    const firstRecord = list.value[0]
    return {
      deviceCode: firstRecord.deviceCode,
      deviceName: firstRecord.deviceName,
      model: firstRecord.model // 确保列表数据中也有 model
    }
  }
  return null
})

const handleClose = () => {
  // 重置状态避免多个弹窗出现
  dialogVisible.value = false
  loading.value = false
  list.value = []

  total.value = 0
  queryParams.pageNo = 1
  queryParams.pageSize = 10

  // 通知父组件弹窗已关闭
  emit('close')
}

// 计算 距离下次保养运行时长 H
const calculateTimePeriod = (item: IotMaintenanceBomVO) => {
  if (item.runningTimeRule === 0) {
    const totalRunVal = item.totalRunTime ?? item.tempTotalRunTime
    const next = Number(item.nextRunningTime) || 0
    const totalRun = totalRunVal != null ? Number(totalRunVal) : 0
    const lastRun = Number(item.lastRunningTime) || 0
    const result = next - (totalRun - lastRun)
    return Number(result.toFixed(2))
  }
  return typeof item.timePeriod === 'number' ? Number(item.timePeriod.toFixed(2)) : item.timePeriod
}

// 计算 距离下次保养公里数 KM
const calculateKiloPeriod = (item: IotMaintenanceBomVO) => {
  if (item.mileageRule === 0) {
    const totalRunVal = item.totalMileage ?? item.tempTotalMileage
    const next = Number(item.nextRunningKilometers) || 0
    const totalRun = totalRunVal != null ? Number(totalRunVal) : 0
    const lastRun = Number(item.lastRunningKilometers) || 0
    const result = next - (totalRun - lastRun)
    return Number(result.toFixed(2))
  }
  return typeof item.kilometerCycle === 'number'
    ? Number(item.kilometerCycle.toFixed(2))
    : item.kilometerCycle
}

// 计算下次保养日期
const calculateNextNaturalDate = (item: IotMaintenanceBomVO): string => {
  if (item.naturalDateRule !== 0 || !item.lastNaturalDate || !item.nextNaturalDate) {
    return '-'
  }
  return dayjs(item.lastNaturalDate).add(item.nextNaturalDate, 'day').format('YYYY-MM-DD')
}

// 计算属性：控制时间相关列的显示
const showTimeColumns = computed(() => {
  return paginatedList.value.some((item) => item.runningTimeRule === 0)
})

// 计算属性：控制里程相关列的显示
const showMileageColumns = computed(() => {
  return paginatedList.value.some((item) => item.mileageRule === 0)
})

// 计算属性：自然日期相关列的显示
const showNaturalDateColumns = computed(() => {
  return paginatedList.value.some((item) => item.naturalDateRule === 0)
})

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  // getList()
}
const choose = (row: DictDataVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 判断是否为负数的辅助函数
const isNegative = (value: any): boolean => {
  if (value === null || value === undefined || value === '') return false
  const num = Number(value)
  return !isNaN(num) && num < 0
}
</script>

<style lang="scss" scoped>
@media (width <= 768px) {
  .dialog-title__subtitle {
    display: none;
  }

  .device-info-grid {
    grid-template-columns: minmax(0, 1fr);
    padding: 12px;
  }

  .maintenance-section .table-container {
    padding-right: 12px;
    padding-left: 12px;
  }
}

.device-info-card {
  display: flex;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 8%);
  flex-wrap: wrap;
  gap: 24px; /* 项间距 */

  .info-item {
    display: flex;
    align-items: center;

    .info-label {
      margin-right: 8px;
      font-weight: 600;
      color: #606266;
      white-space: nowrap;
    }

    .info-value {
      min-width: 200px;
      padding: 4px 12px;
      font-weight: 500;
      color: #303133;
      background: #fff;
      border: 1px solid #ebeef5;
      border-radius: 4px;
    }
  }
}

/* 负数值样式 */
.negative-value {
  font-weight: 600;
  color: #f56c6c;
}

.dialog-title {
  display: flex;
  align-items: center;
  min-width: 0;
}

.dialog-title__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 38px;
  margin-right: 12px;
  font-size: 18px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 8px;
}

.dialog-title__text {
  font-size: 17px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
}

.dialog-title__subtitle {
  margin-top: 1px;
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.device-info-section,
.maintenance-section {
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.section-heading {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  font-size: 15px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.section-heading span {
  width: 4px;
  height: 17px;
  margin-right: 9px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.device-info-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
  padding: 14px 16px;
}

.device-info-grid .info-item {
  display: flex;
  align-items: center;
  min-width: 0;
  padding: 10px 12px;
  background: var(--el-fill-color-extra-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
}

.device-info-grid .info-label {
  flex: 0 0 auto;
  margin-right: 10px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}

.device-info-grid .info-value {
  min-width: 0;
  overflow: hidden;
  font-weight: 500;
  color: var(--el-text-color-primary);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.maintenance-section .table-container {
  padding: 14px 16px 0;
}

/* 设备信息卡片样式 */
</style>
