<!-- src/pages/view/notice/detail.vue -->
<template>
  <BasicLayout>
    <view class="notice-detail-page">
      <view v-if="isLoading" class="loading-indicator">加载中...</view>
      <view v-else-if="noticeDetail" class="detail-container">
        <!-- 1. 主要内容卡片 -->
        <view class="info-card main-content-card">
          <!-- 封面 -->
          <view v-if="noticeDetail.coverImage" class="cover-image-container">
            <image
              :src="noticeDetail.coverImage"
              mode="aspectFill"
              class="cover-image"
            ></image>
          </view>
          <view v-else class="cover-placeholder">
            <uni-icons type="image" size="30" color="#ccc"></uni-icons>
            <text>暂无封面</text>
          </view>

          <!-- 标题 -->
          <text class="notice-title">{{ noticeDetail.title }}</text>

          <!-- 内容 -->
          <view class="notice-content">
            <text>{{ noticeDetail.content }}</text>
          </view>

          <!-- 附件 (简单展示) -->
          <view
            v-if="
              noticeDetail.attachments && noticeDetail.attachments.length > 0
            "
            class="attachments-section"
          >
            <text class="sub-title">附件:</text>
            <view
              v-for="(att, index) in noticeDetail.attachments"
              :key="index"
              class="attachment-item"
            >
              <uni-icons type="link" size="16" color="#007aff"></uni-icons>
              <text class="attachment-name">{{ att.name }}</text>
            </view>
          </view>
        </view>

        <!-- 2. 按名单填写卡片 (反馈情况) -->
        <view class="info-card feedback-card">
          <text class="feedback-title"
            >反馈完成情况 ({{ receivedCount }}/{{ totalStudents }})</text
          >
          <view class="name-tags">
            <view
              v-for="student in noticeDetail.targetStudents"
              :key="student.id"
              class="name-tag"
              :class="{ received: student.received }"
            >
              <text>{{ student.name }}</text>
              <view v-if="student.received" class="checkmark-icon">
                <uni-icons
                  type="checkmarkempty"
                  size="12"
                  color="#ffffff"
                ></uni-icons>
              </view>
            </view>
            <!-- Modify button is usually not shown in detail view -->
            <!-- <button class="modify-btn">修改</button> -->
          </view>
        </view>

        <!-- 4. 时间卡片 -->
        <view class="info-card list-item-card">
          <view class="list-item-row no-border">
            <text class="list-label">结束时间</text>
            <view class="list-value">
              <text>{{ noticeDetail.endTime }}</text>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="empty-state">通知详情未找到</view>
    </view>
    <template #bottom>
      <view class="bottom-actions">
        <button class="action-btn publish-btn">接龙</button>
      </view>
    </template>
  </BasicLayout>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";

interface Attachment {
  name: string;
  type: string; // e.g., 'image', 'video', 'file'
  url: string;
}

interface StudentFeedback {
  id: string;
  name: string;
  received: boolean;
  avatar?: string; // Optional avatar
}

interface NoticeDetail {
  id: string;
  title: string;
  content: string;
  coverImage?: string;
  attachments?: Attachment[];
  targetClass: string;
  targetStudents: StudentFeedback[]; // Array of student feedback objects
  signatureStatus: string; // e.g., '不启用', '启用中'
  startTime: string;
  endTime: string;
  // Add other fields if needed (e.g., publisher, publishTime)
}

const noticeId = ref<string>("");
const noticeDetail = ref<NoticeDetail | null>(null);
const isLoading = ref(false);

// Computed properties for feedback status
const receivedCount = computed(() => {
  return (
    noticeDetail.value?.targetStudents.filter((s) => s.received).length ?? 0
  );
});
const totalStudents = computed(() => {
  return noticeDetail.value?.targetStudents.length ?? 0;
});

onLoad((options) => {
  if (options && options.id) {
    noticeId.value = options.id;
    fetchNoticeDetail();
  } else {
    console.error("Notice ID is missing!");
    uni.showToast({ title: "加载失败，缺少通知ID", icon: "none" });
  }
});

// 模拟获取通知详情数据
const fetchNoticeDetail = async () => {
  console.log(`Fetching details for notice ID: ${noticeId.value}`);
  isLoading.value = true;
  await new Promise((resolve) => setTimeout(resolve, 500));

  // --- Replace with actual API call using noticeId.value ---

  // Example Mock Data with targetStudents
  const mockDetail: NoticeDetail = {
    id: noticeId.value,
    title: "重要通知接龙",
    content:
      "由于xxx原因，现下发《关于加强建设xxxx工作的通知》\n希望大家自习阅读，认真执行。",
    // coverImage: '/static/mock/notice-cover.png', // 可选封面
    attachments: [
      { name: "附件1.docx", type: "file", url: "" },
      { name: "相关图片.png", type: "image", url: "" },
    ],
    targetClass: "一年级3班",
    targetStudents: [
      { id: "s111", name: "施延兴", received: true },
      { id: "s112", name: "安苒溪", received: false },
      { id: "s113", name: "罗浩晨", received: false },
      { id: "s114", name: "康萌", received: true },
      { id: "s115", name: "范文昊", received: false },
      { id: "s116", name: "丁贺祥", received: false },
      { id: "s117", name: "韦运昊", received: false },
      { id: "s118", name: "萧润丽", received: true },
      { id: "s119", name: "谢林", received: false },
      { id: "s120", name: "鲍泽远", received: true },
      { id: "s121", name: "杨俊", received: false },
      { id: "s122", name: "秦禹辰", received: false },
      { id: "s123", name: "姜杨", received: false },
      { id: "s124", name: "窦晶滢", received: true },
      { id: "s125", name: "廉佳毅", received: false },
      { id: "s126", name: "许冰枫", received: false },
      { id: "s127", name: "曹佳惠", received: true },
      { id: "s128", name: "元运昊", received: false },
      { id: "s129", name: "孔欣怡", received: false },
      { id: "s130", name: "许润平", received: true },
      { id: "s131", name: "谢汝鑫", received: true },
      { id: "s132", name: "康益帆", received: true },
      { id: "s133", name: "凤帆", received: false },
      { id: "s134", name: "吴雅晗", received: false },
      { id: "s135", name: "曹阳", received: false },
      { id: "s136", name: "萧润丽", received: true }, // Duplicate name example
      { id: "s137", name: "褚慧嘉", received: false },
      { id: "s138", name: "薛欣怡", received: true },
      { id: "s139", name: "倪雄霖", received: false },
      { id: "s140", name: "顾雪", received: true },
    ], // Mock received status
    signatureStatus: "不启用",
    startTime: "2025-03-10 12:00:00",
    endTime: "2025-03-10 12:00:00",
  };

  noticeDetail.value = mockDetail; // Assign the mock data
  isLoading.value = false;

  // 设置导航栏标题
  uni.setNavigationBarTitle({ title: "通知详情" });
};

// Placeholder for attachment preview function
const previewAttachment = (attachment: Attachment) => {
  console.log("尝试下载/预览附件:", attachment);

  if (!attachment.url) {
    uni.showToast({ title: "附件链接无效", icon: "none" });
    return;
  }

  uni.showLoading({ title: "正在准备附件..." });

  uni.downloadFile({
    url: attachment.url,
    success: (res) => {
      if (res.statusCode === 200) {
        const filePath = res.tempFilePath;
        console.log("文件下载成功:", filePath);
        uni.hideLoading();
        // Attempt to open the downloaded file
        uni.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log("打开文档成功");
          },
          fail: function (err) {
            console.error("打开文档失败:", err);
            uni.showToast({ title: "无法打开该文件类型", icon: "none" });
            uni.hideLoading(); // Ensure loading is hidden on failure too
          },
        });
      } else {
        console.error("下载文件失败，服务器状态码:", res.statusCode);
        uni.hideLoading();
        uni.showToast({ title: "下载附件失败", icon: "none" });
      }
    },
    fail: (err) => {
      console.error("下载文件请求失败:", err);
      uni.hideLoading();
      uni.showToast({ title: "下载附件失败", icon: "none" });
    },
  });
};
</script>

<style scoped lang="scss">
.notice-detail-page {
  background-color: #f4f5f7;
  min-height: 100vh;
  padding: 15px;
  box-sizing: border-box;
}

.bottom-actions {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 12px 15px; 
  background-color: #ffffff;
  border-top: 1px solid #e5e5e5;

  .action-btn {
    width: 90%;
    min-width: 90px;
    margin: 0 5px;
    font-size: 15px;
    height: 40px;
    line-height: 40px;
    border-radius: 20px;
    padding: 0 20px;

    &::after {
      border: none;
    }

    &.draft-btn {
      background-color: #f4f4f5;
      color: #909399;
      border: 1px solid #e9e9eb;
    }
    &.preview-btn {
      background-color: #ecf5ff;
      color: #409eff;
      border: 1px solid #d9ecff;
    }
    &.publish-btn {
      background-color: #409eff;
      color: #ffffff;
      border: none;
    }
    &.draft-btn:active {
      background-color: #e0e0e0;
    }
    &.preview-btn:active {
      background-color: #d9ecff;
    }
    &.publish-btn:active {
      background-color: #3a8ee6;
    }
  }
}

.loading-indicator,
.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 15px;
  font-size: 14px;
}

.detail-container {
  // 卡片之间的间距由卡片自身的 margin-bottom 控制
}

/* 通用卡片样式 */
.info-card {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
}

/* 主要内容卡片 */
.main-content-card {
  .cover-placeholder {
    background-color: #f0f0f0;
    height: 120px;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #ccc;
    font-size: 14px;
    margin-bottom: 15px;
    text {
      margin-top: 5px;
    }
  }
  .cover-image-container {
    margin-bottom: 15px;
    .cover-image {
      width: 100%;
      height: 150px; // Or adjust as needed
      border-radius: 6px;
      display: block;
    }
  }

  .notice-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 10px;
  }
  .notice-content {
    font-size: 15px;
    color: #555;
    line-height: 1.7;
    margin-bottom: 20px;
    white-space: pre-wrap; // 保留换行符
  }

  // 设计稿中的添加附件占位
  .add-attachment-placeholder {
    display: flex;
    align-items: center;
    border: 1px dashed #dcdcdc;
    border-radius: 6px;
    padding: 15px;
    margin-top: 15px;
    .add-icon {
      width: 30px;
      height: 30px;
      border: 1px solid #dcdcdc;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
    }
    .placeholder-text {
      font-size: 14px;
      color: #999;
    }
  }
}

/* 附件区域 */
.attachments-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  .sub-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    display: block;
  }
  .attachment-item {
    display: flex;
    align-items: center;
    padding: 5px 0;
    .attachment-name {
      font-size: 14px;
      color: #007aff;
      margin-left: 5px;
    }
  }
}

/* 按名单填写/反馈情况卡片 */
.feedback-card {
  // Optional: Add specific padding if needed
}

.feedback-title {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.name-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 10px; // Row gap, Column gap

  .name-tag,
  .modify-btn {
    // Apply same sizing logic to modify button if it exists
    position: relative;
    font-size: 13px;
    padding: 5px 8px; // Adjust horizontal padding slightly if needed
    border-radius: 4px;
    text-align: center;
    flex-grow: 0;
    flex-shrink: 0;
    box-sizing: border-box;
    // Calculate basis for 5 items per row, accounting for 10px gap
    flex-basis: calc((100% - 40px) / 5);
    height: 30px; // Slightly taller height
    line-height: 20px; // Adjust line-height for vertical centering
    border: 1px solid #f4f4f5;
    // Remove overflow hidden to allow wrapping if necessary
    // overflow: hidden;
    // Ensure text can wrap
    white-space: normal;
    word-break: break-all; // Break long names if they don't fit
  }

  .name-tag {
    background-color: #f4f4f5;
    color: #909399;

    &.received {
      background-color: #e1f3d8;
      color: #67c23a;
      border-color: #b3e19d;
    }

    .checkmark-icon {
      position: absolute;
      top: -1px;
      right: -1px;
      width: 16px;
      height: 16px;
      background-color: #67c23a;
      border-bottom-left-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 1px;
      box-sizing: border-box;
      .uni-icons {
        // Icon adjustments if needed
      }
    }
  }

  // Modify button (usually hidden in detail)
  .modify-btn {
    // ... styles ...
    flex-basis: calc((100% - 40px) / 5); // Keep consistent basis
  }
}

/* 列表项样式的卡片 */
.list-item-card {
  padding: 5px 15px; // 减少上下 padding
}

.list-item-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0; // 行内上下 padding
  border-bottom: 1px solid #f0f0f0;

  &.no-border {
    border-bottom: none;
  }

  .list-label {
    font-size: 15px;
    color: #333;
  }
  .list-value {
    display: flex;
    align-items: center;
    font-size: 15px;
    color: #666;
    text {
      margin-right: 3px;
    }
  }
}
</style>
