<template>
  <view :class="pageRootClass" class="tab-page lrd-page">
    <view v-if="loading" class="lrd-state">
      <text class="text-body lrd-state__txt">{{ $t('livestockResourceDetailPage.loading') }}</text>
    </view>
    <view v-else-if="loadError" class="lrd-state">
      <text class="text-body lrd-state__txt">{{ loadError }}</text>
    </view>
    <scroll-view v-else scroll-y class="lrd-scroll" enable-back-to-top>
      <view class="lrd-inner">
        <text class="lrd-title">{{ displayTitle }}</text>

        <view class="lrd-meta">
          <text v-if="typeLabel" class="lrd-meta__tag text-body">{{ typeLabel }}</text>
          <text v-if="publishTime" class="lrd-meta__date text-body">{{ publishTime }}</text>
        </view>

        <view v-if="showCoverSection" class="lrd-section">
          <text class="lrd-section__label text-title">{{ $t('newsDetailPage.coverTitle') }}</text>
          <view v-if="hasCover" class="lrd-cover-wrap" role="button" @click="onPreviewCover">
            <image class="lrd-cover" :src="coverSrc" mode="aspectFit" />
          </view>
          <text v-else class="text-body lrd-muted">{{ $t('newsDetailPage.noCover') }}</text>
        </view>

        <view class="lrd-section">
          <text class="lrd-section__label text-title">{{ $t('newsDetailPage.introTitle') }}</text>
          <text class="text-body lrd-intro">{{ introText }}</text>
        </view>

        <view v-if="showVideoSection" class="lrd-section">
          <text class="lrd-section__label text-title">{{ $t('livestockResourceDetailPage.videoTitle') }}</text>
          <view v-if="videoSrc" class="lrd-video-wrap">
            <video
              class="lrd-video"
              :src="videoSrc"
              :poster="hasCover ? coverSrc : ''"
              controls
              object-fit="contain"
              :enable-progress-gesture="true"
              :show-center-play-btn="true"
            />
          </view>
          <text v-else class="text-body lrd-muted">{{ $t('livestockResourceDetailPage.noVideo') }}</text>
        </view>

        <view v-if="detailRows.length" class="lrd-section">
          <text class="lrd-section__label text-title">{{ $t('livestockResourceDetailPage.sectionInfo') }}</text>
          <view v-for="(row, idx) in detailRows" :key="idx" class="lrd-kv">
            <text class="lrd-kv__label text-body">{{ row.label }}</text>
            <text class="lrd-kv__value text-body">{{ row.value }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import tabPage from '@/mixins/tabPage'
import { getLivestockResourceDetail } from '@/api/livestockResource'
import { resolveResourceUrl } from '@/utils/resourceUrl'
import {
  buildLivestockDetailRows,
  formatPublishTime,
  resolveDetailCover,
  resolveDetailVideo
} from '@/utils/livestockResourceDetail'

const TAB_TYPE_CODES = ['004002', '004006', '004007', '004008']
const TAB_I18N_KEYS = ['t1', 't2', 't3', 't4']

export default {
  mixins: [tabPage],
  data() {
    return {
      navTitleKey: 'livestockResourceDetailPage.navTitle',
      resourceId: '',
      sourceType: 0,
      typeCode: '',
      detail: null,
      loading: false,
      loadError: '',
      coverRaw: '',
      coverSrc: '',
      videoSrc: ''
    }
  },
  computed: {
    displayTitle() {
      const name = this.detail && (this.detail.resourceName || this.detail.title)
      return name || this.$t('livestockResourceDetailPage.titleFallback')
    },
    typeLabel() {
      const code = (this.detail && this.detail.resourceType) || this.typeCode
      const idx = TAB_TYPE_CODES.indexOf(code)
      if (idx >= 0) {
        return this.$t(`livestockResourcesPage.tabs.${TAB_I18N_KEYS[idx]}`)
      }
      return code || ''
    },
    publishTime() {
      return formatPublishTime(this.detail && this.detail.publishTime)
    },
    introText() {
      return (this.detail && this.detail.introduction) || this.$t('livestockResourceDetailPage.noIntro')
    },
    isVideoCourse() {
      const rt = (this.detail && this.detail.resourceType) || this.typeCode
      return rt === '004008'
    },
    hasCover() {
      return !!(this.coverRaw || '').trim()
    },
    /** 视频课程：封面作 poster，有视频时不单独占一大块封面区 */
    showCoverSection() {
      if (!this.hasCover) {
        return !this.isVideoCourse
      }
      if (this.isVideoCourse && this.videoSrc) {
        return false
      }
      return true
    },
    showVideoSection() {
      return this.isVideoCourse
    },
    detailRows() {
      return buildLivestockDetailRows(this.detail, this.sourceType, (key) => this.$t(key))
    }
  },
  onLoad(query) {
    const q = query || {}
    this.resourceId = this.decodeQuery(q, 'id')
    this.typeCode = this.decodeQuery(q, 'typeCode')
    const st = parseInt(this.decodeQuery(q, 'sourceType'), 10)
    this.sourceType = st === 1 || st === 2 ? st : 0
    this.loadDetail()
  },
  onShow() {
    const title = this.displayTitle
    const p = uni.setNavigationBarTitle({
      title: title === this.$t('livestockResourceDetailPage.titleFallback') ? this.$t(this.navTitleKey) : title
    })
    if (p && typeof p.catch === 'function') {
      p.catch(() => {})
    }
  },
  methods: {
    decodeQuery(q, key) {
      const raw = q && q[key]
      if (raw == null || raw === '') {
        return ''
      }
      try {
        return decodeURIComponent(String(raw))
      } catch (e) {
        return String(raw)
      }
    },
    loadDetail() {
      if (!this.resourceId || !this.sourceType) {
        this.loadError = this.$t('livestockResourceDetailPage.invalidParams')
        return Promise.resolve()
      }
      this.loading = true
      this.loadError = ''
      return getLivestockResourceDetail(this.resourceId, this.sourceType)
        .then((res) => {
          this.detail = res.data || null
          if (!this.detail) {
            this.loadError = this.$t('livestockResourceDetailPage.notFound')
            return
          }
          const cover = resolveDetailCover(this.detail, this.sourceType)
          this.coverRaw = cover || ''
          this.coverSrc = cover ? resolveResourceUrl(cover) : ''
          const video = resolveDetailVideo(this.detail)
          this.videoSrc = video ? resolveResourceUrl(video) : ''
          if (this.detail.resourceType) {
            this.typeCode = this.detail.resourceType
          }
          uni.setNavigationBarTitle({ title: this.displayTitle })
        })
        .catch((e) => {
          this.detail = null
          this.loadError = (e && e.message) || this.$t('livestockResourceDetailPage.loadFail')
        })
        .finally(() => {
          this.loading = false
        })
    },
    onPreviewCover() {
      if (!this.coverSrc) return
      uni.previewImage({ urls: [this.coverSrc], current: 0 })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/morandi.scss';
@import '@/styles/tab-page.scss';

.lrd-page {
  display: flex;
  flex-direction: column;
  min-width: 0;
  min-height: 100%;
  box-sizing: border-box;
  background: $morandi-bg-page;
}

.lrd-scroll {
  flex: 1;
  min-height: 0;
  min-width: 0;
}

.lrd-inner {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 28rpx;
  min-width: 0;
  padding: 40rpx 32rpx 48rpx;
  box-sizing: border-box;
}

.lrd-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48rpx 24rpx;
}

.lrd-state__txt {
  color: $morandi-text-muted;
  text-align: center;
}

.lrd-title {
  display: block;
  width: 100%;
  text-align: center;
  font-size: 38rpx;
  font-weight: 700;
  line-height: 1.45;
  color: #111827;
  word-break: break-word;
  overflow-wrap: anywhere;
}

.lrd-meta {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 12rpx 20rpx;
  width: 100%;
}

.lrd-meta__tag {
  padding: 6rpx 16rpx;
  border-radius: 999rpx;
  font-size: 22rpx;
  line-height: 1.4;
  color: #15803d;
  background: rgba(34, 197, 94, 0.12);
  border: 1rpx solid rgba(34, 197, 94, 0.25);
}

.lrd-meta__date {
  font-size: 24rpx;
  line-height: 1.5;
  color: $morandi-text-muted;
}

.lrd-section {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  min-width: 0;
  padding: 24rpx;
  box-sizing: border-box;
  border-radius: 16rpx;
  background: $morandi-bg-card;
  border: 1rpx solid $morandi-border;
}

.lrd-section__label {
  font-size: 30rpx;
  font-weight: 600;
  color: $morandi-text;
}

.lrd-muted {
  font-size: 26rpx;
  line-height: 1.5;
  color: $morandi-text-muted;
}

.lrd-intro {
  font-size: 28rpx;
  line-height: 1.65;
  color: $morandi-text-secondary;
  word-break: break-word;
  overflow-wrap: anywhere;
  white-space: pre-wrap;
}

.lrd-cover-wrap {
  width: 100%;
  max-width: 480rpx;
  height: 280rpx;
  margin: 0 auto;
  border-radius: 12rpx;
  overflow: hidden;
  background: $morandi-bg-card-inner;
  border: 1rpx solid $morandi-border-soft;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lrd-cover {
  display: block;
  width: 100%;
  height: 100%;
}

.lrd-video-wrap {
  width: 100%;
  min-width: 0;
  border-radius: 12rpx;
  overflow: hidden;
  background: #1a1a1a;
  border: 1rpx solid $morandi-border-soft;
}

.lrd-video {
  display: block;
  width: 100%;
  height: 360rpx;
  background: #1a1a1a;
}

.lrd-kv {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 16rpx;
  min-width: 0;
  padding: 14rpx 0;
  border-top: 1rpx solid $morandi-border-soft;

  &:first-of-type {
    border-top: none;
    padding-top: 0;
  }

  &:last-of-type {
    padding-bottom: 0;
  }
}

.lrd-kv__label {
  flex-shrink: 0;
  width: 168rpx;
  font-size: 24rpx;
  line-height: 1.55;
  color: $morandi-text-soft;
}

.lrd-kv__value {
  flex: 1;
  min-width: 0;
  font-size: 26rpx;
  line-height: 1.55;
  color: $morandi-text;
  word-break: break-word;
  overflow-wrap: anywhere;
}

.lrd-page.lang-bo {
  .lrd-title {
    font-size: 34rpx;
    line-height: 1.75;
    letter-spacing: 2rpx;
    font-family: 'Noto Sans Tibetan', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }

  .lrd-meta__tag,
  .lrd-meta__date,
  .lrd-intro,
  .lrd-muted,
  .lrd-kv__label,
  .lrd-kv__value {
    font-size: 22rpx;
    line-height: 1.75;
    letter-spacing: 2rpx;
    font-family: 'Noto Sans Tibetan', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }

  .lrd-section__label {
    font-size: 28rpx;
    line-height: 1.75;
    letter-spacing: 2rpx;
    font-family: 'Noto Sans Tibetan', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
}
</style>
