<template>
  <!-- 资讯详情：从上页携带 id + type，请求 /app/farmingNews/{id}?type= 展示源表字段 -->
  <view :class="pageRootClass" class="tab-page news-detail-page">
    <view v-if="loading" class="news-detail-state">
      <text class="text-body news-detail-state__txt">{{ $t('newsDetailPage.loading') }}</text>
    </view>
    <view v-else-if="loadError" class="news-detail-state">
      <text class="text-body news-detail-state__txt">{{ loadError }}</text>
    </view>

    <scroll-view v-else scroll-y class="news-detail-scroll" enable-back-to-top>
      <view class="news-detail-inner">
        <text class="news-detail-title">{{ resolvedTitle }}</text>

        <view class="news-detail-meta">
          <text v-if="displayTypeLabel" class="news-detail-meta__tag text-body">{{ displayTypeLabel }}</text>
          <text v-if="displayDate" class="text-body news-detail-date">{{ displayDate }}</text>
        </view>

        <view class="news-detail-section">
          <text class="news-detail-section__label text-title">{{ $t('newsDetailPage.coverTitle') }}</text>
          <image
            v-if="hasCover"
            class="news-detail-cover"
            :src="coverFullUrl"
            mode="widthFix"
            role="button"
            @click="previewCover"
          />
          <text v-else class="text-body news-detail-muted">{{ $t('newsDetailPage.noCover') }}</text>
        </view>

        <view class="news-detail-section">
          <text class="news-detail-section__label text-title">{{ $t('newsDetailPage.introTitle') }}</text>
          <text class="text-body news-detail-intro">{{ displayIntro || $t('newsDetailPage.noIntro') }}</text>
        </view>

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

        <view v-if="isCommonProsperity" class="news-detail-section">
          <text class="news-detail-section__label text-title">{{ $t('newsDetailPage.cpOpImages') }}</text>
          <view v-if="opImageUrls.length" class="news-detail-op-grid">
            <image
              v-for="(url, idx) in opImageUrls"
              :key="idx"
              class="news-detail-op-img"
              :src="url"
              mode="aspectFill"
              role="button"
              @click="previewOpImages(idx)"
            />
          </view>
          <text v-else class="text-body news-detail-muted">{{ $t('newsDetailPage.dash') }}</text>
        </view>

        <view v-if="showContentAttachment" class="news-detail-section">
          <text class="news-detail-section__label text-title">
            {{ isCommonProsperity ? $t('newsDetailPage.cpVideo') : $t('newsDetailPage.attachmentTitle') }}
          </text>

          <image
            v-if="attachmentKind === 'image'"
            class="news-detail-attach-img"
            :src="contentFullUrl"
            mode="widthFix"
            role="button"
            @click="previewImageAttachment"
          />

          <view v-else-if="attachmentKind === 'video'" class="news-detail-video-wrap">
            <video
              class="news-detail-video"
              :src="contentFullUrl"
              :poster="hasCover ? coverFullUrl : ''"
              controls
              object-fit="contain"
              :enable-progress-gesture="true"
              :show-center-play-btn="true"
            />
          </view>

          <view v-else-if="attachmentKind === 'pdf'" class="news-detail-pdf-wrap">
            <!-- #ifdef H5 -->
            <iframe
              class="news-detail-pdf-frame"
              :src="contentFullUrl"
              frameborder="0"
            />
            <!-- #endif -->
            <!-- #ifndef H5 -->
            <view class="news-detail-attach-card" role="button" @click="openOnlineAttachment">
              <up-icon name="file-text" color="#15803d" :size="28" />
              <view class="news-detail-attach-card__mid">
                <text class="news-detail-attach-card__name">{{ attachmentFileName }}</text>
                <text class="text-body news-detail-attach-card__hint">{{ $t('newsDetailPage.viewOnline') }}</text>
              </view>
              <up-icon name="arrow-right" color="#9ca3af" :size="16" />
            </view>
            <!-- #endif -->
          </view>

          <view
            v-else
            class="news-detail-attach-card"
            role="button"
            @click="openOnlineAttachment"
          >
            <up-icon name="file-text" color="#15803d" :size="28" />
            <view class="news-detail-attach-card__mid">
              <text class="news-detail-attach-card__name">{{ attachmentFileName }}</text>
              <text class="text-body news-detail-attach-card__hint">{{ $t('newsDetailPage.viewOnline') }}</text>
            </view>
            <up-icon name="arrow-right" color="#9ca3af" :size="16" />
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import UIcon from 'uview-plus/components/u-icon/u-icon.vue'
import tabPage from '@/mixins/tabPage'
import { resolveResourceUrl } from '@/utils/resourceUrl'
import { fileNameFromPath, openOnlinePreview, resolveMediaKind } from '@/utils/filePreview'
import { getFarmingNewsDetail } from '@/api/farmingNews'
import {
  buildFarmingDetailRows,
  formatPublishTime,
  resolveDetailContent,
  resolveDetailCover,
  resolveDetailIntro,
  resolveDetailTitle,
  resolveOpImageUrls
} from '@/utils/farmingNewsDetail'

const COMMON_PROSPERITY_TYPE = '003004'

function decodeQuery(val) {
  if (val == null || val === '') {
    return ''
  }
  try {
    return decodeURIComponent(String(val))
  } catch (e) {
    return String(val)
  }
}

function normPath(url) {
  return String(url || '')
    .trim()
    .replace(/\\/g, '/')
    .split('?')[0]
    .toLowerCase()
}

export default {
  components: {
    'up-icon': UIcon
  },
  mixins: [tabPage],
  data() {
    return {
      navTitleKey: 'newsDetailPage.navTitle',
      newsId: '',
      newsType: '',
      displayTypeLabel: '',
      displayTitle: '',
      displayDate: '',
      displayIntro: '',
      coverFileUrl: '',
      contentFileUrl: '',
      detail: null,
      detailRows: [],
      opImageUrls: [],
      loading: false,
      loadError: '',
      openingAttachment: false
    }
  },
  computed: {
    isCommonProsperity() {
      return this.newsType === COMMON_PROSPERITY_TYPE
    },
    resolvedTitle() {
      return this.displayTitle || this.$t('newsDetailPage.titleFallback')
    },
    hasCover() {
      return !!(this.coverFileUrl || '').trim()
    },
    hasAttachment() {
      return !!(this.contentFileUrl || '').trim()
    },
    coverFullUrl() {
      return resolveResourceUrl(this.coverFileUrl)
    },
    contentFullUrl() {
      return resolveResourceUrl(this.contentFileUrl)
    },
    attachmentKind() {
      return resolveMediaKind(this.contentFileUrl)
    },
    attachmentFileName() {
      return fileNameFromPath(this.contentFileUrl)
    },
    showContentAttachment() {
      if (!this.hasAttachment) {
        return false
      }
      if (!this.hasCover) {
        return true
      }
      if (normPath(this.coverFileUrl) !== normPath(this.contentFileUrl)) {
        return true
      }
      return this.attachmentKind !== 'image'
    }
  },
  onLoad(query) {
    this.newsId = decodeQuery(query.id)
    this.newsType = decodeQuery(query.type)
    this.displayTypeLabel = decodeQuery(query.typeLabel)
    this.loadDetail()
  },
  methods: {
    loadDetail() {
      if (!this.newsId || !this.newsType) {
        this.loadError = this.$t('newsDetailPage.invalidParams')
        return
      }
      this.loading = true
      this.loadError = ''
      getFarmingNewsDetail(this.newsId, this.newsType)
        .then((res) => {
          const data = res.data || null
          if (!data) {
            this.loadError = this.$t('newsDetailPage.notFound')
            return
          }
          this.applyDetail(data)
        })
        .catch((e) => {
          this.detail = null
          this.loadError = (e && e.message) || this.$t('newsDetailPage.loadFail')
        })
        .finally(() => {
          this.loading = false
        })
    },
    applyDetail(data) {
      this.detail = data
      this.displayTitle = resolveDetailTitle(data)
      this.displayIntro = resolveDetailIntro(data)
      this.coverFileUrl = resolveDetailCover(data)
      this.contentFileUrl = resolveDetailContent(data)
      this.displayDate = formatPublishTime(data.publishTime)
      this.detailRows = buildFarmingDetailRows(data, this.newsType, (key) => this.$t(key))
      this.opImageUrls = resolveOpImageUrls(data, resolveResourceUrl)
      if (this.displayTitle) {
        uni.setNavigationBarTitle({ title: this.displayTitle })
      }
    },
    previewCover() {
      if (!this.coverFullUrl) {
        return
      }
      uni.previewImage({
        urls: [this.coverFullUrl],
        current: 0
      })
    },
    previewOpImages(index) {
      if (!this.opImageUrls.length) {
        return
      }
      uni.previewImage({
        urls: this.opImageUrls,
        current: typeof index === 'number' ? index : 0
      })
    },
    previewImageAttachment() {
      if (!this.contentFullUrl) {
        return
      }
      uni.previewImage({
        urls: [this.contentFullUrl],
        current: 0
      })
    },
    openOnlineAttachment() {
      if (!this.contentFileUrl || this.openingAttachment) {
        return
      }
      if (this.attachmentKind === 'image') {
        this.previewImageAttachment()
        return
      }
      this.openingAttachment = true
      openOnlinePreview(this.contentFileUrl, { title: this.attachmentFileName })
        .catch(() => {
          uni.showToast({
            title: this.$t('newsDetailPage.previewFail'),
            icon: 'none'
          })
        })
        .finally(() => {
          this.openingAttachment = false
        })
    }
  }
}
</script>

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

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

.news-detail-state {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  min-height: 40vh;
  padding: 48rpx 32rpx;
  box-sizing: border-box;
}

.news-detail-state__txt {
  font-size: 28rpx;
  line-height: 1.6;
  color: $morandi-text-muted;
  text-align: center;
}

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

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

.news-detail-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;
}

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

.news-detail-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);
}

.news-detail-date {
  font-size: 24rpx;
  line-height: 1.5;
  color: $morandi-text-muted;
}

.news-detail-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;
}

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

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

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

.news-detail-kv {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 16rpx;
  min-width: 0;
  padding: 8rpx 0;
  border-bottom: 1rpx solid $morandi-border-soft;

  &:last-child {
    border-bottom: none;
  }
}

.news-detail-kv__label {
  flex-shrink: 0;
  width: 180rpx;
  font-size: 26rpx;
  line-height: 1.5;
  color: $morandi-text-muted;
}

.news-detail-kv__value {
  flex: 1;
  min-width: 0;
  font-size: 26rpx;
  line-height: 1.5;
  color: $morandi-text-secondary;
  word-break: break-word;
  overflow-wrap: anywhere;
  white-space: pre-wrap;
}

.news-detail-op-grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 16rpx;
}

.news-detail-op-img {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  background: $morandi-bg-card-inner;
}

.news-detail-cover,
.news-detail-attach-img {
  display: block;
  width: 100%;
  border-radius: 12rpx;
  background: $morandi-bg-card-inner;
}

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

.news-detail-video {
  display: block;
  width: 100%;
  height: 400rpx;
  background: #1a1a1a;
}

.news-detail-pdf-wrap {
  width: 100%;
  min-width: 0;
}

.news-detail-pdf-frame {
  display: block;
  width: 100%;
  height: 70vh;
  min-height: 480rpx;
  border: none;
  border-radius: 12rpx;
  background: $morandi-bg-card-inner;
}

.news-detail-attach-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16rpx;
  min-width: 0;
  padding: 20rpx;
  box-sizing: border-box;
  border-radius: 12rpx;
  background: $morandi-bg-card-inner;
  border: 1rpx solid $morandi-border-soft;
}

.news-detail-attach-card__mid {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.news-detail-attach-card__name {
  font-size: 28rpx;
  font-weight: 500;
  line-height: 1.45;
  color: $morandi-text;
  word-break: break-all;
}

.news-detail-attach-card__hint {
  font-size: 24rpx;
  color: $morandi-accent-soft;
}

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

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

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

  .news-detail-attach-card__name {
    font-size: 26rpx;
    line-height: 1.75;
    letter-spacing: 2rpx;
    font-family: 'Noto Sans Tibetan', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }

  .news-detail-kv__label {
    width: 220rpx;
  }
}
</style>
