<template>
  <!-- 团购包管理 - 详情页面 -->
  <div class="table-box" style="width: 100%; min-height: 100%; background-color: white">
    <div class="header">
      <el-button @click="goBack"> 返回 </el-button>
      <h2 class="title">团购详情</h2>
    </div>
    <div class="content">
      <!-- 左侧内容区域 -->
      <div class="contentLeft">
        <!-- 基础信息模块 -->
        <div class="model">
          <h3 style="font-weight: bold">基础信息：</h3>
          <!-- 团购图片 -->
          <div class="detail-item">
            <div class="detail-label">图片</div>
            <div class="detail-value">
              <div class="image-list">
                <el-image
                  v-for="(image, index) in storeInfoModel.imageValueStr"
                  :key="index"
                  :src="getImageUrl(image)"
                  class="detail-image"
                  :preview-src-list="imagePreviewList"
                  :initial-index="index"
                  show-progress
                  preview-teleported
                />
              </div>
            </div>
          </div>
          <!-- 团购名称 -->
          <div class="detail-item">
            <div class="detail-label">团购名称</div>
            <div class="detail-value">
              {{ storeInfoModel.groupName || "--" }}
            </div>
          </div>
          <!-- 开始售卖时间 -->
          <div class="detail-item">
            <div class="detail-label">开始时间</div>
            <div class="detail-value">
              {{ getStartTimeText() }}
            </div>
          </div>
          <!-- 结束售卖时间 -->
          <div class="detail-item">
            <div class="detail-label">结束时间</div>
            <div class="detail-value">
              {{ storeInfoModel.endTime ? formatDate(storeInfoModel.endTime) : "--" }}
            </div>
          </div>
          <!-- 库存数量 -->
          <div class="detail-item">
            <div class="detail-label">库存数量</div>
            <div class="detail-value">
              {{ storeInfoModel.inventoryNum || "--" }}
            </div>
          </div>
          <!-- 每人限购 -->
          <div class="detail-item">
            <div class="detail-label">每人限购</div>
            <div class="detail-value">
              {{ getQuotaText() }}
            </div>
          </div>
          <!-- 套餐内容 -->
          <div class="detail-item package-content-item">
            <div class="detail-label">套餐内容</div>
            <div class="detail-value">
              <div v-if="lifeGroupBuyThalis && lifeGroupBuyThalis.length > 0" class="package-content-list">
                <div v-for="(group, groupIndex) in lifeGroupBuyThalis" :key="groupIndex" class="package-group-item">
                  <div v-for="(dish, dishIndex) in group.dishes" :key="dishIndex" class="package-dish-item">
                    <span class="dish-category">{{ group.groupName }}:</span>
                    <span class="dish-name">{{ dish.dishName }}</span>
                    <span class="dish-price">¥{{ dish.dishPrice }}/{{ dish.dishesUnit }}</span>
                    <span class="dish-quantity">数量{{ dish.qty }}</span>
                  </div>
                </div>
              </div>
              <span v-else class="empty-text">--</span>
            </div>
          </div>
        </div>
        <!-- 价格信息模块 -->
        <div class="model">
          <h3 style="font-weight: bold">价格：</h3>
          <!-- 原价 -->
          <div class="detail-item">
            <div class="detail-label">原价(¥)</div>
            <div class="detail-value">
              {{ storeInfoModel.originalPrice || "--" }}
            </div>
          </div>
          <!-- 优惠价 -->
          <div class="detail-item">
            <div class="detail-label">优惠价(¥)</div>
            <div class="detail-value">
              {{ storeInfoModel.preferentialPrice || "--" }}
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧内容区域 -->
      <div class="contentRight">
        <!-- 购买须知模块 -->
        <div class="model">
          <h3 style="font-weight: bold">购买须知：</h3>
          <!-- 有效期 -->
          <div class="detail-item">
            <div class="detail-label">有效期</div>
            <div class="detail-value">
              {{ getEffectiveDateText() }}
            </div>
          </div>
          <!-- 不可用日期 -->
          <div class="detail-item">
            <div class="detail-label">不可用日期</div>
            <div class="detail-value">
              {{ getDisableDateText() }}
            </div>
          </div>
          <!-- 核销方式 -->
          <div class="detail-item">
            <div class="detail-label">核销方式</div>
            <div class="detail-value">手动核销</div>
          </div>
          <!-- 预约规则 -->
          <div class="detail-item">
            <div class="detail-label">预约规则</div>
            <div class="detail-value" v-html="storeInfoModel.reservationRules || '详情请咨询商家'" />
          </div>
          <!-- 使用规则 -->
          <div class="detail-item">
            <div class="detail-label">使用规则</div>
            <div class="detail-value" v-html="storeInfoModel.useRules || '详情请咨询商家'" />
          </div>
          <!-- 适用人数 -->
          <div class="detail-item">
            <div class="detail-label">适用人数</div>
            <div class="detail-value">
              {{ storeInfoModel.applicableNum ? storeInfoModel.applicableNum + "人" : "--" }}
            </div>
          </div>
          <!-- 其他规则 -->
          <div class="detail-item">
            <div class="detail-label">其他规则</div>
            <div class="detail-value" v-html="storeInfoModel.otherRules || '详情请咨询商家'" />
          </div>
          <!-- 发票信息 -->
          <div class="detail-item">
            <div class="detail-label">发票信息</div>
            <div class="detail-value">
              <div v-if="invoiceInfoList && invoiceInfoList.length > 0">
                <span v-for="(info, index) in invoiceInfoList" :key="index">
                  {{ info }}<span v-if="index < invoiceInfoList.length - 1">、</span>
                </span>
              </div>
              <span v-else>详情请咨询商家</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="groupPackageDetail">
/**
 * 团购包管理 - 详情页面
 * 功能：显示团购包的详细信息
 */
import { ref, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { getThaliById, getHolidayList } from "@/api/modules/groupPackageManagement";
import { localGet } from "@/utils";

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

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

// 页面ID参数
const id = ref<string>("");

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

// 套餐内容（数组，每个元素是一个分组）
const lifeGroupBuyThalis = ref<any[]>([]);

// 星期选项列表
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([]);

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

// ==================== 计算属性 ====================

// 图片预览列表
const imagePreviewList = computed(() => {
  return storeInfoModel.value.imageValueStr.map((item: any) => getImageUrl(item));
});

// 发票信息列表
const invoiceInfoList = computed(() => {
  if (!storeInfoModel.value.invoiceInformation || storeInfoModel.value.invoiceInformation.length === 0) {
    return [];
  }
  return storeInfoModel.value.invoiceInformation
    .map((val: string) => {
      const numVal = parseInt(val);
      const type = businessTypes.value.find(item => item.value === numVal);
      return type ? type.label : "";
    })
    .filter(Boolean);
});

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

/**
 * 组件挂载时初始化
 * 从路由参数中获取ID并加载详情数据
 */
onMounted(async () => {
  id.value = (route.query.id as string) || "";
  // 加载节日列表
  await loadHolidayList();
  if (id.value) {
    await loadDetailData();
  } else {
    ElMessage.warning("缺少团购ID参数");
  }
});

// ==================== 事件处理函数 ====================

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

// ==================== 数据加载函数 ====================

/**
 * 加载节日列表
 */
const loadHolidayList = async () => {
  try {
    let params = {
      year: new Date().getFullYear(),
      page: 1,
      size: 500,
      openFlag: 1,
      holidayName: ""
    };
    let res: any = await getHolidayList(params);
    if (res && res.code == 200) {
      holidayList.value = res.data.records;
    }
  } catch (error) {
    console.error("加载节日列表出错:", error);
  }
};

/**
 * 加载详情数据
 */
const loadDetailData = async () => {
  try {
    const params = {
      id: id.value,
      userId: localGet("userId") || "104"
    };
    const res: any = await getThaliById(params);
    if (res && res.code == 200) {
      // 合并主数据
      storeInfoModel.value = { ...storeInfoModel.value, ...res.data.lifeGroupBuyMain };
      // 处理发票信息
      if (storeInfoModel.value.invoiceType) {
        storeInfoModel.value.invoiceInformation = storeInfoModel.value.invoiceType.split(";");
      }

      // 处理不可用日期
      if (storeInfoModel.value.disableDateValue) {
        const listVal = storeInfoModel.value.disableDateValue.split(";");
        if (listVal.length >= 2) {
          storeInfoModel.value.unavailableWeekdays = listVal[0] ? listVal[0].split(",") : [];
          storeInfoModel.value.unavailableHolidays = listVal[1] ? listVal[1].split(",") : [];
        }
      }

      // 处理套餐内容
      if (res.data.lifeGroupBuyThalis && res.data.lifeGroupBuyThalis.length > 0) {
        lifeGroupBuyThalis.value = res.data.lifeGroupBuyThalis;
      }
    } else {
      ElMessage.error("加载详情数据失败");
    }
  } catch (error) {
    console.error("加载详情数据出错:", error);
    ElMessage.error("加载详情数据出错");
  }
};

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

/**
 * 获取开始时间文本
 */
const getStartTimeText = () => {
  if (storeInfoModel.value.startTimeType === 0) {
    return (
      "审核通过立即开始" + (storeInfoModel.value.startTimeValue ? "/" + formatDate(storeInfoModel.value.startTimeValue) : "")
    );
  } else if (storeInfoModel.value.startTimeType === 1 && storeInfoModel.value.startTimeValue) {
    return formatDate(storeInfoModel.value.startTimeValue);
  }
  return "--";
};

/**
 * 获取限购文本
 */
const getQuotaText = () => {
  if (storeInfoModel.value.quotaType === 0) {
    return "不限量";
  } else if (storeInfoModel.value.quotaType === 1) {
    return storeInfoModel.value.quotaValue ? `不限量/${storeInfoModel.value.quotaValue}` : "不限量";
  }
  return "--";
};

/**
 * 获取有效期文本
 */
const getEffectiveDateText = () => {
  if (storeInfoModel.value.effectiveDateType === 0) {
    if (storeInfoModel.value.expirationDate) {
      return `用户购买后${storeInfoModel.value.expirationDate}天内有效`;
    }
    return "--";
  } else if (storeInfoModel.value.effectiveDateType === 1) {
    if (storeInfoModel.value.expirationDateList && storeInfoModel.value.expirationDateList.length === 2) {
      return `${formatDate(storeInfoModel.value.expirationDateList[0])}-${formatDate(storeInfoModel.value.expirationDateList[1])}`;
    }
    return "--";
  }
  return "--";
};

/**
 * 获取不可用日期文本
 */
const getDisableDateText = () => {
  if (storeInfoModel.value.disableDateType === 0) {
    return "全部日期可用";
  } else if (storeInfoModel.value.disableDateType === 1) {
    const weekdays: string[] = [];
    const holidays: string[] = [];

    // 处理星期
    if (storeInfoModel.value.unavailableWeekdays && storeInfoModel.value.unavailableWeekdays.length > 0) {
      storeInfoModel.value.unavailableWeekdays.forEach((day: string) => {
        const weekday = weekdayList.value.find(w => w.oName === day);
        if (weekday) {
          weekdays.push(weekday.name);
        }
      });
    }

    // 处理节日
    if (storeInfoModel.value.unavailableHolidays && storeInfoModel.value.unavailableHolidays.length > 0) {
      storeInfoModel.value.unavailableHolidays.forEach((holidayId: string) => {
        const holiday = holidayList.value.find((h: any) => h.id === holidayId);
        if (holiday) {
          holidays.push(holiday.festivalName);
        }
      });
    }

    const parts: string[] = [];
    if (weekdays.length > 0) {
      parts.push(weekdays.join("、"));
    }
    if (holidays.length > 0) {
      parts.push(holidays.join("、"));
    }

    return parts.length > 0 ? parts.join("、") : "--";
  } else if (storeInfoModel.value.disableDateType === 2) {
    if (storeInfoModel.value.disableDateList && storeInfoModel.value.disableDateList.length > 0) {
      const dateStrings = storeInfoModel.value.disableDateList
        .filter((date: any) => date && date.length === 2)
        .map((date: any) => `${formatDate(date[0])}-${formatDate(date[1])}`);
      return dateStrings.length > 0 ? dateStrings.join("、") : "--";
    }
    return "--";
  }
  return "--";
};

/**
 * 格式化日期
 * @param date 日期字符串 (YYYY-MM-DD)
 * @returns 格式化后的日期字符串 (YYYY/MM/DD)
 */
const formatDate = (date: string) => {
  if (!date) return "--";
  return date.replace(/-/g, "/");
};

/**
 * 获取图片URL
 * @param item 图片项（可能是文件对象或URL字符串）
 * @returns 图片URL
 */
const getImageUrl = (item: any): string => {
  if (typeof item === "string") {
    return item;
  }
  if (item.url) {
    return item.url;
  }
  if (item.response && item.response.data) {
    return item.response.data;
  }
  return "";
};
</script>

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

/* 头部区域 */
.header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgb(0 0 0 / 2%);
}
.title {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

/* 内容区域布局 */
.content {
  display: flex;
  flex: 1;
  column-gap: 24px;
  width: 98%;
  padding: 0 12px;
  margin: 24px auto;

  /* 左侧内容区域 */
  .contentLeft {
    width: 50%;
    padding-right: 12px;
  }

  /* 右侧内容区域 */
  .contentRight {
    width: 50%;
    padding-left: 12px;
  }
}

/* 模块容器 */
.model {
  margin-bottom: 50px;
  h3 {
    padding-bottom: 12px;
    margin: 0 0 20px;
    font-size: 16px;
    color: #303133;
    border-bottom: 2px solid #e4e7ed;
  }
}

/* 详情项样式 */
.detail-item {
  display: flex;
  align-items: flex-start;
  min-height: 32px;
  margin-bottom: 24px;
}
.detail-label {
  flex-shrink: 0;
  min-width: 120px;
  font-size: 14px;
  font-weight: 500;
  line-height: 32px;
  color: #606266;
}
.detail-value {
  flex: 1;
  font-size: 14px;
  line-height: 32px;
  color: #303133;
  word-break: break-word;
}
.empty-text {
  color: #909399;
}

/* 图片列表样式 */
.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.detail-image {
  width: 100px;
  height: 100px;
  cursor: pointer;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 5%);
  transition: all 0.3s;
}
.detail-image:hover {
  border-color: #409eff;
  box-shadow: 0 4px 8px rgb(64 158 255 / 20%);
  transform: translateY(-2px);
}

/* 套餐内容样式 */
.package-content-item {
  align-items: flex-start;
}
.package-content-item .detail-value {
  line-height: 1.8;
}
.package-content-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}
.package-group-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.package-dish-item {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  padding: 8px 12px;
  font-size: 14px;
  line-height: 1.6;
  background-color: #f8f9fa;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.package-dish-item:hover {
  background-color: #f0f2f5;
}
.dish-category {
  font-weight: 500;
  color: #303133;
  white-space: nowrap;
}
.dish-name {
  color: #303133;
  white-space: nowrap;
}
.dish-price {
  font-weight: 500;
  color: #e6a23c;
  white-space: nowrap;
}
.dish-quantity {
  color: #606266;
  white-space: nowrap;
}
</style>
