<template>
  <div class="home">
    <nav-bar />
    <div class="bj"></div>
    
    <!-- 顶部医院图片 -->
    <div class="hospital-header">
      <div class="hospital-img-container">
        <img src="../assets/back.webp" alt="医院大楼" class="hospital-img" />
      </div>
    </div>
    
    <!-- 医院信息盒子 -->
    <div class="hospital-info-box">
      <div class="hospital-info">
        <div class="info-header">
          <!-- 医院logo -->
          <div class="hospital-logo">
            <img :src="hospitalData.logo" alt="医院logo" v-if="hospitalData.logo" />
            <!-- 兜底图片，防止接口返回logo为空 -->
            <img src="../assets/nxwjlogo2.jpg" alt="医院logo" v-else />
          </div>
          
          <!-- 医院名称和标签 -->
          <div class="info-content">
            <h1 class="hospital-name">{{ hospitalData.name || "宁夏武警总队医院" }}</h1>
            <div class="info-row">
              <div class="hospital-level">{{ hospitalData.label || "二级甲等" }}</div>
              <div class="hospital-tags">
                <!-- <span class="tag">周末上班</span> -->
                <span class="tag">现场加项</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 地址信息 -->
        <div class="address-info" @click="navigateTo('/Hospital_dh1')">
          <van-icon name="location" />
          <span>{{ hospitalData.address || "银川市兴庆区清和南街895号" }}</span>
        </div>
        
        <!-- 体检时间 -->
        <div class="time-info">
          <van-icon name="clock" />
          <div>
            <div>体检时间：{{ examTime.weekday }} {{ examTime.timeRange }}</div>
          </div>
        </div>
        
        <!-- 公告栏 -->
        <van-notice-bar scrollable left-icon="volume" background="#fff" style="padding:0 !important;">
          {{ noticeContent }}
        </van-notice-bar>
      </div>
    </div>
    
    <!-- 功能按钮区域 -->
    <div class="feature-buttons">
      <!-- 体检套餐按钮 -->
      <div class="feature-button" @click="navigateTo('/Zstj_yy')">
        <div class="button-content">
          <h3>体检套餐</h3>
          <p>超值套餐任意选</p>
        </div>
        <div class="button-image">
          <img src="../assets/zstj_pic3.png" alt="体检套餐" />
        </div>
      </div>
      
      <!-- 报告查询按钮 -->
      <div class="feature-button" @click="navigateTo('/Member_wdbg')">
        <div class="button-content">
          <h3>报告查询</h3>
          <p>体检报告随时查</p>
        </div>
        <div class="button-image">
          <img src="../assets/zstj_pic1.png" alt="报告查询" />
        </div>
      </div>
    </div>
    
    <!-- 热门体检套餐推荐（复用apiOpTiQuery接口，和体检页面一致） -->
    <div class="hot-packages">
      <div class="section-title">
        <h3>热门体检套餐</h3>
        <span @click="navigateTo('/Zstj_yy')" class="more">查看更多 ></span>
      </div>
      
      <!-- 加载状态 -->
      <div class="loading-container" v-if="packageLoading">
        <van-loading type="spinner" color="#46c3b0" />
        <p class="loading-text">正在加载套餐数据...</p>
      </div>
      
      <!-- 空数据提示 -->
      <div class="empty-container" v-else-if="hotPackageList.length === 0">
        <van-empty description="暂无热门套餐数据" image="empty" />
      </div>
      
      <!-- 套餐列表（适配体检页面字段映射） -->
      <div class="package-list" v-else>
        <div 
          class="package-card" 
          v-for="(pkg, index) in hotPackageList" 
          :key="index" 
          @click="navigateToPackage(pkg)"
        >
          <div class="package-tag" v-if="index === 0">爆款</div>
          <div class="package-name">{{ pkg.program_name || "默认体检套餐" }}</div>
          <div class="package-price">
            <span class="price">¥{{ pkg.price || 0 }}</span>
          </div>
          <div class="package-desc">{{ pkg.description || "包含基础体检项目，满足日常健康筛查需求" }}</div>
          <button class="package-btn">立即预约</button>
        </div>
      </div>
    </div>
    
    <!-- 常见问题 -->
    <div class="faq-section">
      <div class="section-title">
        <h3>常见问题</h3>
      </div>
      <div class="faq-list">
        <div class="faq-item">
          <h4>体检需要提前预约吗？</h4>
          <p>是的，为了确保体检服务质量，建议提前1-3天在线预约。</p>
        </div>
        <div class="faq-item">
          <h4>体检前需要做哪些准备？</h4>
          <p>体检前三天保持正常饮食，勿饮酒，避免剧烈运动；体检当天需空腹8-12小时。</p>
        </div>
        <div class="faq-item">
          <h4>体检报告多久可以获取？</h4>
          <p>一般情况下，体检后1-5个工作日可以通过本平台查询电子报告。</p>
        </div>
        <div class="faq-item">
          <h4>体检当天需要携带什么证件？</h4>
          <p>请携带本人身份证原件，以便登记和核实身份信息。</p>
        </div>
        <div class="faq-item">
          <h4>可以调整体检套餐内容吗？</h4>
          <p>是的，您可以根据个人需求在预约时或到院后咨询医生，进行套餐内容的调整。</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 引入所需Vant组件（和体检页面一致）
import { NoticeBar, Icon, Loading, Empty, Toast } from 'vant';
// 复用体检页面的apiOpTiQuery接口，无需额外接口
import { apiOpTiQuery, apiGetHospitalInfo } from "@/request/api.js";

export default {
  components: {
    [NoticeBar.name]: NoticeBar,
    [Icon.name]: Icon,
    [Loading.name]: Loading,
    [Empty.name]: Empty
  },
  data() {
    return {
      // 公告内容
      noticeContent: '关注健康 定期体检 - 为您的健康保驾护航 - 体检注意事项：周一至周五上午8:00-10:30体检；体检前三天保持正常饮食，勿饮酒，避免剧烈运动；体检当天需空腹8-12小时；慢性病患者请携带平时服用的药物；女性特殊时期请告知医护人员；体检当天穿宽松的衣裤。',
      // 体检时间信息
      examTime: {
        weekday: '周一到周五',
        timeRange: '08:00-10:30',
        bloodTime: '10:30'
      },
      // 医院信息（接口返回）
      hospitalData: {},
      // 热门套餐相关（复用体检页面接口逻辑）
      hotPackageList: [], // 存储前2条热门套餐数据
      packageLoading: true, // 加载状态
      same_day: '', // 默认日期（和体检页面一致）
      allDataCache: {} // 缓存数据（和体检页面缓存格式一致）
    };
  },
  mounted() {
    // 初始化日期（和体检页面initDateList逻辑一致）
    this.initDateList();
    // 获取医院信息
    this.getData();
    // 获取热门套餐数据（复用apiOpTiQuery）
    this.getHotPackageData();
  },
  methods: {
    // 路由跳转（和体检页面一致，跳转至套餐列表页）
    navigateTo(path) {
      this.$router.push(path);
    },
    navigateToPackage(pkg) {
      // 跳转到 Zstj_tc 页面并传递套餐信息，以便自动勾选
      this.$router.push({
        path: '/Zstj_tc',
        query: {
          preSelectedItems: JSON.stringify([{
            id: pkg.program_id || `package_${Date.now()}`,
            name: pkg.category || "体检套餐",
            price: pkg.price || 0,
            explain: pkg.program_name || "默认体检套餐"
          }])
        }
      });
    },

    // 获取医院信息
    getData() {
      apiGetHospitalInfo().then((res) => {
        console.log("医院信息：", res.data);
        this.hospitalData = res.data || {};
      }).catch(err => {
        console.error("获取医院信息失败：", err);
        this.hospitalData = {};
      });
    },

    // 初始化日期（完全复用体检页面逻辑，保证日期一致）
    initDateList() {
      const today = new Date();
      const todayDay = today.getDay();
      let start = new Date(today);

      // 如果今天是周末，跳到下周一
      if (todayDay === 0) start.setDate(today.getDate() + 1);
      else if (todayDay === 6) start.setDate(today.getDate() + 2);

      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
      const dates = [];
      let current = new Date(start);

      for (let i = 0; i < 5; i++) {
        const d = current.getDate();
        const m = current.getMonth() + 1;
        const dateString = `${current.getFullYear()}-${m}-${d}`;
        const week = `周${weekDays[current.getDay()]}`;
        const name = `${m}.${d}`;
        dates.push({ date: dateString, week, name });

        current.setDate(current.getDate() + 1);
        while (current.getDay() === 0 || current.getDay() === 6) {
          current.setDate(current.getDate() + 1);
        }
      }

      this.same_day = dates[0].date;
    },

    // 日期格式化（完全复用体检页面方法，保证接口参数一致）
    formatDateForAPI(dateStr) {
      const [year, month, day] = dateStr.split('-').map(Number);
      return `${year}/${String(month).padStart(2, '0')}/${String(day).padStart(2, '0')}`;
    },

    // 获取热门套餐数据（复用apiOpTiQuery接口，和体检页面逻辑一致）
    getHotPackageData() {
      this.packageLoading = true;
      const apiDate = this.formatDateForAPI(this.same_day);
      const cacheKey = apiDate + '_1'; // 1=套餐类型，和体检页面缓存key格式一致

      // 优先从缓存获取，避免重复请求
      if (this.allDataCache[cacheKey]) {
        this.handlePackageData(this.allDataCache[cacheKey]);
        this.packageLoading = false;
        return;
      }

      // 调用体检页面同款接口，请求套餐类型数据
      apiOpTiQuery({
        startDate: apiDate,
        endDate: apiDate,
        HospitalZone: "",
        Type: '1' // 1=套餐类型，和体检页面一致
      }).then((res) => {
        console.log("热门套餐数据（apiOpTiQuery）：", res.data);
        const data = res.data?.data || [];
        // 缓存数据（和体检页面缓存格式一致）
        this.allDataCache[cacheKey] = data;
        // 处理热门套餐数据（取前2条）
        this.handlePackageData(data);
      }).catch((err) => {
        console.error("套餐数据加载失败：", err);
        this.hotPackageList = [];
        Toast.fail('加载失败');
      }).finally(() => {
        this.packageLoading = false;
        Toast.clear();
      });
    },

    // 处理热门套餐数据（取前2条，适配字段映射）
    handlePackageData(rawData) {
      // 过滤有效数据，取前2条作为热门套餐
      const validData = rawData.filter(item => item.program_id && item.program_name);
      this.hotPackageList = validData.slice(0, 2); // 取前2条，保持页面简洁
    }
  }
}
</script>

<style scoped lang="scss">
.bj {
  background: #fff;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  z-index: -1;
}

/* 顶部医院图片 */
.hospital-header {
  position: relative;
  margin-bottom: -30px; /* 为信息盒子留出覆盖空间 */
}

/* 医院图片容器 */
.hospital-img-container {
  width: 100%;
  height: 5rem;
  overflow: hidden;
}

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

/* 医院信息盒子 */
.hospital-info-box {
  background: white;
  border-radius: 20px 20px 0 0; /* 只有上圆角 */
  box-shadow: 0 -5px 20px rgba(0,0,0,0.1); /* 顶部阴影 */
  padding-top: 40px; /* 为logo留出空间 */
  position: relative;
  z-index: 10;
}

/* 医院信息 */
.hospital-info {
  padding: 0 20px 20px;
}

/* 信息头部：logo + 名称和标签 */
.info-header {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 20px;
}

/* 医院logo */
.hospital-logo {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  flex-shrink: 0;
  position: absolute;
  top: -1rem; /* 向上超出盒子 */
  left: 20px;
  background: white;
  border: 3px solid white;
}

.hospital-logo img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 医院名称和标签 */
.info-content {
  flex: 1;
  margin-left: 3rem; /* 为logo留出空间 */
}

.hospital-name {
  font-size: .5rem;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: #333;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 15px;
}

.hospital-level {
  font-size: .3rem;
  color: #666;
  font-weight: 500;
}

.hospital-tags {
  display: flex;
  gap: 8px;
}

.tag {
  background: #e6f7ff;
  color: #1890ff;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: .3rem;
  font-weight: 500;
}

.address-info,
.time-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: .35rem;
  color: #666;
  position: relative;
}

.address-info {
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.time-info {
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 15px;
}

.van-notice-bar {
  margin-top: 15px;
}

.address-info van-icon,
.time-info van-icon {
  margin-right: 8px;
  margin-top: 2px;
  color: #999;
}

.time-info div {
  flex: 1;
}

.time-info div:first-child {
  font-weight: 500;
  margin-bottom: 2px;
}

/* 功能按钮区域 */
.feature-buttons {
  margin-top: 25px;
  padding: 0 15px 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-button {
  background: white;
  border-radius: 16px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.feature-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 6px;
  height: 100%;
  border-radius: 16px 0 0 16px;
}

.feature-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}

/* 体检套餐按钮样式 */
.feature-button:first-child {
  background: linear-gradient(135deg, #fff9e6 0%, #fff3cd 100%);
}

.feature-button:first-child::before {
  background: linear-gradient(180deg, #ffc107 0%, #ff9800 100%);
}

/* 报告查询按钮样式 */
.feature-button:last-child {
  background: linear-gradient(135deg, #e6f7ff 0%, #b3d9ff 100%);
}

.feature-button:last-child::before {
  background: linear-gradient(180deg, #1890ff 0%, #096dd9 100%);
}

.button-content {
  flex: 1;
}

.button-content h3 {
  font-size: .5rem;
  font-weight: bold;
  margin: 0 0 5px 0;
}

.button-content p {
  font-size: .3rem;
  color: #666;
  margin: 0;
}

.button-image {
  width: 1rem;
  height: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.button-image img {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

/* 通用标题样式 */
.section-title {
  padding: 0 15px;
  margin-bottom: 15px;
}

.section-title h3 {
  font-size: .4rem;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: inline-block;
  position: relative;
  padding-left: 12px;
}

.section-title h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: linear-gradient(180deg, #46c3b0 0%, #3aa897 100%);
  border-radius: 2px;
}

/* 热门体检套餐样式（适配体检页面超长描述） */
.hot-packages {
  margin-top: 20px;
  padding: 0 15px;
}

.more {
  font-size: .3rem;
  color: #46c3b0;
  cursor: pointer;
  margin-left: 10px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  
  .loading-text {
    font-size: .3rem;
    color: #999;
    margin-top: 10px;
  }
}

/* 空数据样式 */
.empty-container {
  padding: 20px 0;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}

.package-list {
  display: flex;
  gap: 15px;
  overflow-x: auto;
  padding-bottom: 10px;
  /* 隐藏滚动条，保留滚动功能，适配移动端 */
  &::-webkit-scrollbar {
    display: none;
  }
}

.package-card {
  min-width: 4.5rem;
  background: white;
  border-radius: 12px;
  padding: 20px 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  }
  
  .package-tag {
    position: absolute;
    top: 15px;
    right: 15px;
    background: #46c3b0;
    color: #fff;
    font-size: .25rem;
    padding: 2px 8px;
    border-radius: 8px;
  }
  
  .package-name {
    font-size: .37rem;
    font-weight: 600;
    color: #333;
    margin: 0 0 10px 0;
  }
  
  .package-price {
    margin-bottom: 10px;
    
    .price {
      font-size: .4rem;
      font-weight: bold;
      color: #d62e25;
    }
  }
  
  .package-desc {
    font-size: .28rem;
    color: #666;
    margin-bottom: 15px;
    line-height: 1.4;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 3; /* 显示3行，超出隐藏 */
    -webkit-box-orient: vertical;
  }
  
  .package-btn {
    width: 100%;
    background: linear-gradient(135deg, #46c3b0 0%, #3aa897 100%);
    color: #fff;
    border: none;
    border-radius: 8px;
    padding: 8px 0;
    font-size: .35rem;
    cursor: pointer;
    transition: background 0.3s ease;
    
    &:hover {
      opacity: 0.9;
    }
  }
}

/* 常见问题 */
.faq-section {
  margin-top: 30px;
  margin-bottom: 30px;
  padding: 0 15px;
}

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

.faq-item {
  background: white;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
}

.faq-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.faq-item h4 {
  font-size: .37rem;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.faq-item h4::before {
  content: '?';
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: linear-gradient(135deg, #46c3b0 0%, #3aa897 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  margin-right: 10px;
  flex-shrink: 0;
}

.faq-item p {
  font-size: .32rem;
  color: #666;
  margin: 0;
  line-height: 1.5;
  padding-left: 30px;
}

/* 响应式设计 */
@media screen and (min-width: 768px) {
  .home {
    max-width: 600px;
    margin: 0 auto;
    background: white;
    min-height: 100vh;
  }
  
  .hospital-img {
    height: 250px;
  }
  
  .faq-section {
    padding: 0 30px;
  }
  
  .section-title {
    padding: 0 30px;
  }
  
  .hot-packages {
    padding: 0 30px;
  }
}
</style>