<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">
              {{ activityModel.activityName || "--" }}
            </div>
          </div>
          <!-- 活动类型 -->
          <div class="detail-item">
            <div class="detail-label">活动类型</div>
            <div class="detail-value">
              {{ getActivityTypeLabel(activityModel.activityType) }}
            </div>
          </div>
          <!-- 活动时间 -->
          <div class="detail-item">
            <div class="detail-label">活动时间</div>
            <div class="detail-value">
              <span v-if="activityModel.startTime && activityModel.endTime">
                {{ formatDate(activityModel.startTime) }} - {{ formatDate(activityModel.endTime) }}
              </span>
              <span v-else>--</span>
            </div>
          </div>

          <!-- 评论有礼相关字段 -->
          <template v-if="activityModel.activityType == 2">
            <!-- 用户可参与次数 -->
            <div class="detail-item">
              <div class="detail-label">用户可参与次数</div>
              <div class="detail-value">
                {{ activityModel.participationLimit || "--" }}
              </div>
            </div>
            <!-- 优惠券/代金券名称 -->
            <div class="detail-item">
              <div class="detail-label">
                {{ activityModel.rewardType === "VOUCHER" ? "代金券" : "优惠券" }}
              </div>
              <div class="detail-value">
                {{
                  activityModel.rewardType === "VOUCHER" ? activityModel.voucherName || "--" : activityModel.couponName || "--"
                }}
              </div>
            </div>
            <!-- 优惠券/代金券发放数量 -->
            <div class="detail-item">
              <div class="detail-label">
                {{ (activityModel.rewardType === "VOUCHER" ? "代金券" : "优惠券") + "发放数量" }}
              </div>
              <div class="detail-value">
                {{
                  activityModel.rewardType === "VOUCHER"
                    ? activityModel.voucherQuantity || "--"
                    : activityModel.couponQuantity || "--"
                }}
              </div>
            </div>
          </template>

          <!-- 营销活动相关字段 -->
          <template v-if="activityModel.activityType == 1">
            <!-- 报名时间 -->
            <div class="detail-item">
              <div class="detail-label">报名时间</div>
              <div class="detail-value">
                <span v-if="activityModel.signupStartTime && activityModel.signupEndTime">
                  {{ activityModel.signupStartTime.split(" ")[0] }} - {{ activityModel.signupEndTime.split(" ")[0] }}
                </span>
                <span v-else>--</span>
              </div>
            </div>
            <!-- 活动限制人数 -->
            <div class="detail-item">
              <div class="detail-label">活动限制人数</div>
              <div class="detail-value">
                {{ activityModel.activityLimitPeople + "人" || "无限制" }}
              </div>
            </div>
            <!-- 活动详情 -->
            <div class="detail-item">
              <div class="detail-label">活动详情</div>
              <div class="detail-value" style="word-break: break-word; white-space: pre-wrap">
                {{ activityModel.activityDetails || "--" }}
              </div>
            </div>
          </template>
          <!-- 审核状态 -->
          <div class="detail-item">
            <div class="detail-label">审核状态</div>
            <div class="detail-value">
              {{ activityModel.auditStatus == 1 ? "审核通过" : "审核驳回" }}
            </div>
          </div>
          <!-- 审核时间 -->
          <div class="detail-item" v-if="activityModel.auditTime">
            <div class="detail-label">审核时间</div>
            <div class="detail-value">
              {{ formatDateTime(activityModel.auditTime) }}
            </div>
          </div>
          <!-- 审核拒绝原因 -->
          <div class="detail-item" v-if="activityModel.approvalComments">
            <div class="detail-label">审核拒绝原因</div>
            <div class="detail-value" style="word-break: break-word; white-space: pre-wrap">
              {{ activityModel.approvalComments }}
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧内容区域 -->
      <div class="contentRight">
        <!-- 活动宣传图模块 -->
        <div class="model">
          <div class="promotion-images-container">
            <!-- 活动标题图 -->
            <div class="promotion-image-item">
              <h3 style="font-weight: bold">活动标题图：</h3>
              <div class="image-container">
                <div v-if="getImageUrl(activityModel.activityTitleImgUrl)" class="image-item">
                  <el-image
                    :src="getImageUrl(activityModel.activityTitleImgUrl)"
                    fit="contain"
                    class="promotion-image"
                    :preview-src-list="getPreviewImageList()"
                    :initial-index="0"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon>
                          <Picture />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div v-else class="empty-text">--</div>
              </div>
            </div>
            <!-- 活动详情图 -->
            <div class="promotion-image-item">
              <h3 style="font-weight: bold">活动详情图：</h3>
              <div class="image-container">
                <div v-if="detailImageList.length > 0" class="detail-images-grid">
                  <div
                    v-for="(imgUrl, index) in detailImageList"
                    :key="index"
                    class="detail-image-item"
                    @click="previewDetailImage(index)"
                  >
                    <el-image
                      :src="imgUrl"
                      fit="cover"
                      class="detail-image"
                      :preview-src-list="getPreviewImageList()"
                      :initial-index="getImageUrl(activityModel.activityTitleImgUrl) ? index + 1 : index"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon>
                            <Picture />
                          </el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                </div>
                <div v-else class="empty-text">--</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="activityDetail">
/**
 * 运营活动管理 - 详情页面
 * 功能：显示运营活动的详细信息
 */
import { ref, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Picture } from "@element-plus/icons-vue";
import { getActivityDetail } from "@/api/modules/operationManagement";

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

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

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

// ==================== 活动信息数据模型 ====================
const activityModel = ref<any>({
  // 活动类型：1-评论有礼，2-营销活动
  activityType: 1,
  // 活动名称
  activityName: "",
  // 活动开始时间
  startTime: "",
  // 活动结束时间
  endTime: "",
  // 用户可参与次数（评论有礼）
  participationLimit: 0,
  // 券类型：'COUPON'-优惠券，'VOUCHER'-代金券（评论有礼）
  rewardType: "COUPON",
  // 优惠券ID（评论有礼）
  couponId: "",
  // 优惠券名称（评论有礼）
  couponName: "",
  // 优惠券发放数量（评论有礼）
  couponQuantity: 0,
  // 代金券ID（评论有礼）
  voucherId: "",
  // 代金券名称（评论有礼）
  voucherName: "",
  // 代金券发放数量（评论有礼）
  voucherQuantity: 0,
  // 报名开始时间（营销活动）
  signupStartTime: "",
  // 报名结束时间（营销活动）
  signupEndTime: "",
  // 活动限制人数（营销活动）
  activityLimitPeople: "",
  // 活动详情（营销活动）
  activityDetails: "",
  // 活动标题图片
  activityTitleImgUrl: null,
  // 活动详情图片
  activityDetailImgUrl: null,
  // 状态
  status: 0,
  // 审核时间
  approvalTime: "",
  auditTime: "",
  // 审核拒绝原因
  approvalComments: ""
});

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

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

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

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

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

/**
 * 加载详情数据
 */
const loadDetailData = async () => {
  try {
    const res: any = await getActivityDetail({ id: id.value });
    if (res && res.code == 200) {
      // 合并主数据
      const data = res.data || {};

      // 兼容旧数据格式：如果后端返回的是 couponType（数字），转换为 rewardType（字符串）
      let rewardType = "COUPON";
      if (data.rewardType) {
        rewardType = data.rewardType;
      } else if (data.couponType !== undefined) {
        rewardType = data.couponType === 4 ? "VOUCHER" : "COUPON";
      }

      // 合并数据，并根据 rewardType 设置对应字段
      activityModel.value = { ...activityModel.value, ...data, rewardType };
    } else {
      ElMessage.error("加载详情数据失败");
    }
  } catch (error) {
    console.error("加载详情数据出错:", error);
    ElMessage.error("加载详情数据出错");
  }
};

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

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

/**
 * 格式化日期时间
 * @param dateTime 日期时间字符串
 * @returns 格式化后的日期时间字符串
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "--";
  // 将 - 替换为 /，并保持时间部分
  return dateTime.replace(/-/g, "/");
};

/**
 * 获取活动类型标签
 */
const getActivityTypeLabel = (activityType: number) => {
  const typeMap: Record<number, string> = {
    1: "营销活动",
    2: "评论有礼"
  };
  return typeMap[activityType] || "--";
};

/**
 * 获取状态标签
 */
const getStatusLabel = (status: number) => {
  const statusMap: Record<number, string> = {
    1: "待审核",
    2: "未开始",
    3: "审核驳回",
    5: "进行中",
    6: "已下架",
    7: "已结束",
    8: "审核通过"
  };
  return statusMap[status] || "--";
};

/**
 * 获取审核状态标签（只显示审核相关的状态）
 */
const getAuditStatusLabel = (status: number) => {
  const auditStatusMap: Record<number, string> = {
    1: "待审核",
    2: "未开始",
    3: "审核驳回",
    5: "审核通过",
    8: "审核通过"
  };
  return auditStatusMap[status] || "--";
};

/**
 * 获取活动规则显示文本
 */
const getRuleDisplayText = (ruleValue: any) => {
  if (!ruleValue) return "--";

  // 如果是字符串，尝试解析为数组
  let ruleArray: any[] = [];
  if (typeof ruleValue === "string") {
    try {
      ruleArray = JSON.parse(ruleValue);
    } catch {
      return ruleValue.replace(/,/g, " / ");
    }
  } else if (Array.isArray(ruleValue)) {
    ruleArray = ruleValue;
  } else {
    return ruleValue.replace(/,/g, " / ");
  }

  // 将数组转换为显示文本，用 " / " 连接
  if (ruleArray && ruleArray.length > 0) {
    return ruleArray.filter(item => item).join(" / ");
  }

  return "--";
};

/**
 * 获取图片URL（支持对象和字符串格式）
 */
const getImageUrl = (img: any): string => {
  if (!img) return "";
  if (typeof img === "string") return img;
  if (img.url) return img.url;
  return "";
};

/**
 * 处理活动详情图列表（支持字符串、数组、对象数组）
 */
const detailImageList = computed(() => {
  const imgData = activityModel.value.activityDetailImgUrl || activityModel.value.activityDetailImgUrlList;
  if (!imgData) return [];

  // 如果是字符串，可能是逗号分隔的多张图片
  if (typeof imgData === "string") {
    return imgData.split(",").filter((url: string) => url.trim());
  }

  // 如果是数组
  if (Array.isArray(imgData)) {
    return imgData
      .map((item: any) => {
        if (typeof item === "string") return item;
        if (item && item.url) return item.url;
        return "";
      })
      .filter((url: string) => url);
  }

  return [];
});

/**
 * 获取预览图片列表
 */
const getPreviewImageList = () => {
  const list: string[] = [];
  const titleUrl = getImageUrl(activityModel.value.activityTitleImgUrl);
  if (titleUrl) {
    list.push(titleUrl);
  }
  // 添加所有详情图
  list.push(...detailImageList.value);
  return list;
};

/**
 * 预览详情图
 */
const previewDetailImage = (index: number) => {
  // 预览功能由 el-image 的 preview-src-list 自动处理
};
</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: 100%;
  max-width: 800px;
  padding: 24px;
  margin: 0 auto;
  background-color: #ffffff;
  .contentLeft {
    width: 50%;
    padding-right: 12px;
  }
  .contentRight {
    width: 50%;
    padding-left: 12px;
  }
}

/* 模块容器 */
.model {
  margin-bottom: 50px;
  h3 {
    width: 100%;
    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;
  width: 140px;
  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;
}

/* 活动宣传图容器 */
.promotion-images-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  align-items: flex-start;
  width: 100%;
}
.promotion-image-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
  .image-label {
    font-size: 14px;
    font-weight: 500;
    color: #409eff;
  }
}

/* 图片容器样式 */
.image-container {
  width: 100%;
  min-height: 100px;
}
.image-item {
  width: 100%;
}
.promotion-image {
  width: 100%;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
}
.empty-text {
  padding: 20px 0;
  font-size: 14px;
  color: #909399;
}

/* 活动标题图 - 21:9横向样式 */
.promotion-image-item:first-child {
  .image-container {
    width: 100%;
  }
  .image-item {
    width: 100%;
    aspect-ratio: 21 / 9;
  }
  .promotion-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

/* 活动详情图 - 网格布局 */
.promotion-image-item:last-child {
  .image-container {
    width: 100%;
  }
  .detail-images-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
    width: 100%;
  }
  .detail-image-item {
    width: 150px;
    height: 150px;
    overflow: hidden;
    cursor: pointer;
    background: #f5f7fa;
    border-radius: 8px;
  }
  .detail-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  min-height: 200px;
  font-size: 30px;
  color: var(--el-text-color-placeholder);
  background: var(--el-fill-color-light);
}
</style>
