<template>
  <Dialog v-model="dialogVisible"
          :title="t('monitor.details')"
          style="width: 1500px"
          class="fixed-height-dialog"
          @close="handleClose" >
      <ContentWrap>
        <!-- 添加表格容器并设置滚动 -->
        <el-table
          v-loading="loading"
          :data="paginatedList"
          :stripe="true"
          :show-overflow-tooltip="true"
          style="width: 100%"
          height="100%"
          class="scrollable-table"
        >
          <el-table-column :label="t('iotDevice.code')" align="center" prop="deviceCode" />
          <el-table-column :label="t('iotDevice.name')" align="center" prop="deviceName" />
          <el-table-column :label="t('operationFillForm.sumTime')" align="center" prop="totalRunTime" >
            <template #default="{ row }">
              {{ row.totalRunTime ?? row.tempTotalRunTime }}
            </template>
          </el-table-column>
          <el-table-column :label="t('operationFillForm.sumKil')" align="center" prop="totalMileage" >
            <template #default="{ row }">
              {{ row.totalMileage ?? row.tempTotalMileage }}
            </template>
          </el-table-column>
          <el-table-column :label="t('mainPlan.MaintItems')" align="center" prop="name" />

          <template v-if="showTimeColumns">
            <el-table-column :label="t('mainPlan.lastMaintenanceOperationTime')" align="center" prop="lastRunningTime" />
            <el-table-column :label="t('mainPlan.RunTimeCycle')" align="center" prop="nextRunningTime" />
            <el-table-column :label="t('mainPlan.nextMaintTime')" align="center" prop="timePeriod" />
          </template>

          <template v-if="showMileageColumns">
            <el-table-column :label="t('mainPlan.lastMaintenanceMileage')" align="center" prop="lastRunningKilometers" />
            <el-table-column :label="t('mainPlan.operatingMileageCycle')" align="center" prop="nextRunningKilometers" />
            <el-table-column :label="t('mainPlan.nextMaintKil')" align="center" prop="kilometerCycle" />
          </template>

          <template v-if="showNaturalDateColumns">
            <el-table-column :label="t('mainPlan.lastMaintenanceOperationTime')" align="center" prop="lastNaturalDate"  width="220">
              <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: 60%"
                  :disabled="true"
                />
              </template>
            </el-table-column>
            <el-table-column :label="t('mainPlan.NaturalDailyCycle')" align="center" prop="nextNaturalDate" />
            <el-table-column :label="t('mainPlan.nextMaintDate')" align="center" prop="naturalDatePeriod" />
          </template>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </ContentWrap>
  </Dialog>
</template>

<script setup lang="ts">
import { DictDataVO } from '@/api/system/dict/dict.data'
import dayjs from 'dayjs'
import { IotMainWorkOrderBomApi, IotMainWorkOrderBomVO } from '@/api/pms/iotmainworkorderbom'
import { IotMaintenanceBomApi, IotMaintenanceBomVO } from '@/api/pms/iotmaintenancebom'
import {propTypes} from "@/utils/propTypes";
const { t } = useI18n() // 国际化
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 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, deviceId?: number) => {
  await nextTick() // 确保DOM更新完成
  queryParams.deviceId = 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 handleClose = () => {
  // 重置状态避免多个弹窗出现
  dialogVisible.value = false
  loading.value = false
  list.value = []

  // 通知父组件弹窗已关闭
  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()
}

</script>

<style lang="scss" scoped>
/* 新版CSS解决方案 */
.fixed-height-dialog :deep(.el-dialog) {
  width: 1500px !important; /* 合并原内联样式 */
  height: 800px !important; /* 关键：固定高度 */
  display: flex;
  flex-direction: column;
}

.fixed-height-dialog :deep(.el-dialog__header) {
  padding: 20px;
  flex-shrink: 0; /* 防止标题栏压缩 */
}

.fixed-height-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow: hidden; /* 隐藏外层滚动 */
  padding: 10px 20px; /* 适当内边距 */
}

/* 表格滚动核心 */
.scrollable-table {
  height: 100% !important;

  :deep(.el-table__body-wrapper) {
    overflow-y: auto !important;
    max-height: calc(100% - 40px); /* 扣除表头高度 */
  }

  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
  }
}
</style>
