<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="typeSelect">
      <div 
        :class="{ active: typeSelection === '1' }" 
        @click="typeSelection = '1'; handleTypeChange()"
      >
        套餐
      </div>
      <div 
        :class="{ active: typeSelection === '2' }" 
        @click="typeSelection = '2'; handleTypeChange()"
      >
        单项
      </div>
    </div>

    <!-- 项目列表 -->
    <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>
                    <p>{{ item.description }}</p>
                  </h2>
                  <h3>¥{{ item.price }}</h3>
                </div>
              </li>
            </ul>
          </van-list>
        </div>
      </div>
    </div>

    <!-- 底部预约列表按钮 -->
    <div class="cart-button-container">
      <div 
        class="cart-button" 
        @click="openCartPopup"
        v-if="selectedItems.length > 0"
      >
        <van-icon name="records" class="cart-icon" />
        <div class="cart-text">预约列表</div>
        <div class="cart-count">{{ selectedItems.length }}</div>
      </div>
      <div 
        class="cart-button empty" 
        @click="openCartPopup"
        v-else
      >
        <van-icon name="records" class="cart-icon" />
        <div class="cart-text">预约列表</div>
      </div>
    </div>

    <!-- 预约列表弹窗 -->
    <van-popup
      v-model="showCartPopup"
      position="bottom"
      :style="{ height: '80%', borderRadius: '20px 20px 0 0' }"
    >
      <div class="cart-popup">
        <!-- 弹窗头部 -->
        <div class="cart-popup-header">
          <h3>已选择项目 ({{ selectedItems.length }})</h3>
          <van-button 
            type="default" 
            size="small" 
            @click="closeCartPopup"
            plain
          >
            关闭
          </van-button>
        </div>

        <!-- 项目列表 -->
        <div class="cart-popup-content">
          <van-checkbox-group 
            v-model="checkedItems" 
            @change="handlePopupSelectionChange"
          >
            <van-cell-group>
              <van-cell 
                v-for="item in selectedItemsDetails" 
                :key="item.id"
                :title="item.name"
                :value="`¥${item.price}`"
                is-link
              >
                <template #extra>
                  <van-checkbox :name="item.id" />
                </template>
                <template #label>
                  <div class="item-explain">{{ item.explain }}</div>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>

        <!-- 弹窗底部操作 -->
        <div class="cart-popup-footer">
          <div class="cart-popup-actions">
            <van-button 
              type="default" 
              @click="selectAll"
              plain
            >
              全选
            </van-button>
            <van-button 
              type="danger" 
              @click="deleteSelected"
              plain
            >
              删除已选项
            </van-button>
          </div>
          <van-button 
            type="primary" 
            block 
            @click="makeAppointment"
            class="appointment-btn"
          >
            立即预约
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { apiOpTiQuery } from "@/request/api.js";
import { Toast, Popup, Button, Checkbox, CheckboxGroup, Cell, CellGroup, Icon } from 'vant';

export default {
  name: 'Home',
  components: {
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Icon.name]: Icon,
  },
  data() {
    return {
      searchKeyword: "",
      same_week: [],
      same_day: "",
      selectedItems: [],
      selectedItemsDetails: [], // 存储选择的项目详情
      list: [],
      filteredList: [],
      loading: false,
      finished: false,
      allDataCache: {}, // 缓存格式: { "2025/10/13": [item1, item2, ...] }
      typeSelection: "1", // 1: 套餐, 2: 单项
      showCartPopup: false, // 控制预约列表弹窗显示
      checkedItems: [], // 控制弹窗中选择的项目
    };
  },
  created() {
    this.initDateList();
  },
  activated() {
    const apiDate = this.formatDateForAPI(this.same_day);
      if (this.allDataCache[apiDate + '_' + this.typeSelection]) {
        this.displayData(this.allDataCache[apiDate + '_' + this.typeSelection]);
      } else {
        this.fetchDataForDate(this.same_day);
      }
  },
  methods: {
    toggleSelection(itemId) {
      const index = this.selectedItems.indexOf(itemId);
      if (index > -1) {
        this.selectedItems.splice(index, 1);
        this.selectedItemsDetails = this.selectedItemsDetails.filter(item => item.id !== itemId);
      } else {
        this.selectedItems.push(itemId);
        const itemDetails = this.list.find(item => item.id === itemId);
        if (itemDetails) {
          this.selectedItemsDetails.push(itemDetails);
        }
      }
      // 同步到弹窗的选择状态
      this.checkedItems = [...this.selectedItems];
    },

    // 打开预约列表弹窗
    openCartPopup() {
      if (this.selectedItems.length === 0) {
        Toast('请先选择项目');
        return;
      }
      this.showCartPopup = true;
    },

    // 关闭预约列表弹窗
    closeCartPopup() {
      this.showCartPopup = false;
    },

    // 处理弹窗中的选择变化
    handlePopupSelectionChange(checkedIds) {
      this.checkedItems = checkedIds;
    },

    // 全选功能
    selectAll() {
      if (this.checkedItems.length === this.selectedItems.length) {
        // 如果已经全选，则取消全选
        this.checkedItems = [];
        Toast.success('已取消全选');
      } else {
        // 全选所有项目
        this.checkedItems = [...this.selectedItems];
        Toast.success('已全选');
      }
    },

    // 删除已选项功能
    deleteSelected() {
      if (this.checkedItems.length === 0) {
        Toast('请先选择要删除的项目');
        return;
      }
      
      // 保存要删除的项目数量
      const deletedCount = this.checkedItems.length;
      
      // 删除选中的项目
      this.selectedItems = this.selectedItems.filter(id => 
        !this.checkedItems.includes(id)
      );
      this.selectedItemsDetails = this.selectedItemsDetails.filter(item => 
        !this.checkedItems.includes(item.id)
      );
      
      // 清空选择状态
      this.checkedItems = [];
      
      // 如果没有项目了，关闭弹窗
      if (this.selectedItems.length === 0) {
        this.closeCartPopup();
      }
      
      Toast.success(`已删除 ${deletedCount} 个项目`);
    },

    // 确认预约
    makeAppointment() {
      if (this.checkedItems.length === 0) {
        Toast('请先在弹窗中选择要预约的项目');
        return;
      }

      // 只提交弹窗中勾选的项目
      const selectedForAppointment = this.selectedItemsDetails.filter(item => 
        this.checkedItems.includes(item.id)
      );

      this.$router.push({
        path: 'Zstj_detail',
        query: {
          items: JSON.stringify(selectedForAppointment),
          seldate: this.same_day
        }
      });
      this.closeCartPopup();
      Toast.success(`已选择 ${selectedForAppointment.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.searchKeyword = "";
      this.list = [];
      this.filteredList = [];

      const apiDate = this.formatDateForAPI(this.same_day);
      const cacheKey = apiDate + '_' + this.typeSelection;
      if (this.allDataCache[cacheKey]) {
        this.displayData(this.allDataCache[cacheKey]);
      } 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: "",
          Type: this.typeSelection
        });

        const data = res.data?.data || [];
        console.log(data);
        this.allDataCache[apiDate + '_' + this.typeSelection] = 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,
        description:item.description,
        type: this.typeSelection// 添加类型标识
      }));

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

    handleTypeChange() {
      // 切换类型时重新加载数据
      this.list = [];
      this.filteredList = [];
      this.finished = false;
      this.loading = false;
      
      const apiDate = this.formatDateForAPI(this.same_day);
      if (this.allDataCache[apiDate + '_' + this.typeSelection]) {
        this.displayData(this.allDataCache[apiDate + '_' + this.typeSelection]);
      } else {
        this.fetchDataForDate(this.same_day);
      }
    },

    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;
  }
}

/* 类型选择样式 */
.typeSelect {
  display: flex;
  justify-content: center;
  background: white;
  padding: 10px;
  position: fixed;
  top: 4.2rem;
  left: 0;
  width: 100%;
  z-index: 9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.typeSelect div {
  flex: 1;
  max-width: 200px;
  text-align: center;
  padding: 12px;
  margin: 0 5px;
  border-radius: 25px;
  background: #f5f5f5;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: bold;
  font-size: 24px;
}

.typeSelect div.active {
  background: #46c3b0;
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 3px 10px rgba(70, 195, 176, 0.3);
}

.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: 25px;
  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: 4.6rem;
  left: 0;
  right: 0;
  bottom: 1.5rem;
  overflow: hidden;
}

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

/* 预约列表按钮样式 */
.cart-button-container {
  position: fixed;
  bottom: 0.6rem;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
}

.cart-button {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #46c3b0 0%, #3aa897 100%);
  color: white;
  padding: 15px 30px;
  border-radius: 50px;
  box-shadow: 0 5px 20px rgba(70, 195, 176, 0.3);
  cursor: pointer;
  transition: all 0.3s;
  font-weight: bold;
  font-size: 24px;
  position: relative;
}

.cart-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(70, 195, 176, 0.4);
}

.cart-button:active {
  transform: translateY(-1px);
}

.cart-button.empty {
  background: #f5f5f5;
  color: #666;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.cart-button.empty:hover {
  background: #e8e8e8;
}

.cart-icon {
  font-size: 32px;
  margin-right: 10px;
}

.cart-count {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

/* 预约列表弹窗样式 */
.cart-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.cart-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.cart-popup-header h3 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
}

.cart-popup-content {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.item-explain {
  font-size: 20px;
  color: #666;
  margin-top: 5px;
}

.cart-popup-footer {
  padding-top: 20px;
  padding-bottom: calc(20px + env(safe-area-inset-bottom) + env(safe-area-inset-bottom) / 2);
  padding-bottom: calc(20px + constant(safe-area-inset-bottom) + constant(safe-area-inset-bottom) / 2);
  border-top: 1px solid #eee;
}

.cart-popup-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.appointment-btn {
  height: 80px;
  font-size: 28px;
  font-weight: bold;
}

/* Vant组件样式覆盖 */
.van-popup {
  padding-top: 0 !important;
  /* 确保弹窗底部适配安全区域 */
  padding-bottom: env(safe-area-inset-bottom) !important;
  padding-bottom: constant(safe-area-inset-bottom) !important;
}

/* 为iOS设备添加额外的安全区域适配 */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
  .cart-popup {
    padding-bottom: env(safe-area-inset-bottom) !important;
  }
}
</style>