<template>
  <!-- 团购包管理 - 新增/编辑页面 -->
  <div class="table-box" style="width: 100%; min-height: 100%; background-color: white">
    <el-form :model="storeInfoModel" ref="ruleFormRef" :rules="rules" label-width="120px" class="formBox">
      <div class="content">
        <!-- 左侧内容区域 -->
        <div class="contentLeft">
          <!-- 基础信息模块 -->
          <div class="model">
            <h3 style="font-weight: bold">基础信息：</h3>
            <!-- 团购图片上传 -->
            <el-form-item label="图片" prop="imageList">
              <el-upload
                v-model:file-list="storeInfoModel.imageList"
                :action="uploadUrl"
                list-type="picture-card"
                :accept="'.jpg,.png'"
                :limit="9"
                :on-preview="handlePictureCardPreview"
                :before-remove="handleBeforeRemove"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :show-file-list="true"
              >
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <!-- 团购名称 -->
            <el-form-item label="团购名称" prop="groupName">
              <el-input maxlength="50" v-model="storeInfoModel.groupName" placeholder="请填写团购名称" clearable />
            </el-form-item>
            <!-- 开始售卖时间设置方式 -->
            <el-form-item label="开始售卖时间" prop="startTimeType">
              <el-radio-group v-model="storeInfoModel.startTimeType" class="ml-4">
                <el-radio v-for="status in storeStatusList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 自定义开始售卖时间（当选择"设置售卖时间"时显示） -->
            <el-form-item label="" prop="saleTimeStr" v-if="storeInfoModel.startTimeType == 1">
              <el-date-picker
                v-model="storeInfoModel.saleTimeStr"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始售卖时间"
                :disabled-date="disabledStartDate"
              />
            </el-form-item>
            <!-- 结束售卖时间 -->
            <el-form-item label="结束售卖时间" prop="endTime">
              <el-date-picker
                v-model="storeInfoModel.endTime"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束售卖时间"
                :disabled-date="disabledEndDate"
              />
            </el-form-item>
            <!-- 库存数量 -->
            <el-form-item label="库存数量" prop="inventoryNum">
              <el-input v-model="storeInfoModel.inventoryNum" maxlength="15" placeholder="请填写库存数量" clearable />
            </el-form-item>
            <!-- 每人限购设置 -->
            <el-form-item label="每人限购" prop="quotaType">
              <el-radio-group v-model="storeInfoModel.quotaType" class="ml-4">
                <el-radio v-for="status in perList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 自定义限购数量（当选择"自定义限购数量"时显示） -->
            <el-form-item label="" prop="quotaValue" v-if="storeInfoModel.quotaType == 1">
              <el-input v-model="storeInfoModel.quotaValue" maxlength="15" placeholder="请填写自定义限购数量" clearable />
            </el-form-item>
            <!-- 套餐内容 -->
            <el-form-item label="套餐内容" prop="lifeGroupBuyThalis" class="package-content-item">
              <div class="package-content-wrapper">
                <div class="package-content-header">
                  <el-button type="primary" @click="addGroup" class="add-group-btn"> 添加分组 </el-button>
                  <el-button
                    type="primary"
                    link
                    @click="toggleAllGroupsCollapse"
                    :icon="allGroupsCollapsed ? ArrowDown : ArrowUp"
                    v-show="lifeGroupBuyThalis.length > 1"
                  >
                    {{ allGroupsCollapsed ? "展开全部" : "收起全部" }}
                  </el-button>
                </div>
                <div class="package-content-container">
                  <div v-for="(group, groupIndex) in lifeGroupBuyThalis" :key="groupIndex" class="package-group">
                    <div class="package-group-header">
                      <div class="header-right">
                        <el-button
                          type="danger"
                          link
                          @click="removeGroup(groupIndex)"
                          :icon="Delete"
                          v-show="lifeGroupBuyThalis.length > 1"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                    <transition name="slide-fade">
                      <div v-show="!allGroupsCollapsed" class="package-group-content">
                        <div class="category-row">
                          <span class="label">类别</span>
                          <el-input v-model="group.groupName" placeholder="请输入" clearable />
                        </div>
                        <div v-for="(dish, dishIndex) in group.dishes" :key="dishIndex" class="dish-row">
                          <span class="label">菜品</span>
                          <div class="dish-select-block" @click="openDishDialog(groupIndex, dishIndex)">
                            <span v-if="dish.dishName" class="dish-selected-name"
                              >{{ dish.dishName }}，¥{{ dish.dishPrice }}/{{ dish.dishesUnit }}</span
                            >
                            <span v-else class="dish-placeholder">请选择</span>
                          </div>
                          <span class="label">数量</span>
                          <el-input v-model="dish.qty" placeholder="请输入" clearable class="quantity-input" />
                          <el-button
                            :icon="Delete"
                            link
                            type="danger"
                            @click="removeDish(groupIndex, dishIndex)"
                            class="delete-dish-btn"
                          />
                        </div>
                        <el-button type="primary" @click="addDish(groupIndex)" class="add-dish-btn"> 添加 </el-button>
                      </div>
                    </transition>
                  </div>
                </div>
              </div>
            </el-form-item>
          </div>
          <!-- 价格信息模块 -->
          <div class="model">
            <h3 style="font-weight: bold">价格：</h3>
            <!-- 原价 -->
            <el-form-item label="原价" prop="originalPrice">
              <el-input maxlength="50" v-model="storeInfoModel.originalPrice" placeholder="请填写原价" clearable />
            </el-form-item>
            <!-- 优惠价 -->
            <el-form-item label="优惠价" prop="preferentialPrice">
              <el-input maxlength="50" v-model="storeInfoModel.preferentialPrice" placeholder="请填写优惠价" clearable />
            </el-form-item>
          </div>
        </div>
        <!-- 右侧内容区域 -->
        <div class="contentRight">
          <!-- 购买须知模块 -->
          <div class="model">
            <h3 style="font-weight: bold">购买须知：</h3>
            <el-form-item label="有效期" prop="effectiveDateType">
              <el-radio-group v-model="storeInfoModel.effectiveDateType" class="ml-4">
                <el-radio v-for="status in expirationDateList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" prop="expirationDate" v-if="storeInfoModel.effectiveDateType == 0">
              <div class="expiration-date-container">
                <span class="expiration-label">用户购买</span>
                <el-input-number v-model="storeInfoModel.expirationDate" placeholder="请输入" :min="0" class="expiration-input" />
                <span class="expiration-label">天内有效</span>
              </div>
            </el-form-item>
            <el-form-item label="" prop="effectiveDateValue" v-else>
              <el-date-picker
                v-model="storeInfoModel.effectiveDateValue"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :disabled-date="disabledEffectiveDate"
              />
            </el-form-item>
            <el-form-item label="不可用日期" prop="disableDateType">
              <el-radio-group v-model="storeInfoModel.disableDateType" class="ml-4">
                <el-radio v-for="status in unavailableDatesList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="storeInfoModel.disableDateType == 1">
              <el-form-item label="" prop="unavailableWeekdays">
                <div class="unavailable-dates-container">
                  <!-- 星期选择 -->
                  <div class="date-select-section">
                    <div class="section-title">星期</div>
                    <div class="button-group">
                      <el-button
                        v-for="weekday in weekdayList"
                        :key="weekday.oName"
                        :type="storeInfoModel.unavailableWeekdays?.includes(weekday.oName) ? 'primary' : ''"
                        class="date-select-btn"
                        @click="toggleWeekday(weekday.oName)"
                      >
                        {{ weekday.name }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="" prop="unavailableHolidays">
                <div class="unavailable-dates-container">
                  <!-- 节日选择 -->
                  <div class="date-select-section">
                    <div class="section-title">节日</div>
                    <div class="button-group">
                      <el-button
                        v-for="holiday in holidayList"
                        :key="holiday.id"
                        :type="storeInfoModel.unavailableHolidays?.includes(holiday.id) ? 'primary' : ''"
                        class="date-select-btn"
                        @click="toggleHoliday(holiday.id)"
                      >
                        {{ holiday.festivalName }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </template>
            <el-form-item label="" prop="customUnavailableDates" v-else-if="storeInfoModel.disableDateType == 2">
              <div class="date-picker-container">
                <el-button :icon="Plus" class="add-date-btn" type="primary" @click="addDate"> 添加日期 </el-button>
                <div v-for="(item, index) in dates" :key="index" class="date-item">
                  <el-date-picker
                    v-model="dates[index]"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    class="date-picker"
                    :disabled-date="disabledCustomUnavailableDate"
                  />
                  <el-button
                    :icon="Delete"
                    type="danger"
                    circle
                    size="small"
                    class="delete-btn"
                    @click="removeDate(index)"
                    v-show="dates.length > 1"
                  />
                </div>
              </div>
            </el-form-item>
            <!-- 预约规则 -->
            <el-form-item label="预约规则" prop="reservationRules">
              <el-input
                maxlength="300"
                v-model="storeInfoModel.reservationRules"
                :rows="4"
                type="textarea"
                placeholder="请输入预约规则"
              />
            </el-form-item>
            <!-- 使用规则 -->
            <el-form-item label="使用规则" prop="useRules">
              <el-input
                maxlength="300"
                v-model="storeInfoModel.useRules"
                :rows="4"
                type="textarea"
                placeholder="请输入使用规则"
              />
            </el-form-item>
            <!-- 适用人数 -->
            <el-form-item label="适用人数" prop="applicableNum">
              <el-input v-model="storeInfoModel.applicableNum" maxlength="15" placeholder="请填写适用人数" clearable />
            </el-form-item>
            <!-- 其他规则 -->
            <el-form-item label="其他规则" prop="otherRules">
              <el-input
                maxlength="300"
                v-model="storeInfoModel.otherRules"
                :rows="4"
                type="textarea"
                placeholder="请输入其他规则"
              />
            </el-form-item>
            <!-- 发票信息 -->
            <el-form-item label="发票信息" prop="invoiceInformation">
              <el-checkbox-group v-model="storeInfoModel.invoiceInformation">
                <el-checkbox v-for="bt in businessTypes" :key="bt.value" :value="bt.value" :label="bt.label">
                  {{ bt.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <!-- 发票说明 -->
            <el-form-item label="发票说明" prop="invoiceDescribe">
              <el-input v-model="storeInfoModel.invoiceDescribe" maxlength="15" placeholder="请填写发票说明" clearable />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <!-- 底部按钮区域 -->
    <div class="button-container">
      <el-button @click="goBack"> 返回 </el-button>
      <el-button @click="handleSubmit('cg')"> 存草稿 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </div>
    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePopupVisible" title="预览" width="30%">
      <el-image style="width: 100%" :src="previewImage" fit="contain" />
    </el-dialog>
    <!-- 菜品选择对话框 -->
    <el-dialog v-model="dishDialogVisible" title="菜品" width="600px" :close-on-click-modal="false">
      <div class="dish-dialog-content">
        <el-input
          v-model="dishSearchKeyword"
          placeholder="请输入菜品名称"
          clearable
          class="dish-search-input"
          @input="filterDishList"
        />
        <el-scrollbar height="400px" class="dish-list-container">
          <template v-if="filteredDishList.length > 0">
            <div
              v-for="dish in filteredDishList"
              :key="dish.id"
              :class="['dish-item', { 'dish-item-selected': selectedDishId === dish.id }]"
              @click="selectDish(dish)"
            >
              <div class="dish-image">
                <el-image v-if="dish.imgUrl" :src="dish.imgUrl" fit="cover" class="dish-img" />
                <div v-else class="dish-image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </div>
              <div class="dish-info">
                <div class="dish-name">
                  {{ dish.dishName }}
                </div>
                <div class="dish-price">¥{{ dish.dishPrice }}/{{ dish.dishesUnit }}</div>
              </div>
            </div>
          </template>
          <div v-else class="dish-empty-state">
            <div class="empty-text">暂无可选择菜品</div>
            <div class="empty-hint">请去全部-门店装修-菜品管理中添加</div>
          </div>
        </el-scrollbar>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmDishSelection"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="newGroup">
/**
 * 团购包管理 - 新增/编辑页面
 * 功能：支持团购包的新增和编辑操作
 */
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete, ArrowDown, ArrowUp, Picture, Check } from "@element-plus/icons-vue";
import {
  saveStoreInfo,
  editStoreInfo,
  getDetail,
  getStoreDetail,
  getHolidayList,
  getUserByPhone,
  getMenuByStoreId
} from "@/api/modules/groupPackageManagement";
import { useRouter, useRoute } from "vue-router";
import type { UploadProps, FormInstance } from "element-plus";
import { localGet, localSet } from "@/utils";

// ==================== 响应式数据定义 ====================

// 图片预览对话框显示状态
const imagePopupVisible = ref(false);
// 预览图片地址
const previewImage = ref("");

// 路由相关
const router = useRouter();
const route = useRoute();

// 页面状态
const type = ref<string>(""); // 页面类型：add-新增, edit-编辑
const id = ref<string>(""); // 页面ID参数

// 文件上传地址
const uploadUrl = ref(`${import.meta.env.VITE_API_URL_STORE}/file/upload`);

// ==================== 表单验证规则 ====================
const rules = reactive({
  imageList: [{ required: true, message: "请上传图片" }],
  groupName: [{ required: true, message: "请填写团购名称" }],
  startTimeType: [{ required: true, message: "请选择开始售卖时间" }],
  saleTimeStr: [
    { required: true, message: "请选择开始售卖时间" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.startTimeType === 1) {
          if (!value) {
            callback(new Error("请选择开始售卖时间"));
            return;
          }
          const selectedDate = new Date(value);
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          if (selectedDate < today) {
            callback(new Error("开始售卖时间不能早于当前时间"));
            return;
          }
          // 如果结束时间已设置，验证开始时间必须早于结束时间
          if (storeInfoModel.value.endTime) {
            const endDate = new Date(storeInfoModel.value.endTime);
            if (selectedDate >= endDate) {
              callback(new Error("开始售卖时间必须早于结束售卖时间"));
              return;
            }
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  endTime: [
    { required: true, message: "请选择结束售卖时间" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error("请选择结束售卖时间"));
          return;
        }
        const selectedDate = new Date(value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        if (selectedDate < today) {
          callback(new Error("结束售卖时间不能早于当前时间"));
          return;
        }
        // 如果开始时间已设置，验证结束时间必须晚于开始时间
        if (storeInfoModel.value.startTimeType === 1 && storeInfoModel.value.saleTimeStr) {
          const startDate = new Date(storeInfoModel.value.saleTimeStr);
          if (selectedDate <= startDate) {
            callback(new Error("结束售卖时间必须晚于开始售卖时间"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  inventoryNum: [
    { required: true, message: "请填写库存数量" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        const num = Number(value);
        if (isNaN(num) || num <= 0) {
          callback(new Error("库存数量必须为正整数"));
          return;
        }
        if (!Number.isInteger(num)) {
          callback(new Error("库存数量必须为正整数"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  quotaType: [{ required: true, message: "请选择每人限购" }],
  quotaValue: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.quotaType === 1) {
          if (!value || value.toString().trim() === "") {
            callback(new Error("请输入自定义限购数量"));
            return;
          }
          const num = Number(value);
          if (isNaN(num) || num <= 0) {
            callback(new Error("自定义限购数量必须为正整数"));
            return;
          }
          if (!Number.isInteger(num)) {
            callback(new Error("自定义限购数量必须为正整数"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  lifeGroupBuyThalis: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        try {
          // 验证独立的 lifeGroupBuyThalis 变量
          const thalis = lifeGroupBuyThalis.value;
          if (!thalis || thalis.length === 0) {
            callback(new Error("请至少添加一个套餐分组"));
            return;
          }
          // 如果设置了跳过最后一个分组验证的标记，则只验证除最后一个分组外的所有分组
          const groupsToValidate = skipLastGroupValidation && thalis.length > 1 ? thalis.slice(0, thalis.length - 1) : thalis;

          for (let i = 0; i < groupsToValidate.length; i++) {
            const group = groupsToValidate[i];
            const groupIndex = i;
            if (!group.groupName || group.groupName.trim() === "") {
              callback(new Error(`第${groupIndex + 1}个分组的类别不能为空`));
              return;
            }
            if (!group.dishes || group.dishes.length === 0) {
              callback(new Error(`第${groupIndex + 1}个分组至少需要添加一个菜品`));
              return;
            }
            for (let j = 0; j < group.dishes.length; j++) {
              const dish = group.dishes[j];
              if (!dish.detailId) {
                callback(new Error(`第${groupIndex + 1}个分组的第${j + 1}个菜品未选择`));
                return;
              }
              if (!dish.qty || dish.qty.toString().trim() === "") {
                callback(new Error(`第${groupIndex + 1}个分组的第${j + 1}个菜品数量不能为空`));
                return;
              }
              const quantityNum = Number(dish.qty);
              if (isNaN(quantityNum) || quantityNum <= 0) {
                callback(new Error(`第${groupIndex + 1}个分组的第${j + 1}个菜品数量必须为正整数`));
                return;
              }
              if (!Number.isInteger(quantityNum)) {
                callback(new Error(`第${groupIndex + 1}个分组的第${j + 1}个菜品数量必须为正整数`));
                return;
              }
            }
          }
          callback();
        } catch (error) {
          // 如果验证过程中出错，直接通过验证，避免报错
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  originalPrice: [
    { required: true, message: "请输入原价" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        const num = Number(value);
        if (isNaN(num) || num <= 0) {
          callback(new Error("原价必须为正数"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  preferentialPrice: [
    { required: true, message: "请输入优惠价" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        const num = Number(value);
        if (isNaN(num) || num <= 0) {
          callback(new Error("优惠价必须为正数"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  effectiveDateType: [{ required: true, message: "请选择有效期" }],
  expirationDate: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.expirationDate === 0) {
          if (value === null || value === undefined || value === "") {
            callback(new Error("请输入用户购买天数"));
            return;
          }
          if (value <= 0) {
            callback(new Error("天数必须大于0"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  effectiveDateValue: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.effectiveDateType === 1) {
          if (!value || value.length !== 2) {
            callback(new Error("请选择指定时间段"));
            return;
          }
          // 验证开始时间和结束时间不能早于当前时间
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          const startDate = new Date(value[0]);
          const endDate = new Date(value[1]);
          if (startDate < today) {
            callback(new Error("开始时间不能早于当前时间"));
            return;
          }
          if (endDate < today) {
            callback(new Error("结束时间不能早于当前时间"));
            return;
          }
          // 验证开始时间必须早于结束时间
          if (startDate >= endDate) {
            callback(new Error("开始时间必须早于结束时间"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  disableDateType: [{ required: true, message: "请选择不可用日期" }],
  unavailableWeekdays: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.unavailableDates === 1) {
          if (!value || value.length === 0) {
            callback(new Error("至少需要选择一个星期"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  unavailableHolidays: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.unavailableDates === 1) {
          if (!value || value.length === 0) {
            callback(new Error("至少需要选择一个节日"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  customUnavailableDates: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (storeInfoModel.value.disableDateType === 2) {
          if (!dates.value || dates.value.length === 0) {
            callback(new Error("至少需要添加一个自定义不可用日期"));
            return;
          }
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          // 验证每个日期项是否已填写
          for (let i = 0; i < dates.value.length; i++) {
            if (!dates.value[i] || dates.value[i].length !== 2) {
              callback(new Error(`第${i + 1}个日期项未完整填写`));
              return;
            }
            // 验证开始时间和结束时间不能早于当前时间
            const startDate = new Date(dates.value[i][0]);
            const endDate = new Date(dates.value[i][1]);
            if (startDate < today) {
              callback(new Error(`第${i + 1}个日期项的开始时间不能早于当前时间`));
              return;
            }
            if (endDate < today) {
              callback(new Error(`第${i + 1}个日期项的结束时间不能早于当前时间`));
              return;
            }
            // 验证开始时间必须早于结束时间
            if (startDate >= endDate) {
              callback(new Error(`第${i + 1}个日期项的开始时间必须早于结束时间`));
              return;
            }
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  reservationRules: [{ required: true, message: "请输入预约规则" }],
  useRules: [{ required: true, message: "请输入使用规则" }],
  applicableNum: [
    { required: true, message: "请输入适用人数" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        const num = Number(value);
        if (isNaN(num) || num <= 0) {
          callback(new Error("适用人数必须为正整数"));
          return;
        }
        if (!Number.isInteger(num)) {
          callback(new Error("适用人数必须为正整数"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  otherRules: [{ required: true, message: "请输入其他规则" }],
  invoiceInformation: [{ required: true, message: "请选择发票信息" }],
  invoiceDescribe: [{ required: true, message: "请输入发票说明" }]
});

// ==================== 团购包信息数据模型 ====================
const storeInfoModel = ref<any>({
  // 团购图片列表
  imageList: [],
  // 团购名称
  groupName: "",
  // 开始售卖时间设置方式：0-审核通过后立即开始，1-设置售卖时间
  startTimeType: 0,
  // 开始售卖时间（当storeStatus为1时必填）
  saleTimeStr: "",
  // 结束售卖时间
  endTime: "",
  // 库存数量
  inventoryNum: "",
  // 每人限购设置：0-不限量，1-自定义限购数量
  quotaValueStr: 0,
  // 自定义限购数量（当quotaType为1时必填）
  quotaValue: 0,
  // 套餐内容（虚拟字段，用于表单验证，实际数据在 lifeGroupBuyThalis 变量中）
  lifeGroupBuyThalis: null,
  // 原价
  originalPrice: "",
  // 优惠价
  preferentialPrice: "",
  // 有效期设置：0-指定天数，1-指定时间段内可用
  effectiveDateType: 0,
  expirationDate: 0,
  effectiveDateValue: [],
  // 不可用日期设置：0-全部日期可用，1-限制日期，2-自定义不可用日期
  disableDateType: 0,
  // 限制日期 - 星期选择（数组，存储选中的星期值）
  unavailableWeekdays: [],
  // 限制日期 - 节日选择（数组，存储选中的节日值）
  unavailableHolidays: [],
  // 预约规则
  reservationRules: "",
  // 使用规则
  useRules: "",
  // 适用人数
  applicableNum: "",
  // 其他规则
  otherRules: "",
  // 发票信息（复选框，可多选）
  invoiceInformation: [],
  // 发票说明
  invoiceDescribe: ""
});

// ==================== 下拉选项数据 ====================

// 发票类型列表
const businessTypes = ref([
  { value: 0, label: "提供电子发票" },
  { value: 1, label: "提供纸质发票" }
]);

// 开始售卖时间设置方式列表
const storeStatusList = ref([
  { value: 0, label: "审核通过后立即开始" },
  { value: 1, label: "设置售卖时间" }
]);

// 每人限购设置列表
const perList = ref([
  { value: 0, label: "不限量" },
  { value: 1, label: "自定义限购数量" }
]);
// 每人限购设置列表
const expirationDateList = ref([
  { value: 0, label: "指定天数" },
  { value: 1, label: "指定时间段内可用" }
]);
// 每人限购设置列表
const unavailableDatesList = ref([
  { value: 0, label: "全部日期可用" },
  { value: 1, label: "限制日期" },
  { value: 2, label: "自定义不可用日期" }
]);
//图片集合
const videoUrlList = ref<string[]>([]);
// 自定义不可用日期列表
const dates = ref([]);

// 星期选项列表
const weekdayList = ref([
  { name: "周一", id: "0", oName: "星期一" },
  { name: "周二", id: "1", oName: "星期二" },
  { name: "周三", id: "2", oName: "星期三" },
  { name: "周四", id: "3", oName: "星期四" },
  { name: "周五", id: "4", oName: "星期五" },
  { name: "周六", id: "5", oName: "星期六" },
  { name: "周日", id: "6", oName: "星期日" }
]);

// 节日选项列表
const holidayList: any = ref([]);

// 菜品选项列表（这里需要根据实际API获取，暂时使用示例数据）
const dishOptions = ref([]);

// 套餐内容（数组，每个元素是一个分组）
const lifeGroupBuyThalis = ref([
  {
    groupName: "", // 类别
    dishes: [
      // 菜品列表
      {
        detailId: "", // 菜品ID
        dishName: "", // 菜品名称
        dishPrice: "", // 菜品价格
        dishImage: "", // 菜品图片
        qty: "", // 数量
        dishesUnit: ""
      }
    ]
  }
]);

// 菜品选择对话框相关
const dishDialogVisible = ref(false);
const dishSearchKeyword = ref("");
const filteredDishList: any = ref([]);
const selectedDishId = ref<number | null>(null);
const currentDishGroupIndex = ref<number>(-1);
const currentDishIndex = ref<number>(-1);

// 套餐内容整体展开收起状态
const allGroupsCollapsed = ref(false);

// 标记是否跳过最后一个分组的验证（用于添加新分组时）
let skipLastGroupValidation = false;

// ==================== 监听器 ====================

/**
 * 监听不可用日期选项变化
 * 当切换到自定义不可用日期时，确保至少有一个日期项
 */
watch(
  () => storeInfoModel.value.unavailableDates,
  newVal => {
    if (newVal === 2) {
      // 切换到自定义不可用日期时，如果dates为空，则添加一个默认项
      if (!dates.value || dates.value.length === 0) {
        dates.value = [null];
      }
    }
  },
  { immediate: true }
);

/**
 * 监听开始售卖时间变化
 * 当开始时间改变时，重新验证结束时间
 */
watch(
  () => storeInfoModel.value.saleTimeStr,
  () => {
    if (storeInfoModel.value.endTime) {
      nextTick(() => {
        ruleFormRef.value?.validateField("endTime");
      });
    }
  }
);

/**
 * 监听结束售卖时间变化
 * 当结束时间改变时，重新验证开始时间
 */
watch(
  () => storeInfoModel.value.endTime,
  () => {
    if (storeInfoModel.value.startTimeType === 1 && storeInfoModel.value.saleTimeStr) {
      nextTick(() => {
        ruleFormRef.value?.validateField("saleTimeStr");
      });
    }
  }
);

// ==================== 生命周期钩子 ====================

/**
 * 组件挂载时初始化
 * 从路由参数中获取页面类型和ID
 */
onMounted(async () => {
  id.value = (route.query.id as string) || "";
  type.value = (route.query.type as string) || "";
  let param = {
    // phone: localGet("iphone")
    phone: "18641153170"
  };
  const resP: any = await getUserByPhone(param);
  if (resP.data && resP.data.storeId) {
    localSet("createdId", resP.data.storeId);
    const resD: any = await getDetail({
      id: localGet("createdId")
    });
    if (resD.data && resD.data.commissionRate) {
      localSet("commissionRate", resD.data.commissionRate);
    }
    if (resD.data && resD.data.businessSection) {
      localSet("businessSection", resD.data.businessSection);
    }
  } else {
    ElMessage.warning("请完成商家入驻后再进行新建团购");
  }
  let params = {
    year: new Date().getFullYear(),
    page: 1,
    size: 500,
    openFlag: 1,
    holidayName: ""
  };
  let res = await getHolidayList(params);
  if (res && res.code == 200) {
    holidayList.value = res.data.records;
  }
  if (type.value != "add") {
    let res: any = await getStoreDetail({ id: id.value } as any);
    storeInfoModel.value = res.data as any;
    videoUrlList.value = (res.data as any).businessLicenseAddress || [];
    let imageList: any[] = [];
    handleImageParam((res.data as any).businessLicenseAddress || [], imageList);
    storeInfoModel.value.imageList = imageList;
    // 确保星期和节日字段存在
    if (!storeInfoModel.value.unavailableWeekdays) {
      storeInfoModel.value.unavailableWeekdays = [];
    }
    if (!storeInfoModel.value.unavailableHolidays) {
      storeInfoModel.value.unavailableHolidays = [];
    }
    // 确保套餐内容字段存在
    if (res.data.lifeGroupBuyThalis && res.data.lifeGroupBuyThalis.length > 0) {
      lifeGroupBuyThalis.value = res.data.lifeGroupBuyThalis;
      // 确保每个分组都有必要的字段
      lifeGroupBuyThalis.value.forEach((group: any) => {
        if (!group.dishes || group.dishes.length === 0) {
          group.dishes = [
            {
              detailId: "",
              qty: ""
            }
          ];
        }
      });
    } else {
      // 如果没有数据，使用默认值
      lifeGroupBuyThalis.value = [
        {
          groupName: "",
          dishes: [
            {
              detailId: "",
              dishName: "",
              dishPrice: "",
              dishImage: "",
              qty: "",
              dishesUnit: ""
            }
          ]
        }
      ];
    }
    // 确保自定义不可用日期字段存在
    if (storeInfoModel.value.unavailableDates === 2) {
      if (!dates.value || dates.value.length === 0) {
        dates.value = [null];
      }
    }
  } else {
    // 新增模式下，如果默认选择自定义不可用日期，确保dates至少有一个元素
    if (storeInfoModel.value.unavailableDates === 2) {
      if (!dates.value || dates.value.length === 0) {
        dates.value = [null];
      }
    }
  }
});
// ==================== 事件处理函数 ====================

/**
 * 返回上一页
 */
const goBack = () => {
  router.go(-1);
};

/**
 * 图片上传 - 删除前确认
 * @param uploadFile 要删除的文件对象
 * @param uploadFiles 当前文件列表
 * @returns Promise<boolean>，true 允许删除，false 阻止删除
 */
const handleBeforeRemove = async (uploadFile: any, uploadFiles: any[]): Promise<boolean> => {
  try {
    await ElMessageBox.confirm("确定要删除这张图片吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    // 用户确认删除，返回 true 允许删除
    return true;
  } catch {
    // 用户取消删除，返回 false 阻止删除
    return false;
  }
};

/**
 * 图片上传 - 移除图片回调（删除成功后调用）
 * @param uploadFile 已删除的文件对象
 * @param uploadFiles 删除后的文件列表
 */
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // 删除成功后提示
  ElMessage.success("图片已删除");
};

/**
 * 图片上传 - 上传成功回调
 * @param response 上传响应数据
 */
const handleSuccess = (response: any) => {
  ElMessage.success("图片上传成功");
  // 上传成功后，imageList 会自动更新，response.data 包含图片URL
};

/**
 * 图片预览 - 打开预览对话框
 * @param e 上传文件对象
 */
const handlePictureCardPreview = (e: any) => {
  imagePopupVisible.value = true;
  previewImage.value = e.url;
};

/**
 * 添加自定义不可用日期
 */
const addDate = () => {
  dates.value.push(null);
};

/**
 * 删除自定义不可用日期
 * @param index 要删除的日期索引
 */
const removeDate = (index: number) => {
  if (dates.value.length <= 1) {
    ElMessage.warning("至少需要保留一个日期项");
    return;
  }
  dates.value.splice(index, 1);
};

/**
 * 切换星期选择
 * @param value 星期值
 */
const toggleWeekday = value => {
  if (!storeInfoModel.value.unavailableWeekdays) {
    storeInfoModel.value.unavailableWeekdays = [];
  }
  const index = storeInfoModel.value.unavailableWeekdays.indexOf(value);
  if (index > -1) {
    storeInfoModel.value.unavailableWeekdays.splice(index, 1);
  } else {
    storeInfoModel.value.unavailableWeekdays.push(value);
  }
  console.log(storeInfoModel.value.unavailableWeekdays);
  // 触发表单验证
  nextTick(() => {
    ruleFormRef.value?.validateField("unavailableWeekdays");
  });
};

/**
 * 切换节日选择
 * @param value 节日值
 */
const toggleHoliday = value => {
  if (!storeInfoModel.value.unavailableHolidays) {
    storeInfoModel.value.unavailableHolidays = [];
  }
  const index = storeInfoModel.value.unavailableHolidays.indexOf(value);
  if (index > -1) {
    storeInfoModel.value.unavailableHolidays.splice(index, 1);
  } else {
    storeInfoModel.value.unavailableHolidays.push(value);
  }
  console.log(storeInfoModel.value.unavailableHolidays);
  // 触发表单验证
  nextTick(() => {
    ruleFormRef.value?.validateField("unavailableHolidays");
  });
};

/**
 * 添加套餐分组
 */
const addGroup = () => {
  if (!lifeGroupBuyThalis.value) {
    lifeGroupBuyThalis.value = [];
  }

  // 记录旧分组的数量，用于后续只验证旧分组
  const oldGroupsCount = lifeGroupBuyThalis.value.length;

  // 添加新分组
  lifeGroupBuyThalis.value.push({
    groupName: "",
    dishes: [
      {
        detailId: "",
        dishName: "",
        dishPrice: "",
        dishImage: "",
        qty: "",
        dishesUnit: ""
      }
    ]
  });

  // 清除表单验证状态，避免新分组显示验证错误
  // 只清除验证状态，不重新触发验证
  // 让用户操作时（如点击添加菜品）再触发验证
  nextTick(() => {
    ruleFormRef.value?.clearValidate("lifeGroupBuyThalis");
    skipLastGroupValidation = false;
  });
};

/**
 * 删除套餐分组
 * @param groupIndex 分组索引
 */
const removeGroup = (groupIndex: number) => {
  if (lifeGroupBuyThalis.value.length <= 1) {
    ElMessage.warning("至少需要保留一个分组");
    return;
  }
  ElMessageBox.confirm("确定要删除这个分组吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      lifeGroupBuyThalis.value.splice(groupIndex, 1);
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

/**
 * 切换所有分组的收起/展开状态
 */
const toggleAllGroupsCollapse = () => {
  allGroupsCollapsed.value = !allGroupsCollapsed.value;
};

/**
 * 添加菜品
 * @param groupIndex 分组索引
 */
const addDish = (groupIndex: number) => {
  const group = lifeGroupBuyThalis.value[groupIndex];

  // 验证当前分组是否填写完整
  // 验证类别
  if (!group.groupName || group.groupName.trim() === "") {
    ElMessage.warning("请先完成现有菜品的填写");
    // 触发表单验证，显示验证错误
    nextTick(() => {
      ruleFormRef.value?.validateField("lifeGroupBuyThalis");
    });
    return;
  }

  // 验证是否有菜品
  if (!group.dishes || group.dishes.length === 0) {
    ElMessage.warning("请先完成现有菜品的填写");
    // 触发表单验证，显示验证错误
    nextTick(() => {
      ruleFormRef.value?.validateField("lifeGroupBuyThalis");
    });
    return;
  }

  // 验证当前分组中每个菜品是否填写完整
  for (let j = 0; j < group.dishes.length; j++) {
    const dish = group.dishes[j];

    // 验证菜品是否已选择
    if (!dish.detailId) {
      ElMessage.warning("请先完成现有菜品的填写");
      // 触发表单验证，显示验证错误
      nextTick(() => {
        ruleFormRef.value?.validateField("lifeGroupBuyThalis");
      });
      return;
    }

    // 验证数量是否已填写
    if (!dish.qty || dish.qty.toString().trim() === "") {
      ElMessage.warning("请先完成现有菜品的填写");
      // 触发表单验证，显示验证错误
      nextTick(() => {
        ruleFormRef.value?.validateField("lifeGroupBuyThalis");
      });
      return;
    }

    // 验证数量格式
    const quantityNum = Number(dish.qty);
    if (isNaN(quantityNum) || quantityNum <= 0 || !Number.isInteger(quantityNum)) {
      ElMessage.warning("请先完成现有菜品的填写");
      // 触发表单验证，显示验证错误
      nextTick(() => {
        ruleFormRef.value?.validateField("lifeGroupBuyThalis");
      });
      return;
    }
  }

  // 所有验证通过，添加新菜品
  if (!group.dishes) {
    group.dishes = [];
  }
  group.dishes.push({
    detailId: "",
    dishName: "",
    dishPrice: "",
    dishImage: "",
    qty: "",
    dishesUnit: ""
  });
};

/**
 * 删除菜品
 * @param groupIndex 分组索引
 * @param dishIndex 菜品索引
 */
const removeDish = (groupIndex: number, dishIndex: number) => {
  const dishes = lifeGroupBuyThalis.value[groupIndex].dishes;
  if (dishes.length <= 1) {
    ElMessage.warning("至少需要保留一个菜品");
    return;
  }
  dishes.splice(dishIndex, 1);
};

/**
 * 打开菜品选择对话框
 * @param groupIndex 分组索引
 * @param dishIndex 菜品索引
 */
const openDishDialog = async (groupIndex: number, dishIndex: number) => {
  currentDishGroupIndex.value = groupIndex;
  currentDishIndex.value = dishIndex;
  dishSearchKeyword.value = "";
  const params = {
    storeId: 361,
    phoneId: 18641153170,
    dishType: 0
  };
  const res = await getMenuByStoreId(params);
  if (res && res.code == 200) {
    dishOptions.value = res.data;
  }
  filterDishList();
  // 如果已有选中的菜品，设置选中状态
  const currentDish = lifeGroupBuyThalis.value[groupIndex].dishes[dishIndex];
  selectedDishId.value = currentDish?.detailId || null;
  dishDialogVisible.value = true;
};

/**
 * 选择菜品
 * @param dish 菜品对象
 */
const selectDish = (dish: any) => {
  selectedDishId.value = dish.id;
};

/**
 * 确认菜品选择
 */
const confirmDishSelection = () => {
  if (selectedDishId.value === null) {
    ElMessage.warning("请选择一个菜品");
    return;
  }
  const selectedDish: any = dishOptions.value.find(dish => dish.id === selectedDishId.value);
  if (selectedDish && currentDishGroupIndex.value >= 0 && currentDishIndex.value >= 0) {
    const dish = lifeGroupBuyThalis.value[currentDishGroupIndex.value].dishes[currentDishIndex.value];
    dish.detailId = selectedDish.id;
    dish.dishName = selectedDish.dishName;
    dish.dishPrice = selectedDish.dishPrice;
    dish.dishImage = selectedDish.imgUrl;
    dish.dishesUnit = selectedDish.dishesUnit;
    dishDialogVisible.value = false;
  }
};

/**
 * 过滤菜品列表
 */
const filterDishList = () => {
  if (!dishSearchKeyword.value || dishSearchKeyword.value.trim() === "") {
    filteredDishList.value = [...dishOptions.value];
  } else {
    const keyword = dishSearchKeyword.value.trim().toLowerCase();
    filteredDishList.value = dishOptions.value.filter(dish => dish.dishName.toLowerCase().includes(keyword));
  }
};

// ==================== 表单引用 ====================
const ruleFormRef = ref<FormInstance>(); // 表单引用

/**
 * 提交数据（新增/编辑）
 * 验证表单，通过后调用相应的API接口
 */
const handleSubmit = (type?) => {
  let params: any = { ...storeInfoModel.value };
  if (params.effectiveDateType == 0) {
    params.couponCompDate = `用户购买${params.expirationDate}天内有效`;
  } else {
    params.effectiveDateValue = params.effectiveDateValue.join(",");
  }
  if (params.disableDateType == 1) {
    params.disableDateValue = params.unavailableWeekdays.join(",") + ";" + params.unavailableHolidays.join(",");
    delete params.unavailableWeekdays;
    delete params.unavailableHolidays;
  } else if (params.disableDateType == 2) {
    params.disableDateValue = dates.value.map(subArray => subArray.join(",")).join(";");
  }
  params.invoiceType = params.invoiceInformation.join(",");
  const output = lifeGroupBuyThalis.value.flatMap(group =>
    group.dishes.map(dish => ({
      groupName: group.groupName,
      detailId: dish.detailId,
      qty: dish.qty,
      dishPrice: dish.dishPrice
    }))
  );
  const paramsObj = {
    lifeGroupBuyMain: params,
    lifeGroupBuyThalis: output
  };
  console.log(paramsObj);
  if (type) {
    return;
  }
  // 验证套餐内容
  const validateThalis = () => {
    const thalis = lifeGroupBuyThalis.value;
    if (!thalis || thalis.length === 0) {
      ElMessage.error("请至少添加一个套餐分组");
      return false;
    }
    for (let i = 0; i < thalis.length; i++) {
      const group = thalis[i];
      if (!group.groupName || group.groupName.trim() === "") {
        ElMessage.error(`第${i + 1}个分组的类别不能为空`);
        return false;
      }
      if (!group.dishes || group.dishes.length === 0) {
        ElMessage.error(`第${i + 1}个分组至少需要添加一个菜品`);
        return false;
      }
      for (let j = 0; j < group.dishes.length; j++) {
        const dish = group.dishes[j];
        if (!dish.detailId) {
          ElMessage.error(`第${i + 1}个分组的第${j + 1}个菜品未选择`);
          return false;
        }
        if (!dish.qty || dish.qty.toString().trim() === "") {
          ElMessage.error(`第${i + 1}个分组的第${j + 1}个菜品数量不能为空`);
          return false;
        }
        const quantityNum = Number(dish.qty);
        if (isNaN(quantityNum) || quantityNum <= 0) {
          ElMessage.error(`第${i + 1}个分组的第${j + 1}个菜品数量必须为正整数`);
          return false;
        }
        if (!Number.isInteger(quantityNum)) {
          ElMessage.error(`第${i + 1}个分组的第${j + 1}个菜品数量必须为正整数`);
          return false;
        }
      }
    }
    return true;
  };

  // 验证表单
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    // 验证套餐内容
    if (!validateThalis()) {
      return;
    }
    // 组装提交参数
    let params: any = { ...storeInfoModel.value };
    params.lifeGroupBuyThalis = lifeGroupBuyThalis.value;
  });
};

// ==================== 工具函数 ====================

/**
 * 禁用开始售卖时间的日期
 * 不能选择早于当前时间的日期
 * @param time 日期对象
 * @returns 是否禁用该日期
 */
const disabledStartDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

/**
 * 禁用结束售卖时间的日期
 * 不能选择早于当前时间的日期，也不能选择早于或等于开始售卖时间的日期
 * @param time 日期对象
 * @returns 是否禁用该日期
 */
const disabledEndDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  // 不能早于当前时间
  if (time.getTime() < today.getTime()) {
    return true;
  }
  // 如果开始售卖时间已设置，不能早于或等于开始时间
  if (storeInfoModel.value.startTimeType === 1 && storeInfoModel.value.saleTimeStr) {
    const startDate = new Date(storeInfoModel.value.saleTimeStr);
    startDate.setHours(0, 0, 0, 0);
    return time.getTime() <= startDate.getTime();
  }
  return false;
};

/**
 * 禁用指定时间段内可用的日期
 * 不能选择早于当前时间的日期
 * @param time 日期对象
 * @returns 是否禁用该日期
 */
const disabledEffectiveDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

/**
 * 禁用自定义不可用日期的日期
 * 不能选择早于当前时间的日期
 * @param time 日期对象
 * @returns 是否禁用该日期
 */
const disabledCustomUnavailableDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

/**
 * 处理图片结果
 * 将上传组件的文件对象或URL字符串转换为URL数组
 * @param list 图片列表（可能是文件对象或URL字符串）
 * @returns URL字符串数组
 */
const handleImageResult = (list: any[]): string[] => {
  let result: string[] = [];
  (list || []).forEach((item: any) => {
    if (item.uid) {
      // 如果是上传组件的文件对象，取url属性
      result.push(item.url);
    } else {
      // 如果是URL字符串，直接添加
      result.push(item);
    }
  });
  return result;
};

//图片list 转换为upload 组件的参数
const handleImageParam = (list: any[], result: any[]) => {
  (list || []).forEach((item: any) => {
    // 使用split方法以'/'为分隔符将URL拆分成数组
    const parts = item.split("/");
    // 取数组的最后一项，即图片名称
    const imageName = parts[parts.length - 1];
    result.push({
      name: imageName,
      percentage: 100,
      url: item
    });
  });
};
</script>

<style scoped lang="scss">
/* 页面容器 */
.table-box {
  display: flex;
  flex-direction: column;
  height: auto !important;
  min-height: 100%;
}

/* 内容区域布局 */
.content {
  display: flex;
  flex: 1;
  width: 98%;
  margin: 20px auto;

  /* 左侧内容区域 */
  .contentLeft {
    width: 50%;
  }

  /* 右侧内容区域 */
  .contentRight {
    width: 50%;
  }
}

/* 模块容器 */
.model {
  margin-bottom: 50px;
}

/* 表单容器 */
.formBox {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100%;
}

/* 底部按钮容器 - 居中显示 */
.button-container {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  margin-top: 20px;
}

/* 日期选择器容器 */
.date-picker-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

/* 添加日期按钮 */
.add-date-btn {
  width: fit-content;
  margin-bottom: 8px;
}

/* 日期项容器 */
.date-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;

  // background-color: #f5f7fa;
  border-radius: 4px;
  transition: background-color 0.3s;
  &:hover {
    background-color: #ecf5ff;
  }
}

/* 日期选择器 */
.date-item .date-picker {
  flex: 1;
  max-width: 500px;
}

/* 删除按钮 */
.date-item .delete-btn {
  flex-shrink: 0;
}

/* 有效期天数容器 */
.expiration-date-container {
  display: flex;
  gap: 12px;
  align-items: center;
  width: fit-content;
  padding: 8px 12px;

  // background-color: #f5f7fa;
  border-radius: 4px;
}

/* 有效期标签文字 */
.expiration-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

/* 有效期输入框 */
.expiration-input {
  width: 150px;
}

/* 不可用日期容器 */
.unavailable-dates-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
}

/* 日期选择区块 */
.date-select-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 区块标题 */
.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

/* 按钮组 */
.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 日期选择按钮 */
.date-select-btn {
  min-width: 80px;
  height: 36px;
  padding: 8px 16px;
  margin: 0;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

/* 套餐内容相关样式 */
.package-content-item {
  width: 100%;
}
.package-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}
.package-content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.add-group-btn {
  width: fit-content;
}
.package-content-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}
.package-group {
  overflow: hidden;
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}
.package-group-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}
.header-right {
  display: flex;
  gap: 12px;
  align-items: center;
}
.package-group-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}
.category-row {
  display: flex;
  gap: 12px;
  align-items: center;
}
.dish-row {
  display: flex;
  gap: 12px;
  align-items: center;
}
.label {
  min-width: 50px;
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}
.dish-select-block {
  display: flex;
  flex: 1;
  align-items: center;
  max-width: 300px;
  min-height: 32px;
  padding: 0 11px;
  cursor: pointer;
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.dish-select-block:hover {
  border-color: #c0c4cc;
}
.dish-select-block:focus-within {
  border-color: #409eff;
}
.dish-selected-name {
  font-size: 14px;
  color: #606266;
}
.dish-placeholder {
  font-size: 14px;
  color: #c0c4cc;
}
.quantity-input {
  width: 150px;
}
.delete-dish-btn {
  flex-shrink: 0;
}
.add-dish-btn {
  width: fit-content;
  margin-top: 8px;
}

/* 菜品选择对话框样式 */
.dish-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.dish-search-input {
  width: 100%;
}
.dish-list-container {
  :deep(.el-scrollbar__wrap) {
    overflow-x: hidden;
  }
  :deep(.el-scrollbar__view) {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}
.dish-empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}
.empty-text {
  margin-bottom: 8px;
  font-size: 16px;
  color: #909399;
}
.empty-hint {
  font-size: 14px;
  color: #c0c4cc;
}
.dish-item {
  position: relative;
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  transition: all 0.3s;
}
.dish-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
}
.dish-item-selected {
  background-color: #ecf5ff;
  border-color: #409eff;
  border-width: 2px;
}
.dish-item-selected:hover {
  background-color: #d9ecff;
}
.dish-image {
  flex-shrink: 0;
  width: 60px;
  height: 60px;
  overflow: hidden;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.dish-img {
  width: 100%;
  height: 100%;
}
.dish-image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 24px;
  color: #c0c4cc;
}
.dish-info {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 4px;
}
.dish-name {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}
.dish-price {
  font-size: 14px;
  color: #909399;
}
.dish-selected-icon {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  font-size: 16px;
  color: #ffffff;
  background-color: #409eff;
  border-radius: 50%;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}

/* 展开收起动画 - 高度过渡 */
.slide-fade-enter-active {
  overflow: hidden;
  transition:
    max-height 0.3s ease-out,
    opacity 0.3s ease-out;
}
.slide-fade-leave-active {
  overflow: hidden;
  transition:
    max-height 0.3s ease-in,
    opacity 0.3s ease-in;
}
.slide-fade-enter-from {
  max-height: 0;
  opacity: 0;
}
.slide-fade-leave-to {
  max-height: 0;
  opacity: 0;
}
.slide-fade-enter-to,
.slide-fade-leave-from {
  max-height: 2000px;
  opacity: 1;
}
</style>
