<template>
  <div class="home">
    <nav-bar/>
    <div class="jianjie" @click="tojianjie">
      <h2>
       <img :src="doctorimg || require('@/assets/member_tx.png')" alt="医生头像" />
      </h2>
      <h3>
        {{ yuyue.DoctorName }}
        <span>{{ yuyue.DeptName }}&nbsp;&nbsp;&nbsp;{{ yuyue.DoctorTitle }}</span>
      </h3>
    </div>
    <div class="time container">
      <span>{{ time }}</span>
      <span>{{ week }}</span>
      <em v-if="istoday">今</em>
    </div>
    
    <!-- 分时段挂号列表 - 彩色风格 -->
    <div class="time-slots container">
      <div class="section-title">可预约时段</div>
      
      <!-- 上午时段 -->
      <div v-if="morningSlots.length > 0" class="time-group morning-group">
        <div class="group-title">
          <i class="morning-icon"></i>
          <span>上午</span>
        </div>
        <div class="slots-grid">
          <div 
            v-for="(slot, index) in morningSlots" 
            :key="'morning-' + index" 
            class="slot-box morning-slot"
            :class="{ 
              'sold-out': slot.remainingCount <= 0,
              'disabled': slot.remainingCount <= 0 || loading,
              'loading': slot.loading,
              'selected': selectedSlot === slot
            }"
          
          >
            <van-loading v-if="slot.loading" size="16" color="#2c82c9" />
            <div v-else class="slot-content">
              <div class="slot-time">{{ slot.formattedStartTime }}</div>
              <div class="slot-remaining">余 {{ slot.remainingCount }} 个号</div>
              <div class="slot-money">￥ {{ slot.totalFee}}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 下午时段 -->
      <div v-if="afternoonSlots.length > 0" class="time-group afternoon-group">
        <div class="group-title">
          <i class="afternoon-icon"></i>
          <span>下午</span>
        </div>
        <div class="slots-grid">
          <div 
            v-for="(slot, index) in afternoonSlots" 
            :key="'afternoon-' + index" 
            class="slot-box afternoon-slot"
            :class="{ 
              'sold-out': slot.remainingCount <= 0,
              'disabled': slot.remainingCount <= 0 || loading,
              'loading': slot.loading,
              'selected': selectedSlot === slot
            }"
         
          >
            <van-loading v-if="slot.loading" size="16" color="#f39800" />
            <div v-else class="slot-content">
              <div class="slot-time">{{ slot.formattedStartTime }}</div>
              <div class="slot-remaining">余 {{ slot.remainingCount }} 个号</div>
              <div class="slot-money">￥ {{ slot.totalFee}}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 晚上时段（可选） -->
      <div v-if="eveningSlots.length > 0" class="time-group evening-group">
        <div class="group-title">
          <i class="evening-icon"></i>
          <span>晚上</span>
        </div>
        <div class="slots-grid">
          <div 
            v-for="(slot, index) in eveningSlots" 
            :key="'evening-' + index" 
            class="slot-box evening-slot"
            :class="{ 
              'sold-out': slot.remainingCount <= 0,
              'disabled': slot.remainingCount <= 0 || loading,
              'loading': slot.loading,
              'selected': selectedSlot === slot
            }"
          
          >
            <van-loading v-if="slot.loading" size="16" color="#662d91" />
            <div v-else class="slot-content">
              <div class="slot-time">{{ slot.formattedStartTime }}</div>
              <div class="slot-remaining">余 {{ slot.remainingCount }} 个号</div>
              <div class="slot-money">￥ {{ slot.totalFee}}</div>
            </div>
          </div>
        </div>
      </div>
      
      <van-empty description="暂无可用时段" v-if="validTimeSlots.length === 0 && !loading" style="padding-top:90px" />
      <van-loading v-if="loading" size="30" color="#46c3b0" style="padding: 50px 0" />
    </div>
  </div>
</template>

<script>
import { PartimeQuery,getinfoByName } from "@/request/api.js";
import { Cell, Empty, Toast, Loading } from "vant";

export default {
  components: {
    VanCell: Cell,
    VanEmpty: Empty,
    VanLoading: Loading
  },
  data() {
    return {
      active: 0,
      title: "",
      flag: false,
      istoday: false,
      time: "",
      week: "",
      info: {},
      yuyue: {},
      timeSlots: [], // 所有时段数据
      loading: false,
      selectedSlot: null, // 新增：记录选中的时段
      doctorimg: '', // 医生头像
      doctorid: '', // 医生id
    };
  },
  mounted() {
    this.title = this.$route.meta.title;
    this.yuyue = JSON.parse(sessionStorage.getItem("yuyue")) || {};
    
    if (this.yuyue.t) {
      this.time = this.yuyue.t;
      let wk = new Date(this.time).getDay();
      this.week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][wk];
      
      // 检查是否是今天
      const today = new Date().toISOString().split('T')[0];
      this.istoday = this.time === today;
      
      // 获取时段数据
      this.OutpSchedulePartimeQuery();
    }
    this.getDoctorInfo();
  },
  computed: {
    // 过滤出有效的时段（未过期且有余号）
  validTimeSlots() {
  const now = new Date();
  let accumulatedTotal = 0; // 全局累计总数
  
  return this.timeSlots
    .map(slot => {
      // 累计之前的总号数
      const previousTotal = accumulatedTotal;
      // 当前时段总号数
      const currentTotal = parseInt(slot.ParTimeId, 10) || 0;
      // 更新累计总数
      accumulatedTotal += currentTotal;
      
      // 当前剩余号数
      const remainingCount = parseInt(slot.SerialNo, 10) || 0;
      // 当前后台已使用号数
      const currentUsed = currentTotal - remainingCount;
      
      // 计算起始号码（基于累计）
      const startNumber = previousTotal + currentUsed + 1;
      const endNumber = previousTotal + currentTotal;
      
      // 格式化时间
      const formattedStartTime = this.formatTime(slot.StartTime);
      const formattedEndTime = this.formatTime(slot.EndTime);
       // 计算总费用
        const totalFee = (parseFloat(slot.ClinicFee) + parseFloat(slot.RegistrationFee)).toFixed(2);
      return {
        ...slot,
        startNumber,
        endNumber,
        remainingCount,
        formattedStartTime,
        formattedEndTime,
        hour: this.parseTime(slot.StartTime).getHours(),
        totalFee // 获取小时用于分组
      };
    })
    .filter(slot => {
      // 过滤掉时间格式化失败的时段
      if (slot.formattedStartTime.includes('NaN') || slot.formattedEndTime.includes('NaN')) {
        console.warn('无效的时间格式:', slot);
        return false;
      }
      
      const endTime = this.parseTime(slot.EndTime);
      // 检查时段是否已结束
      const isExpired = endTime <= now;
      return !isExpired && slot.remainingCount > 0;
    });
},
    // 上午时段 (6:00 - 12:00)
    morningSlots() {
      return this.validTimeSlots.filter(slot => slot.hour >= 6 && slot.hour < 12);
    },
    // 下午时段 (12:00 - 18:00)
    afternoonSlots() {
      return this.validTimeSlots.filter(slot => slot.hour >= 12 && slot.hour < 18);
    },
    // 晚上时段 (18:00 - 24:00)
    eveningSlots() {
      return this.validTimeSlots.filter(slot => slot.hour >= 18 && slot.hour < 24);
    }
  },
  methods: {
    getDoctorInfo(){
    // console.log(this.yuyue.DoctorName);
      getinfoByName({name:this.yuyue.DoctorName, doct_code:this.yuyue.DoctorCode}).then(res => {
        console.log('医生信息:', res);
        // this.info = res.data;
        this.doctorimg = res.data.img;
        this.doctorid = res.data.id;
      })
    },
    // 解析时间字符串为Date对象，处理不同格式
    parseTime(timeStr) {
      if (!timeStr) return new Date();
      
      // 尝试多种格式解析
      const formats = [
        timeStr,
        timeStr.replace(/\//g, '-'), // 将/替换为-尝试解析
        timeStr.split(' ')[0] + 'T' + timeStr.split(' ')[1] // 转换为ISO格式
      ];
      
      for (const format of formats) {
        const date = new Date(format);
        if (!isNaN(date.getTime())) {
          return date;
        }
      }
      
      console.error('无法解析时间:', timeStr);
      return new Date();
    },
    
    // 格式化时间显示（只显示时分）
    formatTime(timeStr) {
      if (!timeStr) return '未知时间';
      
      const date = this.parseTime(timeStr);
      if (isNaN(date.getTime())) {
        return '无效时间';
      }
      
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    // 获取最新的时段数据（包含当前剩余号数）
    OutpSchedulePartimeQuery() {
      this.loading = true;
      const params = {
        StartTime: this.yuyue.t + " 00:00:00",
        EndTime: this.yuyue.t + " 23:59:59",
        DepartCode: this.yuyue.DeptCode,
        DoctorCode: this.yuyue.DoctorCode,
      };
      
      PartimeQuery(params).then(res => {
        this.loading = false;
        console.log('时段数据:', res);
        const jsonObj = this.$x2js.xml2js(res.data);
        const jsonObj2 = jsonObj.Envelope.Body.MOP_OutpSchedulePartimeQueryResponse.request;
        console.log(jsonObj2);
        if (jsonObj2.request.returnresult.returncode === "1") {
          // 处理获取到的时段数据
          let rawSlots = jsonObj2.request.data || [];
          
          // 确保rawSlots是数组
          if (!Array.isArray(rawSlots)) {
            rawSlots = [rawSlots];
          }
          
          // 按开始时间排序（从早到晚）
          rawSlots.sort((a, b) => {
            const timeA = this.parseTime(a.StartTime).getTime();
            const timeB = this.parseTime(b.StartTime).getTime();
            return timeA - timeB;
          });
          
          this.timeSlots = rawSlots;
        }
      }).catch(err => {
        this.loading = false;
        console.error('获取时段数据失败:', err);
        Toast('获取预约时段失败，请稍后重试');
      });
    },
    
    // 处理时段点击事件
    handleSlotClick(slot) {
      if (slot.remainingCount <= 0 || this.loading) {
        Toast('该时段已约满');
        return;
      }
      
      // 记录选中状态
      this.selectedSlot = slot;
      
      // 标记当前时段正在加载
      const slotIndex = this.timeSlots.findIndex(s => s.StartTime === slot.StartTime && s.EndTime === slot.EndTime);
      if (slotIndex !== -1) {
        this.$set(this.timeSlots[slotIndex], 'loading', true);
      }
      
      // 准备跳转数据 - 参数保持不变
      this.yuyue.w = this.week;
      this.yuyue.ClinicFee = slot.ClinicFee;
      this.yuyue.RegistrationFee = slot.RegistrationFee;
      this.yuyue.m = (parseFloat(slot.ClinicFee) + parseFloat(slot.RegistrationFee)).toFixed(2);
      this.yuyue.slotTime = `${slot.formattedStartTime}`;
      this.yuyue.Number = slot.startNumber+''; // 当前起始号码（用户将获得的号码）
      this.yuyue.slotInfo = slot; // 携带完整的时段信息
      
      sessionStorage.setItem("yuyue", JSON.stringify(this.yuyue));
      
      // 跳转到挂号详情页
      this.$router.push({ path: "/Ghxq" }).then(() => {
        // 重置加载状态和选中状态
        this.selectedSlot = null;
        if (slotIndex !== -1) {
          this.$set(this.timeSlots[slotIndex], 'loading', false);
        }
      });
    },
    
    toDecimal2(x) {
      const f = parseFloat(x);
      if (isNaN(f)) return false;
      return (Math.round(x * 100) / 100).toFixed(2);
    },
    tojianjie(){
      // 根据名字查找数据库id，然后查找简介
      this.$router.push({ 
      path: "/Hospital_zjjs_detail",
      query: { id: this.doctorid }
    });
    
    },
  }
};
</script>

<style scoped lang="scss">
.jianjie {
  background: #fff;
  box-sizing: border-box;
  padding: 0.25rem;
  display: flex;
  border-bottom: 0.25rem solid #f5f5f5;

  h2 img {
    width: 1.5rem;
    height: 1.5rem;
    border-radius: 50%;
    margin-right: 0.25rem;
  }

  h3 {
    color: #333;
    font-size: 0.45rem;
    position: relative;
    padding-top: 0.1rem;

    span {
      font-size: 0.35rem;
      padding-top: 0.25rem;
      display: block;
    }
  }
}

.time {
  line-height: 1.5rem;
  font-size: 0.375rem;
  color: #333;
  background: #fff;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  padding: 0 0.25rem;

  span {
    padding-right: 0.325rem;
  }

  em {
    width: 0.5rem;
    height: 0.5rem;
    line-height: 0.5rem;
    text-align: center;
    background: #46c3b0;
    border-radius: 50%;
    font-size: 0.3rem;
    color: #fff;
    display: block;
  }
}

.time-slots {
  background: #fff;
  margin-top: 0.25rem;
  padding-bottom: 0.5rem;

  .section-title {
    font-size: 0.4rem;
    color: #333;
    padding: 0.3rem 0.25rem;
    border-bottom: 2px solid #f0f0f0;
    margin-bottom: 0.3rem;
    font-weight: 600;
  }
  
  .time-group {
    padding: 0 0.25rem 0.4rem;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      left: 0.25rem;
      right: 0.25rem;
      bottom: 0;
      height: 1px;
      background: linear-gradient(90deg, transparent, #eee, transparent);
    }
    
    &:last-child::after {
      display: none;
    }
    
    .group-title {
      display: flex;
      align-items: center;
      font-size: 0.37rem;
      margin-bottom: 0.3rem;
      font-weight: 600;
      padding-left: 0.1rem;
      
      i {
        width: 0.1rem;
        height: 0.3rem;
        border-radius: 0.05rem;
        margin-right: 0.15rem;
      }
    }
    
    .slots-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(1.5rem, 1fr));
      gap: 0.45rem;
    }
    
    .slot-box {
      border-radius: 0.15rem;
      padding: 0.3rem 0.15rem;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      min-height: 1.3rem;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 5px rgba(0,0,0,0.05);
      
      &:not(.disabled):hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 12px rgba(0,0,0,0.1);
      }
      
      &.disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
      }
      
      &.sold-out {
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          top: 50%;
          left: 0;
          right: 0;
          height: 1px;
          background: #999;
          transform: rotate(-15deg) translateY(-50%);
        }
      }
      
      &.loading {
        cursor: wait;
      }
      
      &.selected {
        transform: scale(1.05);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      }
      
      .slot-content {
        width: 100%;
      }
      
      .slot-time {
        font-size: 0.4rem;
        font-weight: 600;
        margin-bottom: 0.1rem;
      }
      
      .slot-remaining {
        font-size: 0.3rem;
        opacity: 0.9;
      }
      .slot-money{
        font-size: 0.3rem;
        opacity: 0.9;
      }
    }
  }
  
  // 上午时段样式
  .morning-group {
    .group-title {
      color: #2c82c9;
      
      i.morning-icon {
        background-color: #2c82c9;
      }
    }
    
    .slot-box.morning-slot {
      background: linear-gradient(145deg, #e6f0fa, #ffffff);
      border: 1px solid #d1e4f5;
      
      .slot-time {
        color: #2c82c9;
      }
      
      &.selected {
        background: linear-gradient(145deg, #d1e4f5, #b9d4f0);
        border-color: #2c82c9;
      }
      
      &.sold-out {
        background: linear-gradient(145deg, #f5f7fa, #e9ecef);
        border-color: #dee2e6;
        
        .slot-time, .slot-remaining,.slot-money {
          color: #868e96;
        }
      }
    }
  }
  
  // 下午时段样式
  .afternoon-group {
    .group-title {
      color: #f39800;
      
      i.afternoon-icon {
        background-color: #f39800;
      }
    }
    
    .slot-box.afternoon-slot {
      background: linear-gradient(145deg, #fff8e6, #ffffff);
      border: 1px solid #ffe8b3;
      
      .slot-time {
        color: #f39800;
      }
      
      &.selected {
        background: linear-gradient(145deg, #ffe8b3, #ffdd80);
        border-color: #f39800;
      }
      
      &.sold-out {
        background: linear-gradient(145deg, #f5f7fa, #e9ecef);
        border-color: #dee2e6;
        
        .slot-time, .slot-remaining,.slot-money {
          color: #868e96;
        }
      }
    }
  }
  
  // 晚上时段样式
  .evening-group {
    .group-title {
      color: #662d91;
      
      i.evening-icon {
        background-color: #662d91;
      }
    }
    
    .slot-box.evening-slot {
      background: linear-gradient(145deg, #f8f0ff, #ffffff);
      border: 1px solid #e9d9ff;
      
      .slot-time {
        color: #662d91;
      }
      
      &.selected {
        background: linear-gradient(145deg, #e9d9ff, #d4b9ff);
        border-color: #662d91;
      }
      
      &.sold-out {
        background: linear-gradient(145deg, #f5f7fa, #e9ecef);
        border-color: #dee2e6;
        
        .slot-time, .slot-remaining ,.slot-money{
          color: #868e96;
        }
      }
    }
  }
}
</style>
