<template>
  <view class="page-container">
    <view class="error" v-if="!maintenanceInfo?.data">
      {{ maintenanceInfo?.msg || '未查询到维修信息' }}
    </view>
    <view v-else>
      <view class="maintenance-item card" v-for="item in maintenanceInfo.data" :key="item.id || item.maintenanceDate">
        <view class="popup-text">资产名称：{{ item.assetName }}</view>
        <view class="popup-text">维修日期：{{ item.maintenanceDate }}</view>
        <view class="popup-text">维修费用：{{ item.maintenanceCost }}</view>
        <view class="popup-text">维修单位：{{ item.maintenanceDapartment }}</view>
        <view class="popup-text">维修人员：{{ item.maintenanceMan }}</view>
        <view class="popup-text">联系方式：{{ item.maintenancePhone }}</view>
        <view class="popup-text">登记人员：{{ item.registrantName }}</view>
        <view class="popup-text">登记日期：{{ item.registrantDate }}</view>
        <view class="popup-text">备注：{{ item.note }}</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
// @ts-ignore JS模块无类型声明
import { fetchMaintenanceInfoById } from '@/pages/api/fixedAssets.js'

const maintenanceInfo = ref<any>({})
const assetId = ref<string | number | null>(null)

onLoad((options?: Record<string, any>) => {
  // 1) 优先从路由参数读取 assetId
  const fromQuery = options?.assetId || options?.assetid
  if (fromQuery) {
    assetId.value = fromQuery
  }

  // 2) 回退：监听 eventChannel（兼容旧的跳转方式）
  if (!assetId.value) {
    const pages = getCurrentPages()
    // @ts-ignore uni-app 小程序端提供，类型定义里可能缺失
    const eventChannel = (pages[pages.length - 1] as any)?.getOpenerEventChannel?.()
    eventChannel?.on('sendData', (res: any) => {
      const data = res?.data || {}
      assetId.value = data.assetId || data.assetid || null
      if (assetId.value) fetchById(assetId.value)
    })
  }
})

onShow(() => {
  // 页面可见时，如果已拿到 assetId 且还未加载数据，则发起请求
  if (assetId.value && !maintenanceInfo.value?.data) {
    fetchById(assetId.value)
  }
})

async function fetchById(id: string | number) {
  try {
    const data: any = await fetchMaintenanceInfoById(id)
    maintenanceInfo.value = data
  } catch (e) {
    console.error('获取数据失败', e)
    maintenanceInfo.value = { msg: '获取数据失败' }
  }
}
</script>

<style scoped>
.page-container { padding: 24rpx; }
.card { background: #fff; border-radius: 20rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.06); padding: 20rpx; margin-bottom: 16rpx; }
.popup-text { font-size: 24rpx; color: #333; margin-top: 6rpx; }
.error { color: #ef5350; background: #fff; border-radius: 12rpx; padding: 20rpx; }
</style>
