<template>
  <view class="main">
    <view class="toptitle">
      <view class="toptitle_left" @click="ht">
        <u-icon name="arrow-left" color="#fff" size="20"></u-icon>
      </view>
      <view class="toptitle_title">设备详情</view>
    </view>

    <view class="box">
      <view class="top">
        <text class="name">{{ detail.sbmc || '-' }}</text>
      </view>
      <view class="row">
        <text class="label">生产厂家</text>
        <text class="value">{{ detail.sccj || '-' }}</text>
      </view>
      <view class="row">
        <text class="label">购入时间</text>
        <text class="value">{{ formatDate(detail.gmsj) }}</text>
      </view>
      <view class="row">
        <text class="label">设备状态</text>
        <view class="value"><text :class="['status-pill', statusClass(detail.sbzt)]">{{ detail.sbzt || '未知状态' }}</text></view>
      </view>
      <view class="divider" />
      <view class="row">
        <text class="label">维护历史</text>
        <text class="value">{{ formatDate(detail.whls) }}</text>
      </view>
      <view class="row">
        <text class="label">维护周期</text>
        <text class="value">{{ detail.whzq || '-' }}</text>
      </view>
      <view class="row">
        <text class="label">维护计划</text>
        <text class="value">{{ formatDate(detail.whjh) || '-' }}</text>
      </view>
      <view class="row">
        <text class="label">备件信息</text>
        <view class="value multiline">{{ stringify(detail.bjxx1) }}</view>
      </view>
      <view class="row" style="display: flex;flex-direction: column;align-items: flex-start;">
        <text class="label">历史故障</text>
        <view class="value" style="margin-top: 5px;" v-html="detail.lsgz"></view>
      </view>
    </view>

    <view class="box">
      <view class="top">
        <text class="name">设备图片</text>
      </view>
      <view class="row" style="flex-direction: column; align-items: flex-start;">
        <view style="width: 100%;">
          <view v-if="images.length" style="display: flex; flex-wrap: wrap; gap: 10px;">
            <image v-for="(img, idx) in images" :key="idx" :src="fullUrl(img.url || img)" mode="widthFix" style="width: 30%; border-radius: 6px;" @click="openImagePreview(idx)" />
          </view>
          <text v-else class="value">-</text>
        </view>
      </view>
    </view>

    <view class="box">
      <view class="top">
        <text class="name">设备资料</text>
      </view>
      <view v-if="files.length" class="row" style="flex-direction: column; align-items: stretch;">
        <view v-for="(file, idx) in files" :key="idx" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
          <view style="display: flex; align-items: center;">
            <image v-if="!isVideoType((file.type || '').toLowerCase())" :src="fileIcon((file.type || '').toLowerCase())" mode="" style="width: 28px; height: 28px; margin-right: 10px;"></image>
            <u-icon v-else name="play-circle-fill" color="#0052D8" size="28" style="margin-right: 10px;"></u-icon>
            <text class="value">{{ file.name || file.title || basename(file.url || file) }}</text>
          </view>
          <view style="display: flex; align-items: center;">
               <u-button size="small" type="primary" text="查看" @click="previewFile(file)"></u-button>
          </view>
        </view>
      </view>
      <view v-else class="row">
        <text class="value">-</text>
      </view>
    </view>
  </view>

</template>

<script>
export default {
  data() {
    return {
      detail: {},
      images: []
      ,
      files: []
    }
  },
  onLoad(options) {
    // 从URL参数获取设备ID
    const deviceId = options.id || options.Id || options.ID
    if (deviceId) {
      this.fetchDeviceDetail(deviceId)
    } else {
      // 兼容旧方式：从缓存读取
      try {
        const raw = uni.getStorageSync('myDeviceDetail')
        if (raw) {
          const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
          const cachedId = parsed.id || parsed.Id || parsed.ID
          if (cachedId) {
            this.fetchDeviceDetail(cachedId)
          } else {
            // 如果没有ID，使用缓存数据（兼容旧版本）
            this.detail = parsed || {}
            this.images = this.parseImageList(this.detail.sbtp || this.detail.tp)
            this.files = this.parseFileList(this.detail.sbzl || this.detail.zl)
          }
        } else {
          uni.showToast({
            icon: 'error',
            title: '缺少设备ID'
          })
        }
      } catch (e) {
        console.error('读取设备详情失败', e)
        uni.showToast({
          icon: 'error',
          title: '加载失败'
        })
      }
    }
  },
  methods: {
    // 获取设备详情
    fetchDeviceDetail(deviceId) {
      uni.showLoading({
        title: '加载中...'
      })
      this.API.hqwdsbxq({ id: deviceId }).then(res => {
        uni.hideLoading()
        console.log('设备详情数据', res)
        if (res && res.code === 200 && res.data) {
          this.detail = res.data || {}
          console.log('设备详情数据详情', this.detail)
          
          // 设备图片：KhsbInfoOutput 中 sbtp 是 List<FileControlsModel>
          // FileControlsModel: { name, fileId, url }
          if (this.detail.sbtp) {
            if (Array.isArray(this.detail.sbtp)) {
              // 如果已经是数组格式（API返回的对象数组）
              this.images = this.detail.sbtp.map(item => {
                if (typeof item === 'string') {
                  return { url: item }
                }
                // FileControlsModel 格式：{ name, fileId, url }
                const url = item.url || ''
                return {
                  url: url,
                  name: item.name || this.basename(url)
                }
              }).filter(img => img.url)
            } else if (typeof this.detail.sbtp === 'string') {
              // 如果是JSON字符串（兼容旧数据）
              const str = this.detail.sbtp.trim()
              if (str) {
                try {
                  const parsed = JSON.parse(str)
                  if (Array.isArray(parsed)) {
                    this.images = parsed.map(item => {
                      if (typeof item === 'string') {
                        return { url: item }
                      }
                      return {
                        url: item.url || '',
                        name: item.name || this.basename(item.url || '')
                      }
                    }).filter(img => img.url)
                  } else {
                    this.images = [{ url: str }]
                  }
                } catch (e) {
                  // 不是JSON，可能是单个URL字符串
                  this.images = [{ url: str }]
                }
              } else {
                this.images = []
              }
            } else {
              this.images = []
            }
          } else {
            this.images = []
          }
          
          // 设备资料：KhsbInfoOutput 中 sbzl 是 List<FileControlsModel>
          if (this.detail.sbzl) {
            if (Array.isArray(this.detail.sbzl)) {
              // 如果已经是数组格式（API返回的对象数组）
              this.files = this.detail.sbzl.map(item => {
                if (typeof item === 'string') {
                  const url = item
                  return {
                    name: this.basename(url),
                    url: url,
                    type: this.extname(url)
                  }
                }
                // FileControlsModel 格式：{ name, fileId, url }
                const url = item.url || ''
                return {
                  name: item.name || this.basename(url),
                  url: url,
                  type: this.extname(url)
                }
              }).filter(file => file.url)
            } else if (typeof this.detail.sbzl === 'string') {
              // 如果是JSON字符串（兼容旧数据）
              this.files = this.parseFileList(this.detail.sbzl)
            } else {
              this.files = []
            }
          } else {
            this.files = []
          }
          
          console.log('解析后的图片', this.images)
          console.log('解析后的资料', this.files)
        } else {
          uni.showToast({
            icon: 'error',
            title: res?.msg || '获取设备详情失败'
          })
        }
      }).catch(err => {
        uni.hideLoading()
        console.error('获取设备详情失败', err)
        uni.showToast({
          icon: 'error',
          title: '加载失败，请重试'
        })
      })
    },
    ht(){
      uni.navigateBack({ delta: 1 })
    },
    // 解析设备资料列表，统一结构为 {name, url, type}
    parseFileList(v) {
      const arr = []
      if (v === null || v === undefined) return arr
      let list = null
      if (typeof v === 'string') {
        const s = v.trim()
        if (!s) return arr
        try { list = JSON.parse(s) } catch (e) { list = [s] }
      } else if (Array.isArray(v)) {
        list = v
      } else {
        return arr
      }
      for (const it of list) {
        if (typeof it === 'string') {
          const url = it
          arr.push({ name: this.basename(url), url, type: this.extname(url) })
          continue
        }
        const url = it.url || ''
        const name = it.name || it.title || this.basename(url)
        let type = (it.type || '').toLowerCase()
        if (!type) type = this.extname(url)
        arr.push({ name, url, type })
      }
      return arr
    },
    extname(url) {
      if (!url) return ''
      const i = url.lastIndexOf('.')
      if (i === -1) return ''
      return url.substring(i + 1).toLowerCase()
    },
    basename(url) {
      if (!url) return ''
      try {
        const u = url.split('?')[0]
        return u.substring(u.lastIndexOf('/') + 1)
      } catch { return url }
    },
    fileIcon(type) {
      if (!type) return '/static/WORD.png'
      if (type === 'pdf') return '/static/PDF.png'
      if (type === 'doc' || type === 'docx') return '/static/WORD.png'
      if (type === 'xlsx' || type === 'xls') return '/static/WORD.png'
      if (type === 'png' || type === 'jpg' || type === 'jpeg') return '/static/img/picture.png'
      return '/static/WORD.png'
    },
    formatDate(ts) {
      if (!ts) return '-'
      const d = new Date(ts)
      if (isNaN(d.getTime())) return String(ts)
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    statusClass(status) {
      if (status === null || status === undefined) return 'status-unknown'
      const s = String(status).trim().toLowerCase()
      const num = Number(s)
      if (!isNaN(num)) {
        if (num === 1) return 'status-running'
        if (num === 2) return 'status-repair'
        if (num === 3) return 'status-stop'
        if (num === 4) return 'status-scrap'
      }
      if (s.includes('运')) return 'status-running'
      if (s.includes('检') || s.includes('修')) return 'status-repair'
      if (s.includes('停') || s.includes('关')) return 'status-stop'
      if (s.includes('废')) return 'status-scrap'
      if (s.includes('running') || s.includes('run') || s.includes('online')) return 'status-running'
      if (s.includes('repair') || s.includes('maint') || s.includes('maintenance') || s.includes('fix')) return 'status-repair'
      if (s.includes('stop') || s.includes('down') || s.includes('offline')) return 'status-stop'
      if (s.includes('scrap') || s.includes('decomm')) return 'status-scrap'
      return 'status-unknown'
    },
    stringify(v) {
      if (!v) return '-'
      if (Array.isArray(v)) return v.join('、')
      if (typeof v === 'object') return Object.values(v).join('、') || '-'
      return String(v)
    },
    isString(v) { return typeof v === 'string' },
    fullUrl(url) {
      if (!url) return ''
      // 兼容后端返回相对路径
      if (/^https?:\/\//.test(url)) return url
      const base = 'https://hhjj.antissoft.com'
      return base + url
    },
    openImagePreview(idx){
      const urls = (this.images || []).map(img => this.fullUrl(img.url || img)).filter(u => !!u)
      if (!urls.length) return
      uni.previewImage({ current: idx, urls })
    },
    // 解析图片字段：支持 null、空串、JSON 字符串、数组
    parseImageList(v) {
      if (v === null || v === undefined) return []
      if (typeof v === 'string') {
        const s = v.trim()
        if (!s) return []
        try {
          const parsed = JSON.parse(s)
          if (Array.isArray(parsed)) {
            return parsed.map(item => {
              if (typeof item === 'string') {
                return { url: item }
              }
              return {
                url: item.url || '',
                name: item.name || this.basename(item.url || '')
              }
            }).filter(img => img.url)
          }
          return []
        } catch (e) {
          // 不是 JSON，可能是单个 url 字符串
          return [{ url: s }]
        }
      }
      if (Array.isArray(v)) {
        return v.map(item => {
          if (typeof item === 'string') {
            return { url: item }
          }
          return {
            url: item.url || '',
            name: item.name || this.basename(item.url || '')
          }
        }).filter(img => img.url)
      }
      // 非字符串非数组，无法解析
      return []
    },
    // 判断是否为视频类型
    isVideoType(type) {
      const videoTypes = ['mp4', 'mov', 'avi', 'wmv', 'mkv', 'webm', 'mpeg', 'mpg', 'flv', '3gp'];
      return videoTypes.includes((type || '').toLowerCase());
    },
    // 判断是否为图片类型
    isImageType(type) {
      const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];
      return imageTypes.includes((type || '').toLowerCase());
    },
    // 判断是否为PDF类型
    isPdfType(type) {
      return (type || '').toLowerCase() === 'pdf';
    },
    // 统一文件预览方法（在线预览，不支持下载）
    previewFile(file) {
      const url = this.fullUrl(file.url || file)
      const type = (file.type || '').toLowerCase() || url.substring(url.lastIndexOf('.') + 1).toLowerCase()
      
      // 图片预览
      if (this.isImageType(type)) {
        uni.previewImage({ current: 0, urls: [url] })
        return
      }
      
      // PDF预览
      if (this.isPdfType(type)) {
        uni.setStorageSync('wjurl', url)
        uni.navigateTo({ url: '/pages/pdf/pdf' })
        return
      }
      
      // 视频预览
      if (this.isVideoType(type)) {
        uni.setStorageSync('videoUrl', url)
        uni.setStorageSync('videoName', file.name || '视频')
        uni.navigateTo({
          url: '/pages/new/zlgl/video-preview'
        })
        return
      }
      
      // 其他文件类型（Word、Excel等）提示不支持在线预览
      uni.showToast({
        title: '该文件类型暂不支持在线预览',
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import './detail.scss';
</style>