<template>
  <div class="home">
    <nav-bar />
    <div class="bj"></div>

    <!-- 搜索框 -->
    <div class="zstj_tc">
      <div class="container">
        <div class="search">
          <div class="searchBox">
            <input
              type="text"
              v-model="searchKeyword"
              placeholder="输入搜索关键词"
              @input="handleSearch"
            />
            <img src="../assets/search1.png" />
          </div>
        </div>
      </div>
    </div>

    <!-- 日期选择 -->
    <ul class="timeSlelct">
      <li
        v-for="(item, index) in same_week"
        :class="{ active: same_day === item.date }"
        @click="timeSlelct(item)"
        :key="index"
      >
        <div>{{ item.week }}</div>
        <div>{{ item.name }}</div>
        <span></span>
      </li>
    </ul>

    <!-- 项目列表 -->
    <div class="container-wrapper">
      <div class="container">
        <div class="zstj_tc1">
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了">
            <ul>
              <li
                v-for="item in filteredList"
                :key="item.id"
                :class="{ selected: selectedItems.includes(item.id) }"
                @click="toggleSelection(item.id)"
              >
                <div class="checkbox-container">
                  <div class="checkbox" :class="{ checked: selectedItems.includes(item.id) }">
                    <span v-if="selectedItems.includes(item.id)">✓</span>
                  </div>
                </div>
                <div class="content">
                  <h2>
                    {{ item.name }}
                    <p>{{ item.explain }}</p>
                  </h2>
                  <h3>¥{{ item.price }}</h3>
                </div>
              </li>
            </ul>
          </van-list>
        </div>
      </div>
    </div>

    <!-- 底部预约按钮 -->
    <div class="bottom-actions" v-if="selectedItems.length > 0">
      <div class="action-buttons">
        <button class="btn-appointment" @click="makeAppointment">立即预约</button>
      </div>
    </div>
  </div>
</template>

<script>
import { apiOpTiQuery } from "@/request/api.js";
import { Toast } from 'vant';

export default {
  name: 'Home',
  data() {
    return {
      searchKeyword: "",
      same_week: [],
      same_day: "",
      selectedItems: [],
      list: [],
      filteredList: [],
      loading: false,
      finished: false,
      allDataCache: {}, // 缓存格式: { "2025/10/13": [item1, item2, ...] }
    };
  },
  created() {
    this.initDateList();
  },
  activated() {
    const apiDate = this.formatDateForAPI(this.same_day);
    if (this.allDataCache[apiDate]) {
      this.displayData(this.allDataCache[apiDate]);
    } else {
      this.fetchDataForDate(this.same_day);
    }
  },
  methods: {
    toggleSelection(itemId) {
      const index = this.selectedItems.indexOf(itemId);
      if (index > -1) {
        this.selectedItems.splice(index, 1);
      } else {
        this.selectedItems.push(itemId);
      }
    },

    makeAppointment() {
      if (this.selectedItems.length === 0) {
        Toast('请先选择项目');
        return;
      }

      const selectedItemsInfo = this.list.filter(item =>
        this.selectedItems.includes(item.id)
      );

      this.$router.push({
        path: 'Zstj_detail',
        query: {
          items: JSON.stringify(selectedItemsInfo),
          seldate: this.same_day
        }
      });
      Toast.success(`已选择 ${this.selectedItems.length} 个项目进行预约`);
    },

    handleSearch() {
      const keyword = this.searchKeyword.trim().toLowerCase();
      if (!keyword) {
        this.filteredList = [...this.list];
        return;
      }

      const filtered = this.list.filter(item =>
        item.name?.toLowerCase().includes(keyword) ||
        item.explain?.toLowerCase().includes(keyword)
      );

      this.filteredList = filtered;
      if (filtered.length === 0) {
        Toast('未找到匹配内容');
      }
    },

    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_week = dates;
      this.same_day = dates[0].date;
      this.fetchDataForDate(this.same_day);
    },

    timeSlelct(item) {
      this.same_day = item.date;
      this.selectedItems = [];
      this.searchKeyword = "";
      this.list = [];
      this.filteredList = [];

      const apiDate = this.formatDateForAPI(this.same_day);
      if (this.allDataCache[apiDate]) {
        this.displayData(this.allDataCache[apiDate]);
      } else {
        this.fetchDataForDate(this.same_day);
      }
    },

    async fetchDataForDate(dateStr) {
      const apiDate = this.formatDateForAPI(dateStr);
      if (this.loading) return;

      this.loading = true;
      Toast.loading({ message: '加载中...', forbidClick: true, duration: 0 });

      try {
        const res = await apiOpTiQuery({
          startDate: apiDate,
          endDate: apiDate,
          HospitalZone: ""
        });

        const data = res.data?.data || [];
        this.allDataCache[apiDate] = data; // 缓存当天数据
        this.displayData(data);
      } catch (err) {
        console.error("请求失败:", err);
        Toast.fail('加载失败');
        this.finished = true;
      } finally {
        this.loading = false;
        Toast.clear();
      }
    },

    displayData(rawData) {
      this.list = rawData.map(item => ({
        id: item.program_id,
        name: item.category,
        price: item.price,
        explain: item.program_name,
      }));

      this.filteredList = [...this.list];
      this.finished = true; // 一次性加载完成
    },

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

<style scoped lang="scss">
ul.timeSlelct {
  background-color: white;
  display: flex;
  justify-content: space-between;
  position: fixed;
  z-index: 10;
  width: 100%;
  height: 1.8rem;
  overflow-x: auto;
  top: 2.4rem;

  li {
    padding: 0.25rem;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    background-color: rgba(22, 104, 204, 0.2);
    position: relative;
    border-left: 1px solid #f5f5f5;
    border-radius: 0.25rem;
    margin: 0.05rem;
  }

  li:nth-child(1) {
    border-left: 0;
  }

  .active {
    background-color: #166bcc;
    color: #fff;
  }
}

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

.zstj_tc {
  background: #fff;
  padding: 15px 0px;
  position: fixed;
  width: 100%;
  top: 1rem;
  z-index: 9;
}

.searchBox {
  position: relative;
  width: 100%;
  height: 64px;
  border-radius: 32px;
  font-size: 28px;
  color: #999;
  margin: 15px 0px;
}

.searchBox input {
  width: 100%;
  height: 100%;
  border-radius: 32px;
  background: #f1f1f1;
  border: none;
  text-align: center;
  padding-left: 30px;
  box-sizing: border-box;
}

.searchBox img {
  position: absolute;
  top: 18px;
  right: 20px;
  width: 28px;
  height: 28px;
}

.zstj_tc1 {
  margin-top: 120px;
  padding: 30px 0px;
  padding-bottom: 100px;
}

.zstj_tc1 ul li {
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 24px;
  box-sizing: border-box;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;

  &.selected {
    border: 2px solid #46c3b0;
    background-color: #f0f9f8;
  }
}

.checkbox-container {
  margin-right: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox {
  width: 36px;
  height: 36px;
  border: 2px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &.checked {
    background-color: #46c3b0;
    border-color: #46c3b0;
    color: white;
  }

  span {
    font-size: 24px;
    font-weight: bold;
  }
}

.content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content h2 {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.content h2 p {
  font-size: 24px;
  color: #999;
  padding-top: 10px;
  margin: 0;
}

.content h3 {
  color: #d62e25;
  font-size: 32px;
  text-align: right;
  margin: 0;
}

.container-wrapper {
  position: fixed;
  top: 2.4rem;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.container {
  height: 100%;
  overflow-y: auto;
  background: #f5f5f5;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.action-buttons {
  display: flex;
  justify-content: center;
  padding: 0 15px;
}

.btn-appointment {
  width: 80%;
  max-width: 500px;
  height: 80px;
  border: none;
  border-radius: 40px;
  font-size: 28px;
  font-weight: bold;
  background-color: #46c3b0;
  color: white;
  transition: all 0.3s;
}

.btn-appointment:active {
  background-color: #3aa897;
}
</style>