<template>
  <!-- 好友优惠券 - 详情页面（数据由列表页 sessionStorage 传入，不调详情接口） -->
  <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">
              {{ couponModel.storeName || "--" }}
            </div>
          </div>
          <!-- 类型 -->
          <div class="detail-item">
            <div class="detail-label">类型</div>
            <div class="detail-value">
              {{ getCouponTypeText(couponModel.couponType) }}
            </div>
          </div>
          <!-- 优惠券名称 -->
          <div class="detail-item">
            <div class="detail-label">优惠券名称</div>
            <div class="detail-value">
              {{ couponModel.couponName || couponModel.name || "--" }}
            </div>
          </div>
          <!-- 折扣券：折扣率；满减券等：面值 -->
          <div class="detail-item" v-if="Number(couponModel.couponType) === 2">
            <div class="detail-label">折扣率</div>
            <div class="detail-value">
              {{ formatDiscountRateDisplay(couponModel.discountRate) }}
            </div>
          </div>
          <div class="detail-item" v-else>
            <div class="detail-label">面值</div>
            <div class="detail-value">
              {{ formatCurrency(couponModel.nominalValue ?? couponModel.price, 2, "￥") }}
            </div>
          </div>
          <!-- 数量 -->
          <div class="detail-item">
            <div class="detail-label">数量</div>
            <div class="detail-value">
              {{ couponModel.ownedQuantity ?? couponModel.couponNum ?? couponModel.singleQty ?? "--" }}
            </div>
          </div>
          <!-- 有效期：longTermValid=1 长期有效；否则展示 expirationDate（天） -->
          <div class="detail-item">
            <div class="detail-label">有效期</div>
            <div class="detail-value">
              {{ getValidityDisplay() }}
            </div>
          </div>
          <!-- 最低消费金额 -->
          <div class="detail-item">
            <div class="detail-label">最低消费金额</div>
            <div class="detail-value">
              {{ formatCurrency(couponModel.minimumSpendingAmount, 2, "￥") }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="friendCouponDetail">
/**
 * 好友优惠券 - 详情页：数据来自列表行（sessionStorage），不请求详情接口
 */
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { formatCurrency } from "@/utils/formatCurrency";

const FRIEND_COUPON_DETAIL_ROW_KEY = "friendCoupon_detail_row";

const router = useRouter();

const couponModel = ref<any>({
  acName: "",
  couponName: "",
  couponNum: 0,
  deleteFlag: 0,
  endDate: "",
  expirationDate: "",
  longTermValid: undefined as number | undefined,
  id: 0,
  imgUrl: "",
  lifeDiscountCouponFriendRuleDetailVos: [],
  minimumSpendingAmount: undefined,
  moneyHigh: 0,
  moneyLow: 0,
  nominalValue: 0,
  discountRate: undefined,
  status: "",
  storeId: 0,
  storeName: ""
});

const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  const raw = sessionStorage.getItem(FRIEND_COUPON_DETAIL_ROW_KEY);
  sessionStorage.removeItem(FRIEND_COUPON_DETAIL_ROW_KEY);

  if (!raw) {
    ElMessage.warning("缺少列表数据，请从列表重新进入");
    router.go(-1);
    return;
  }

  try {
    const row = JSON.parse(raw);
    couponModel.value = { ...couponModel.value, ...row };
  } catch {
    ElMessage.error("数据解析失败");
    router.go(-1);
  }
});

const getValidityDisplay = () => {
  const m = couponModel.value;
  const lt = m.longTermValid;
  if (lt === 1 || lt === "1" || lt === true) return "长期有效";
  const ed = m.expirationDate;
  if (ed === null || ed === undefined || ed === "") return "--";
  const s = String(ed).trim();
  if (/^\d{4}-\d{2}-\d{2}/.test(s) || s.includes("T")) {
    return s.includes("-") ? (s.replace(/-/g, "/").split(" ")[0] ?? s) : s;
  }
  return Number.isNaN(Number(s)) ? s : `${s}天`;
};

const formatDiscountRateDisplay = (rate: unknown) => {
  if (rate === null || rate === undefined || rate === "") return "--";
  const n = Number(rate);
  if (isNaN(n)) return `${rate}折`;
  // 与 newCoupon 一致：接口多为 1–100（如 85 表示 8.5 折），展示时除以 10
  const x = n / 10;
  const s = Number.isInteger(x) ? String(x) : String(Number(x.toFixed(1)));
  return `${s.replace(/\.0$/, "")}折`;
};

const getCouponTypeText = (t: number | string | undefined) => {
  const typeMap: Record<string, string> = { "1": "满减券", "2": "折扣券" };
  return t != null && t !== "" ? (typeMap[String(t)] ?? String(t)) : "--";
};
</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;
  }
}
.detail-item {
  display: flex;
  align-items: flex-start;
  min-height: 32px;
  margin-bottom: 24px;
}
.detail-label {
  flex-shrink: 0;
  min-width: 200px;
  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;
}
</style>
