<template>
  <view v-if="articles.length" class="article-container">
    <view class="flex items-center justify-between">
      <view class="module-title">健康宣教</view>
      <view v-if="total > 3" class="flex items-center" @click="toMorePage()">
        <view class="mr-5 text-base text-gray">更多</view>
        <image class="arrow-icon" src="/static/home/arrow-right-gray.png" mode="aspectFit"></image>
      </view>
    </view>

    <view class="mt-10">
      <view v-for="(article, index) in articles" :key="article._id" class="article-card flex"
        :class="{ 'mb-15': index < articles.length - 1 }" @click="goToDetail(article)">
        <image class="flex-shrink-0 cover" :src="article.cover || '/static/home/health-education.png'"
          mode="aspectFill" />
        <view class="w-0 flex-grow">
          <view class="article-title truncate mb-10">
            {{ article.title }}
          </view>
          <view v-if="article.summary" class="article-summary line-clamp-2">
            {{ article.summary }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import api from '@/utils/api';

const props = defineProps({
  team: {
    type: Object,
    default: () => ({})
  }
})

const articles = ref([]);
const total = ref(0);
const loading = ref(false);
const pageSize = 3;

const qrcode = computed(() => {
  const qrcodes = props.team && Array.isArray(props.team.qrcodes) ? props.team.qrcodes : [];
  return qrcodes[0] || {};
});

const articleIds = computed(() => {
  const configured = qrcode.value && Array.isArray(qrcode.value.articles) ? qrcode.value.articles : [];
  const ids = configured.map((item) => item?._id).filter((id) => typeof id === "string" && id.trim());
  return qrcode.value?.enableAnnounce === "YES" ? ids : [];
});

function goToDetail(article) {
  if (!article?._id) return;
  uni.navigateTo({ url: `/pages/article/article-detail?id=${article._id}&corpId=${props.team.corpId}` });
}

const loadArticles = async () => {
  const corpId = props.team?.corpId || "";
  const ids = articleIds.value;

  if (!corpId || ids.length === 0) {
    articles.value = [];
    total.value = 0;
    return;
  }
  if (loading.value) return;

  loading.value = true;
  try {
    const res = await api("getArticleByIds", { corpId, ids: ids.join(",") }, false);
    const rows = res && Array.isArray(res.list) ? res.list : [];

    const order = new Map(ids.map((id, idx) => [id, idx]));
    const sorted = rows
      .slice()
      .sort((a, b) => (order.get(a?._id) ?? 1e9) - (order.get(b?._id) ?? 1e9));

    total.value = sorted.length;
    articles.value = sorted.slice(0, pageSize);
  } catch (err) {
    console.error("loadArticles failed:", err);
    articles.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

function toMorePage() {
  const corpId = props.team?.corpId || "";
  const ids = articleIds.value;
  if (!corpId || ids.length === 0) return;
  uni.navigateTo({ url: `/pages/article/article-cate-list?corpId=${corpId}&ids=${encodeURIComponent(ids.join(","))}` });
}

watch(
  () => ({ corpId: props.team?.corpId || "", ids: articleIds.value.join(",") }),
  async ({ corpId, ids }) => {
    if (!corpId || !ids) {
      articles.value = [];
      total.value = 0;
      return;
    }
    await loadArticles();
  },
  { immediate: true }
);
</script>
<style scoped>
.article-container {
  margin: 0 30rpx;
  margin-top: 24rpx;
  padding-bottom: 40rpx;
  width: calc(100% - 60rpx);
  box-sizing: border-box;
}

.arrow-icon {
  width: 32rpx;
  height: 32rpx;
}

.module-title {
  color: #000000;
  font-size: 38rpx;
  font-style: normal;
  font-weight: 600;
  line-height: normal;
}

.article-card {
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 10rpx 0 rgba(60, 169, 145, 0.06);
  transition: all 0.3s;
  min-height: 188rpx;
  padding: 20rpx;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}

.article-card:active {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.cover {
  width: 200rpx;
  height: 112rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  object-fit: cover;
}

.mb-15 {
  margin-bottom: 20rpx;
}

.article-title {
  color: #333333;
  font-size: 34rpx;
  font-weight: 500;
  line-height: normal;
}

.article-summary {
  max-width: 402rpx;
  color: #666666;
  text-align: justify;
  font-size: 30rpx;
  font-weight: 400;
  line-height: normal;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
}
</style>
