<template>
  <div class="home">
    <nav-bar />
    <div class="bj"></div>
    
    <!-- 全局加载遮罩 -->
    <div v-if="globalLoading" class="global-loading">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-text">数据加载中...</div>
      </div>
    </div>
    
    <div v-show="!globalLoading" class="zstj_tc_detail">
      <!-- 总标题与总价 -->
      <div class="box">
        <div class="container">
          <h2>已选套餐</h2>
          <h3>¥{{ totalPrice }}</h3>
        </div>
      </div>

      <!-- 各项目详情 -->
      <div
        class="box3"
        v-for="(item, index) in detailList"
        :key="index"
      >
        <div class="bt">
          {{ item.name }}
        <p class="time">
  {{ 
    item.detailData 
      ? (item.detailData.time && item.detailData.time_period2 
          ? item.detailData.time_period2 + ' ' + item.detailData.time 
          : '可按其他时间到院咨询')
      : '可按其他时间到院咨询' 
  }}
</p>
        </div>
        <div class="info">
           <p><strong>项目价格：</strong>¥{{ item.price }}</p>
          <p><strong>项目说明：</strong>{{ item.explain }}</p>
          <p v-if="item.detailData && item.detailData.specialRequests">
            <strong>注意事项：</strong>{{ item.detailData.specialRequests }}
          </p>
           <p v-if="item.detailData"><strong>项目详情：</strong>{{ item.detailData.program_items }}</p>
        
        </div>
      </div>

      <div class="gao"></div>
    </div>

    <!-- 立即预约按钮 -->
    <div class="zstj_tc_detail_ljyy" @click="yuyue">
      <span>立即预约</span>
    </div>
  </div>
</template>

<script>
import { apiGetDetail, apiOpTjYy } from "@/request/api.js";
import { Toast,Dialog } from "vant";

export default {
  data() {
    return {
      detailList: [], // 存储多个项目及其详情
      seldate: "",     // 预约日期
      globalLoading: true // 全局加载状态
    };
  },
  mounted() {
    this.seldate = this.$route.query.seldate;
    const itemsStr = this.$route.query.items;

    if (!itemsStr) {
      Toast("未传入项目信息");
      this.globalLoading = false;
      return;
    }

    try {
      const items = JSON.parse(itemsStr);
      this.getData(items);
    } catch (e) {
      Toast("项目数据解析失败");
      console.error(e);
      this.globalLoading = false;
    }
  },
  computed: {
    // 计算总价格
    totalPrice() {
      return this.detailList
        .reduce((sum, item) => sum + parseFloat(item.price || 0), 0)
        .toFixed(2);
    }
  },
  methods: {
    // 初始化项目列表并获取每个项目的详情
    getData(items) {
      console.log("传入的items", items);
      // 初始化项目列表
      this.detailList = items.map(item => ({
        ...item,
        loading: true,
        detailData: null
      }));

      // 创建所有API请求的Promise数组
      const requestPromises = this.detailList.map((item, index) => {
        console.log("当前项目", item);
        return apiGetDetail({
          programId: item.id,
          bookindDate: this.seldate,
          Type: item.type,
        })
          .then(res => {
            const data = res.data;
            console.log(data);
            const detailData = {
              time: data.time || "时间未定",
              time_period: data.time_period,
              time_period2:
                data.time_period === "AM"
                  ? "上午"
                  : data.time_period === "PM"
                  ? "下午"
                  : "全天",
              specialRequests: data.specialRequests || "无特殊要求",
              program_items: data.program_items || item.description || "无具体项目说明",
              price: item.price,
            };
            // 使用 $set 确保响应式更新
            this.$set(this.detailList[index], 'detailData', detailData);
          })
          .catch(err => {
            console.error(`获取项目 ${item.id} 详情失败`, err);
            const failData = {
              time: "获取失败",
              time_period2: "",
              specialRequests: "信息加载异常",
              program_items: item.description || "无具体项目说明",
              price: item.price,
            };
            this.$set(this.detailList[index], 'detailData', failData);
          })
          .finally(() => {
            this.$set(this.detailList[index], 'loading', false);
          });
      });

      // 等待所有请求完成后关闭全局加载状态
      Promise.all(requestPromises)
        .then(() => {
          console.log("所有项目详情加载完成");
          this.globalLoading = false;
        })
        .catch(err => {
          console.error("部分请求失败", err);
          this.globalLoading = false;
        });
    },
    // 计算年龄的函数
getAgeFromIdNo(idNo) {
  if (!idNo || idNo.length !== 18) {
    return '';
  }
  
  // 从身份证号中提取出生日期 (第7-14位)
  const birthYear = parseInt(idNo.substring(6, 10));
  const birthMonth = parseInt(idNo.substring(10, 12));
  const birthDay = parseInt(idNo.substring(12, 14));
  
  // 获取当前日期
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth() + 1;
  const currentDay = today.getDate();
  
  // 计算年龄
  let age = currentYear - birthYear;
  
  // 如果今年的生日还没到，则年龄减1
  if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
    age--;
  }
  
  return age;
},
    // 立即预约
yuyue() {
  const card = JSON.parse(sessionStorage.getItem("card"));

  if (!card) {
   Toast("未查询到用户身份，请先绑定就诊人！！");
   this.$router.push({path: "/Member_jzr"});
    return;
  }

  // 检查是否还有项目正在加载
  const hasLoading = this.detailList.some(item => item.loading);
  if (hasLoading) {
    Toast("数据加载中，请稍后...");
    return;
  }


  //  弹出确认对话框
  Dialog.confirm({
    title: '确认预约',
    message: `您即将预约以下体检项目\n日期：${this.seldate}\n姓名：${card.name}\n电话：${card.phone}\n\n请确认信息无误，是否继续？`,
    confirmButtonText: '确认预约',
    cancelButtonText: '再看看',
    closeOnPopstate: true, // 点击返回键关闭
    messageAlign: 'left'   // 左对齐显示内容，更清晰
  })
    .then(() => {
      // 用户点击"确认"
      
      // 构建精简的项目列表
      const programDetails = this.detailList.map(item => {
        const detail = item.detailData || {};
        return {
          programId: item.id,
          time: detail.time || '',
          timePeriod: detail.time_period || '',
          type:item.type
        };
      });

      const age = this.getAgeFromIdNo(card.idNo);

      const formatDateTime = () => {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hour = String(now.getHours()).padStart(2, '0');
        const minute = String(now.getMinutes()).padStart(2, '0');
        const second = String(now.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      };

      const currentDateTime = formatDateTime();

      const formatDate = (dateStr) => {
        const [year, month, day] = dateStr.split('-').map(Number);
        return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      };

      const formattedBookingDate = formatDate(this.seldate);

      const formData = {
        bookingdate: formattedBookingDate,
        username: card.name,
        phone: card.phone,
        idCard: card.idNo,
        gender: card.sex || 'xx',
        age: age,
        bookingtime: currentDateTime,
        programDetails,
      };

      console.log("提交的预约数据：", formData);

      Toast.loading({ message: '提交中...', forbidClick: true });

      apiOpTjYy(formData)
        .then(res => {
          if (res.code === 200) {
            Toast.success({ message: "预约成功", duration: 3000 });
            // 延时3秒后跳转到预约页面
            setTimeout(() => {
              this.$router.push('Zstj_yy');
            }, 4000);
          } else {
            Toast.fail(res.message || "预约失败，请重试");
          }
        })
        .catch(err => {
          console.error("预约提交失败", err);
          Toast.fail("预约提交失败，请重试");
        });
    })
    .catch(() => {
      // 用户点击"取消"或"再看看"
      // 不做任何操作
    });
}
  }
};
</script>

<style scoped lang="scss">
/* 全局加载遮罩样式 */
.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #46c3b0;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 24px;
  color: #666;
}

.bj {
  background: #f5f5f5;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
}

.zstj_tc_detail .box {
  background: #fff;
  padding: 40px 0;
  margin-bottom: 10px;
}

.zstj_tc_detail .box .container {
  display: flex;
  justify-content: space-between;
  padding: 0 30px;
}

.zstj_tc_detail .box .container h2 {
  font-size: 32px;
  color: #333;
}

.zstj_tc_detail .box .container h3 {
  color: #d62e25;
  font-size: 36px;
}

.zstj_tc_detail .box3 {
  background: #fff;
  padding: 30px;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.box3 .bt {
  display: flex;
  justify-content: space-between;
  color: #333;
  font-size: 32px;
  margin-bottom: 15px;
}

.box3 .bt .time {
  color: #46c3b0;
  font-weight: bold;
}

.box3 .info {
  font-size: 28px;
  line-height: 45px;
  color: #555;
}

.box3 .info p {
  margin: 10px 0;
}

.zstj_tc_detail_ljyy {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 90px;
  line-height: 90px;
  text-align: center;
  font-size: 32px;
  background: linear-gradient(270deg, #1ce27d, #05c6af);
  color: #fff;
  z-index: 100;
}

.gao {
  height: 90px;
}
</style>