<template>
  <div class="news-container">
    <Header />

    <div class="content-wrapper mt-15 max-w-[1200px] mx-auto">
      <h2 class="page-title">
        {{ route.query.tabKey === "notice" ? "通知公告" : "红头文件" }}

        <el-button
          type="primary"
          round
          size="small"
          color="#02409b"
          @click="router.back()"
          ><Icon
            icon="mynaui:corner-up-left"
            class="icon pr-1"
            width="20"
            height="20"
          />返回</el-button
        >
      </h2>

      <!-- 新闻列表区域 - 使用 el-table -->
      <div v-loading="loading" class="table-wrapper">
        <el-table
          :data="newsList"
          style="width: 100%"
          height="70vh"
          v-loading="loading"
          element-loading-text="加载中..."
          :empty-text="loading ? '' : '暂无数据'"
          stripe
          :header-cell-style="{
            backgroundColor: '#e9f7ff',
            color: 'black',
            fontWeight: '400',
          }"
          :cell-style="{
            color: 'black',
          }"
        >
          <!-- 序号列 -->
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          />

          <!-- 标题列 -->
          <el-table-column prop="title" label="标题" min-width="300">
            <template #default="{ row }">
              <span class="table-title">{{ row.docsubject }}</span>
            </template>
          </el-table-column>

          <!-- 时间列 -->
          <el-table-column
            prop="docvaliddate"
            label="发布时间"
            width="180"
            align="center"
            sortable
          />

          <!-- 操作列（可选） -->
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleNoticeItemClick(row)"
                >查看详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import * as dd from "dingtalk-jsapi";
import Header from "@components/home/header.vue";
import Footer from "@components/home/Footer.vue";
import { ElLoading } from "element-plus";
import { Icon } from "@iconify/vue";
import { getNews, ssoLogin, getNotices, getRedHeadFiles } from "@/api/user";
import { useUserStore } from "@/stores/useUserStore";
import { useRoute, useRouter } from "vue-router";
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
// 状态定义
const loading = ref(false);
const newsList = ref([]);

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const handleNoticeItemClick = async (notice) => {
  const res = await ssoLogin({
    username: userStore.getUser.username,
  });

  if (res) {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.includes("dingtalk") || ua.includes("dingtalkwork")) {
      dd.biz.util.openLink({
        url:
          "https://yfoa.keruioil.com/wui/index.html" +
          "?ssoToken=" +
          res +
          "#/main", // 先跳你的 SSO 链接
        onSuccess: () => {
          // 延迟跳目标业务地址（和你原来 setTimeout 逻辑一致）
          setTimeout(() => {
            dd.biz.util.openLink({
              url: `https://yfoa.keruioil.com/spa/document/index.jsp?openAttachment=0&id=${notice.id}`,
            });
          }, 100);
        },
      });
    } else {
      const loading = ElLoading.service({
        lock: true,
        text: "正在跳转，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const newTab = window.open("", "_blank");
      newTab.location.href =
        "https://yfoa.keruioil.com/wui/index.html" +
        "?ssoToken=" +
        res +
        "#/main";

      setTimeout(function () {
        newTab.location.href = `https://yfoa.keruioil.com/spa/document/index.jsp?openAttachment=0&id=${notice.id}`;
        setTimeout(() => {
          loading.close();
        }, 500);
      }, 100);
    }
  }
};

// 获取新闻列表方法
const fetchNewsList = async () => {
  loading.value = true;
  try {
    const requestApi =
      route.query.tabKey === "notice" ? getNotices : getRedHeadFiles;
    const res = await requestApi({
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    });

    // 请根据实际接口返回结构调整以下赋值逻辑
    if (res && res.list) {
      newsList.value = res.list || [];
      pagination.total = res.total || 0;
    } else if (res && res.data) {
      // 兼容另一种常见返回结构
      newsList.value = res.data.list || [];
      pagination.total = res.data.total || 0;
    }
  } catch (error) {
    console.error("获取新闻列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 分页大小改变事件
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.pageNum = 1;
  fetchNewsList();
};

// 当前页改变事件
const handleCurrentChange = (val) => {
  pagination.pageNum = val;
  fetchNewsList();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchNewsList();
});
</script>

<style scoped>
.news-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.content-wrapper {
  flex: 1;
  max-width: 1200px;
  /* margin: 0 auto; */
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
  border-left: 5px solid #409eff;
  padding-left: 10px;
  display: flex;
  gap: 20px;
}

.table-wrapper {
  min-height: 400px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.table-title {
  font-weight: 500;
  color: #303133;
}

.table-summary {
  color: #606266;
  font-size: 13px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  padding: 20px 0;
}
</style>
