<template>
  <div class="container">
    <div class="spacer"></div>

    <div class="main-content">

      <p class="welcome">{{userName}}，欢迎来到炬融圈</p>
      <!-- 轮播图 -->
      <div class="carousel">
        <swiper
          :modules="modules"
          :slides-per-view="1"
          :space-between="0"
          :autoplay="{ delay: 3000, disableOnInteraction: false }"
          :pagination="{ clickable: true }"
          :loop="true"
        >
          <swiper-slide v-for="(item, index) in carouselItems" :key="index">
            <img :src="item.image" :alt="item.title" class="carousel-img" />
            <div class="carousel-title">{{ item.title }}</div>
          </swiper-slide>
        </swiper>
      </div>

      <!-- 头部导航 -->
      <div class="header">
        <div
          v-for="(item, index) in headerItems"
          :key="index"
          class="header-item"
        >
          <div @click="item.text === '系统公告' ? handleSystemAnnouncementClick() : $router.push(item.path)" class="header-item-content">
            <img :src="item.image" :alt="item.text" class="header-image" />
            <div class="header-text">{{ item.text }}</div>
          </div>
        </div>
      </div>

      <!-- 修改后的操作区域 - 三个图片并排 -->
      <div class="action-area">
        <div class="action-grid-horizontal">
          <router-link to="/matching?quantitative=true" class="action-item">
            <img src="/imgs/mainpage/dinglianghuoqu1.png" alt="定量获取" class="action-image1" />
          </router-link>
          <router-link to="/matching" class="action-item">
            <img src="/imgs/mainpage/huoqurongdou1.png" alt="获取融豆" class="action-image2" />
          </router-link>
          <router-link to="/myshop" class="action-item">
            <img src="/imgs/mainpage/shangcheng1.png" alt="商城" class="action-image3" />
          </router-link>
        </div>
      </div>

      <div class="tips">点击获得融豆，可兑换商城好物！</div>

      <!-- 热门资讯 -->
      <div class="hot-news">
        <div class="news-title">热门资讯</div>
        <div class="news-list">
          <div
            class="news-item"
            v-for="(item, index) in newsItems"
            :key="index"
          >
            <span class="news-dot">•</span> {{ item }}
          </div>
        </div>
      </div>
    </div>

    <!-- 欢迎弹窗 -->
    <el-dialog
      v-model="showWelcomeDialog"
      width="90%"
      :style="{ height: isSystemAnnouncementClick ? '525px' : '425px' }"
      :show-close="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      @close="closeWelcomeDialog"
      center
      class="welcome-dialog"
    >
      <div class="welcome-content">
        <div class="welcome-icon">🎉</div>
        <h3>融汇通更新</h3>
        <div class="welcome-features">
          <div class="announcements-container" v-if="displayAnnouncements.length > 0">
            <div 
              class="announcement-item" 
              v-for="announcement in displayAnnouncements" 
              :key="announcement.id"
            >
              <div class="announcement-header">
                <h4 class="announcement-title">{{ announcement.title }}</h4>
                <span class="announcement-priority" :class="announcement.priority">{{ announcement.priority }}</span>
              </div>
              <div class="announcement-content">{{ announcement.content }}</div>
              <div class="announcement-meta">
                <span class="announcement-time">{{ formatDate(announcement.created_at) }}</span>
                <span class="announcement-author">发布者: {{ announcement.creator_name }}</span>
              </div>
            </div>
          </div>
          <div v-else class="no-announcements">
            <span>{{ isSystemAnnouncementClick ? '暂无公告信息' : '暂无未读更新信息' }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeWelcomeDialog">已读</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Autoplay, Pagination } from 'swiper';
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage, ElDialog, ElButton } from 'element-plus';
import { transferAPI } from '../utils/api';
import { useUserStore } from '../stores/user';
import 'swiper/css';
import 'swiper/css/autoplay';
import 'swiper/css/pagination';
import api from '@/utils/api'

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  setup() {
    // 用户store
    const userStore = useUserStore();
    
    // 响应式数据
    const userPoints = ref(0);
    const showWelcomeDialog = ref(false);

    const updateNotice = ref('');
    const announcements = ref([]);
    
    // 计算属性 - 获取用户名
    const userName = computed(() => {
      return userStore.user?.username || '用户';
    });
    const carouselItems = ref([
      { image: '/imgs/top/1.jpg', title: '限时优惠活动' },
      { image: '/imgs/top/2.jpg', title: '新用户专享' },
      { image: '/imgs/top/3.jpg', title: '积分兑换' },
    ]);
    const headerItems = ref([
      {
        image: '/imgs/mainpage/jiaoyijilu.png',
        text: '交易记录',
        path: '/transfers',
      },
      {
        image: '/imgs/mainpage/dingdanchaxun.png',
        text: '订单查询',
        path: '/orders',
      },
      {
        image: '/imgs/mainpage/kefuzhongxin.png',
        text: '客服中心',
        path: '/customerservice',
      },
      {
        image: '/imgs/mainpage/xitonggonggao.png',
        text: '系统公告',
        path: '#',
      },
    ]);
    const newsItems = ref([
      '最新活动：商城特惠',
      '商城新品上架',
    ]);

    // 获取用户积分
    const getUserPoints = async () => {
      try {
        // 使用封装好的API获取用户账户信息
        const {data} = await transferAPI.getUserAccount();
         console.log(data);
         
        // 根据实际API响应结构调整，以下是几种可能的取值方式
        userPoints.value = data.data.points || 0;
      } catch (error) {
        console.error('获取积分信息失败', error);
        userPoints.value = 0;
        ElMessage.error('获取积分信息失败，请稍后重试');
      }
    };

    // 计算未读公告
    const unreadAnnouncements = computed(() => {
      return announcements.value.filter(announcement => !announcement.is_read);
    });

    // 标记是否通过系统公告按钮打开对话框
    const isSystemAnnouncementClick = ref(false);

    // 计算要显示的公告列表
    const displayAnnouncements = computed(() => {
      if (isSystemAnnouncementClick.value) {
        // 如果是通过系统公告按钮打开，显示所有公告并按创建时间倒序排列（最新的在前）
        return [...announcements.value].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
      } else {
        // 否则只显示未读公告
        return unreadAnnouncements.value;
      }
    });

    // 计算是否应该显示弹窗
    const shouldShowDialog = computed(() => {
      return unreadAnnouncements.value.length > 0;
    });

    const getUpdateNotice = async () => {
      try {
        const response = await api.get('/announcements');
        console.log('获取更新信息',response);
        if (response.data.success && response.data.data.announcements) {
          announcements.value = response.data.data.announcements;
          // 设置第一个公告的标题作为默认显示
          if (announcements.value.length > 0) {
            updateNotice.value = announcements.value[0].title;
          }
        }
      } catch (error) {
        console.error('获取更新信息失败', error);
        ElMessage.error('获取更新信息失败，请稍后重试');
      }
    }

    // 定时刷新积分
    let refreshInterval;

    onMounted(async () => {
      getUserPoints();

      await getUpdateNotice();

      // 每5分钟刷新一次积分（可根据需求调整时间）
      refreshInterval = setInterval(getUserPoints, 5 * 60 * 1000);
      
      // 根据是否有未读公告决定是否显示欢迎弹窗
      setTimeout(() => {
        if (shouldShowDialog.value) {
          showWelcomeDialog.value = true;
        }
      }, 500); // 延迟500ms显示，让页面先加载完成
    });

    onUnmounted(() => {
      clearInterval(refreshInterval);
    });

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };

    // 标记公告为已读
    const markAnnouncementAsRead = async (announcementId) => {
      try {
        await api.post(`/announcements/${announcementId}/read`);
        console.log(`公告 ${announcementId} 已标记为已读`);
      } catch (error) {
        console.error('标记公告已读失败:', error);
        ElMessage.error('标记公告已读失败，请稍后重试');
      }
    };

    // 标记所有未读公告为已读的标志
    const isMarkingAsRead = ref(false);

    // 标记所有未读公告为已读
    const markAllAnnouncementsAsRead = async () => {
      if (isMarkingAsRead.value) return; // 防止重复调用
      isMarkingAsRead.value = true;
      
      try {
        for (const announcement of unreadAnnouncements.value) {
          await markAnnouncementAsRead(announcement.id);
        }
      } finally {
        isMarkingAsRead.value = false;
      }
    };

    // 关闭欢迎弹窗并标记所有未读公告为已读
    const closeWelcomeDialog = async () => {
      // 只有在非系统公告点击时才标记为已读
      if (!isSystemAnnouncementClick.value) {
        await markAllAnnouncementsAsRead();
      }
      showWelcomeDialog.value = false;
      isSystemAnnouncementClick.value = false; // 重置标志
    };

    // 点击已读按钮
    const handleReadClick = () => {
      showWelcomeDialog.value = false;
    };

    // 处理系统公告点击事件
    const handleSystemAnnouncementClick = () => {
      console.log('触发')
      isSystemAnnouncementClick.value = true;
      showWelcomeDialog.value = true; // 无条件显示对话框
    };

    return {
      modules: [Autoplay, Pagination],
      userPoints,
      userName,
      carouselItems,
      headerItems,
      newsItems,
      showWelcomeDialog,
      updateNotice,
      announcements,
      unreadAnnouncements,
      shouldShowDialog,
      formatDate,
      getUserPoints, // 如果需要外部调用可以暴露
      closeWelcomeDialog,
      handleReadClick,
      handleSystemAnnouncementClick,
      displayAnnouncements,
      isSystemAnnouncementClick,
    };
  },
};
</script>

<style scoped>
/* 基础样式 */
:root {
  --primary-color: #4361ee;
  --secondary-color: #3f37c9;
  --accent-color: #4895ef;
  --light-color: #f8f9fa;
  --dark-color: #212529;
  --success-color: #4cc9f0;
  --warning-color: #f8961e;
  --danger-color: #f72585;
  --border-radius: 12px;
  --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  --transition: all 0.3s ease;
}

/* 容器布局 */
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  position: relative;
  background-image: url('/imgs/mainpage/jingganglan-1.png'), url('/imgs/mainpage/jingganglan-2.png');
  background-size: 100% 10%, 100% 100%;
  background-position: center 28%, center 100%;
  background-repeat: no-repeat, no-repeat;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 16px;
  width: 100%;
  max-width: 100%;
  margin: 0 auto;
}

/* 欢迎文字 */
.welcome {
  font-size: 15px;
  font-weight: 500;
  color: white;
}

.spacer {
  height: 40px;
}

/* 轮播图样式 */
.carousel {
  width: 100%;
  max-width: 343px;
  height: 148px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: var(--box-shadow);
  position: relative;
  margin: 0 auto;
  opacity: 1;
  z-index: 1; /* 设置较低的z-index，让背景图显示在上面 */
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 8px 16px;
  font-size: 14px;
}

/* 头部导航样式 */
.header {
  display: flex;
  justify-content: space-between; /* 保持元素均匀分布 */
  width: 100%;
  max-width: 343px;
  height: 50px;
  padding: 0; /* 移除内边距 */
  background-color: transparent;
  margin: 0 auto;
  position: relative; /* 为伪元素定位做准备 */
}

.header-item {
  flex: 0 0 60px; /* 固定每个项目宽度为60px */
  text-decoration: none;
}

.header-item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  cursor: pointer;
  transition: var(--transition);
  width: 100%; /* 确保内容占满整个项目宽度 */
}

.header-image {
  width: 24px;
  height: 24px;
  margin-bottom: 2px;
  object-fit: contain;
}

.header-text {
  font-size: 10px;
  font-weight: 500;
  color: var(--dark-color);
  white-space: nowrap;
}

/* 操作区域样式 */
.action-area {
  width: 100%;
  max-width: 343px;
  margin: 0 auto;
}

.action-grid-horizontal {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  width: 100%;
  overflow:hidden;
}



.action-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  cursor: pointer;
  transition: var(--transition);
}

.action-item:hover {
  transform: scale(1.05);
}

.action-image1 {
  width: 175%;
  height: auto;
  max-width: 180px;
  object-fit: contain;
  border-radius: 8px;
  margin-left: 50px;
  margin-top: -5px;
}

.action-image2 {
  width: 175%;
  height: auto;
  max-width: 180px;
  object-fit: contain;
  border-radius: 8px;
  margin-left: 12px;
  z-index: 1;
}

.action-image3 {
  width: 175%;
  height: auto;
  max-width: 180px;
  object-fit: contain;
  border-radius: 8px;
  margin-left: 20px;
  margin-top: 0px;
}

.tips {
  width: 100%;
  max-width: 343px;
  margin: 0 auto;
  padding: 12px 20px;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  color: var(--primary-color);
  background-color: rgba(67, 97, 238, 0.1);
  border: 1px solid var(--primary-color);
  border-radius: 25px;
  box-shadow: 0 2px 8px rgba(67, 97, 238, 0.15);
  color: #22a7ff;
  margin-top: -50px;
}

/* 热门资讯 */
.hot-news {
  width: 100%;
  max-width: 343px;
  padding: 16px;
  background-color: white;
  border-radius: 12px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin: 0 auto;
  opacity: 1;
}

.news-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--dark-color);
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.news-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.news-item {
  font-size: 13px;
  color: #555;
  display: flex;
  align-items: center;
  line-height: 1.4;
}

.news-dot {
  color: var(--primary-color);
  margin-right: 8px;
  font-size: 16px;
}

/* Swiper分页样式 */
:deep(.swiper-pagination-bullet-active) {
  background: var(--primary-color) !important;
}

/* 欢迎弹窗样式 */
:deep(.welcome-dialog .el-dialog__body) {
  background-image: url('/imgs/mainpage/gengxintishi.png');
  background-size: 100% 100%;
  background-position: center bottom;
  background-repeat: no-repeat;
  position: relative;
  /* 调整背景图透明度，值范围0-1，0为完全透明，1为完全不透明 */
  opacity: 1;
  padding-bottom: 60px;
}

:deep(.welcome-dialog .el-dialog__body::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* 调整遮罩层透明度，最后一个数值控制透明度(0-1) */
  background: rgba(255, 255, 255, 0.3);
  z-index: 1;
}

.welcome-content {
  text-align: center;
  padding: 40px 20px 0 20px;
  position: relative;
  z-index: 2;
  height: calc(100% - 80px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.welcome-icon {
  font-size: 48px;
  margin-bottom: 16px;
  animation: bounce 2s infinite;
}

.welcome-content h3 {
  color: var(--primary-color);
  font-size: 26px;
  font-weight: 600;
  margin: 0 0 20px 0;
}

.welcome-content p {
  color: #666;
  font-size: 16px;
  margin: 0 0 24px 0;
  line-height: 1.5;
}

.welcome-features {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 30px;
}

.announcements-container {
  max-height: 200px;
  overflow-y: auto;
  padding-right: 8px;
  scrollbar-width: thin;
  scrollbar-color: var(--primary-color) #f1f1f1;
}

.announcements-container::-webkit-scrollbar {
  width: 6px;
}

.announcements-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.announcements-container::-webkit-scrollbar-thumb {
  background: var(--primary-color);
  border-radius: 3px;
}

.announcements-container::-webkit-scrollbar-thumb:hover {
  background: var(--secondary-color);
}

.announcement-item {
  padding: 12px 16px;
  margin-bottom: 12px;
  border-radius: 8px;
  transition: var(--transition);
}

.announcement-item:hover {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.announcement-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--dark-color);
  margin: 0;
}

.announcement-priority {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
  text-transform: uppercase;
}

.announcement-priority.high {
  background: #ffebee;
  color: #c62828;
}

.announcement-priority.medium {
  background: #fff3e0;
  color: #ef6c00;
}

.announcement-priority.low {
  background: #e8f5e8;
  color: #2e7d32;
}

.announcement-content {
  font-size: 13px;
  color: #555;
  line-height: 1.4;
  margin-bottom: 8px;
}

.announcement-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #888;
}

.announcement-time,
.announcement-author {
  font-size: 11px;
  color: #888;
}

.no-announcements {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
  font-style: italic;
}

:deep(.welcome-dialog .el-dialog__footer) {
  padding: 15px 20px;
  border-top: none;
  background: transparent;
  position: absolute;
  bottom: 10;
  left: 0;
  right: 0;
  z-index: 3;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 0;
  position: absolute;
  bottom: 10;
  left: 0;
  right: 0;
  background: transparent;
  z-index: 3;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

/* 弹窗响应式样式 */
@media (max-width: 480px) {
  .welcome-content {
    padding: 30px 15px 0 15px;
    height: calc(100% - 70px);
  }
  
  .welcome-icon {
    font-size: 40px;
  }
  
  .welcome-content h3 {
    font-size: 22px;
    margin: 0 0 15px 0;
  }
  
  .welcome-content p {
    font-size: 14px;
  }
  
  .welcome-features {
    gap: 15px;
    margin-top: 25px;
  }
  
  .feature-item {
    padding: 10px 12px;
  }
  
  :deep(.welcome-dialog .el-dialog__footer) {
    padding: 10px 15px;
  }
  
  :deep(.welcome-dialog .el-dialog__body) {
    padding-bottom: 50px;
  }
}
</style>
