<template>
  <!-- 优惠券管理 - 新建/编辑页面（参考 IssueCoupons 与设计图） -->
  <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">
        {{ type == "add" ? "新建优惠券" : "编辑优惠券" }}
      </h2>
    </div>
    <el-form :model="couponModel" ref="ruleFormRef" :rules="rules" label-width="200px" class="formBox">
      <div class="content">
        <!-- 左侧：优惠券类型、名称、折扣/面值、低消、时间、有效期 -->
        <div class="contentLeft">
          <!-- 优惠券类型 -->
          <el-form-item label="优惠券类型" prop="couponType">
            <el-radio-group v-model="couponModel.couponType" class="radio-group">
              <el-radio :value="2"> 折扣券 </el-radio>
              <el-radio :value="1"> 满减券 </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 优惠券名称 -->
          <el-form-item label="优惠券名称" prop="name">
            <el-input maxlength="50" v-model="couponModel.name" placeholder="请输入" clearable />
          </el-form-item>
          <!-- 折扣力度（折扣券） -->
          <el-form-item v-if="couponModel.couponType === 2" label="折扣力度" prop="discountRate">
            <el-input v-model="couponModel.discountRate" maxlength="4" placeholder="请输入0.1-9.9之间的数字" clearable>
              <template #suffix> 折 </template>
            </el-input>
          </el-form-item>
          <!-- 面值（满减券） -->
          <el-form-item v-if="couponModel.couponType === 1" label="面值(￥)" prop="nominalValue">
            <el-input v-model="couponModel.nominalValue" maxlength="15" placeholder="请输入" clearable />
          </el-form-item>
          <!-- 是否有低消 -->
          <el-form-item label="是否有低消" prop="hasMinimumSpend">
            <el-radio-group v-model="couponModel.hasMinimumSpend" class="radio-group">
              <el-radio :value="1"> 是 </el-radio>
              <el-radio :value="0"> 否 </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 最低消费金额（元可用） -->
          <el-form-item v-if="couponModel.hasMinimumSpend === 1" label="" prop="minimumSpendingAmount" class="no-label">
            <el-input v-model="couponModel.minimumSpendingAmount" maxlength="15" placeholder="请输入" clearable>
              <template #suffix> 元可用 </template>
            </el-input>
          </el-form-item>
          <!-- 开始领取时间 -->
          <el-form-item label="开始领取时间" prop="beginGetDate">
            <el-date-picker
              v-model="couponModel.beginGetDate"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              placeholder="年/月/日"
              :disabled-date="disabledStartDate"
              style="width: 100%"
            />
          </el-form-item>
          <!-- 结束领取时间 -->
          <el-form-item label="结束领取时间" prop="endGetDate">
            <el-date-picker
              v-model="couponModel.endGetDate"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              placeholder="年/月/日"
              :disabled-date="disabledEndDate"
              style="width: 100%"
            />
          </el-form-item>
          <!-- 有效期 -->
          <el-form-item label="有效期" prop="specifiedDay">
            <el-input v-model="couponModel.specifiedDay" maxlength="5" placeholder="请输入" clearable>
              <template #suffix> 天 </template>
            </el-input>
          </el-form-item>
        </div>
        <!-- 右侧：库存、用户领取规则、收藏店铺、补充说明 -->
        <div class="contentRight">
          <!-- 库存 -->
          <el-form-item label="库存" prop="singleQty">
            <el-input v-model="couponModel.singleQty" maxlength="5" placeholder="请输入" clearable>
              <template #suffix> 张 </template>
            </el-input>
          </el-form-item>
          <!-- 用户领取规则 -->
          <!-- <el-form-item label="用户领取规则" prop="claimRule" class="claim-rule-item">
            <template #label>
              <span>用户领取规则</span>
              <span class="label-tip">（用户间隔多久可以领取一次）</span>
            </template>
            <el-radio-group v-model="couponModel.claimRule" class="radio-group block">
              <el-radio value="day"> 每日一领 </el-radio>
              <el-radio value="week"> 每周一领 </el-radio>
              <el-radio value="month"> 每月一领 </el-radio>
            </el-radio-group>
          </el-form-item> -->
          <!-- 用户是否需要收藏店铺领取 -->
          <el-form-item label="用户是否需要收藏店铺领取" prop="attentionCanReceived">
            <el-radio-group v-model="couponModel.attentionCanReceived" class="radio-group">
              <el-radio :value="1"> 是 </el-radio>
              <el-radio :value="0"> 否 </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 补充说明 -->
          <el-form-item label="补充说明" prop="supplementaryInstruction">
            <el-input
              maxlength="300"
              v-model="couponModel.supplementaryInstruction"
              :rows="4"
              type="textarea"
              placeholder="请输入"
              show-word-limit
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!-- 底部按钮区域 -->
    <div class="button-container">
      <!-- <el-button @click="() => handleSubmit('draft')"> 存草稿 </el-button> -->
      <el-button type="primary" @click="() => handleSubmit()">
        {{ type === "add" ? "新建优惠券" : "编辑优惠券" }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="tsx" name="newCoupon">
/**
 * 优惠券管理 - 新建/编辑页面
 * 参考：group_merchant IssueCoupons、设计图布局（左：类型/名称/折扣或面值/低消/时间/有效期，右：库存/领取规则/收藏/补充说明）
 */
import { ref, reactive, watch, nextTick, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { getCouponDetail, addDiscountCoupon, editDiscountCoupon } from "@/api/modules/couponManagement";
import { validatePositiveNumber, validatePositiveInteger, validateDateRange, validatePriceFormat } from "@/utils/eleValidate";
import { localGet } from "@/utils";

const router = useRouter();
const route = useRoute();
const type = ref<string>("");
const id = ref<string>("");

// 折扣力度校验：0.1-9.9
const validateDiscountRate = (_rule: any, value: any, callback: (err?: Error) => void) => {
  if (couponModel.value.couponType !== 2) {
    callback();
    return;
  }
  if (value === null || value === undefined || value === "") {
    callback(new Error("请输入折扣力度"));
    return;
  }
  const num = Number(value);
  if (isNaN(num) || num < 0.1 || num > 9.9) {
    callback(new Error("请输入0.1-9.9之间的数字"));
    return;
  }
  callback();
};

const rules = reactive({
  name: [{ required: true, message: "请输入优惠券名称" }],
  couponType: [{ required: true, message: "请选择优惠券类型" }],
  nominalValue: [
    {
      validator: (_rule: any, value: any, callback: (err?: Error) => void) => {
        if (couponModel.value.couponType !== 1) {
          callback();
          return;
        }
        if (!value || value.toString().trim() === "") {
          callback(new Error("请输入面值"));
          return;
        }
        const next = validatePriceFormat("整数部分最多6位，小数部分最多2位");
        next(_rule, value, callback);
      },
      trigger: "blur"
    }
  ],
  discountRate: [{ validator: validateDiscountRate, trigger: "blur" }],
  beginGetDate: [
    { required: true, message: "请选择开始领取时间" },
    {
      validator: validateDateRange(
        () => couponModel.value.beginGetDate,
        () => couponModel.value.endGetDate,
        "开始领取时间不能早于当前时间",
        "结束领取时间不能早于当前时间",
        "开始领取时间必须早于结束领取时间",
        true,
        true
      ),
      trigger: "change"
    }
  ],
  endGetDate: [
    { required: true, message: "请选择结束领取时间" },
    {
      validator: validateDateRange(
        () => couponModel.value.beginGetDate,
        () => couponModel.value.endGetDate,
        "开始领取时间不能早于当前时间",
        "结束领取时间不能早于当前时间",
        "开始领取时间必须早于结束领取时间",
        true,
        true
      ),
      trigger: "change"
    }
  ],
  specifiedDay: [
    { required: true, message: "请输入有效期" },
    {
      validator: validatePositiveInteger("有效期必须为正整数", { required: false }),
      trigger: "blur"
    }
  ],
  singleQty: [
    { required: true, message: "请输入库存" },
    {
      validator: validatePositiveInteger("库存必须为正整数", { required: false }),
      trigger: "blur"
    }
  ],
  minimumSpendingAmount: [
    {
      validator: (_rule: any, value: any, callback: (err?: Error) => void) => {
        if (couponModel.value.hasMinimumSpend !== 1) {
          callback();
          return;
        }
        if (value === null || value === undefined || value === "") {
          callback(new Error("请输入最低消费金额"));
          return;
        }
        const next = validatePositiveNumber("最低消费金额必须为正数");
        next(_rule, value, callback);
      },
      trigger: "blur"
    },
    {
      validator: (_rule: any, value: any, callback: (err?: Error) => void) => {
        if (couponModel.value.hasMinimumSpend !== 1 || !value) {
          callback();
          return;
        }
        const next = validatePriceFormat("整数部分最多6位，小数部分最多2位");
        next(_rule, value, callback);
      },
      trigger: "blur"
    }
  ]
});

const claimRuleOptions = [
  { label: "每日一领", value: "day" },
  { label: "每周一领", value: "week" },
  { label: "每月一领", value: "month" }
];

const yesNoOptions = [
  { label: "是", value: 1 },
  { label: "否", value: 0 }
];

// 1-满减券 2-折扣券（与 ticketManagement index couponTypeEnum 一致）
const couponModel = ref<any>({
  name: "",
  couponType: 2,
  nominalValue: "",
  discountRate: "",
  beginGetDate: "",
  endGetDate: "",
  specifiedDay: "",
  singleQty: "",
  claimRule: "day",
  attentionCanReceived: 1,
  hasMinimumSpend: 0,
  minimumSpendingAmount: "",
  supplementaryInstruction: ""
});

const isInitializing = ref(true);

watch(
  () => couponModel.value.beginGetDate,
  () => {
    if (isInitializing.value) return;
    if (couponModel.value.endGetDate) {
      nextTick(() => ruleFormRef.value?.validateField("endGetDate"));
    }
  }
);

watch(
  () => couponModel.value.endGetDate,
  () => {
    if (isInitializing.value) return;
    if (couponModel.value.beginGetDate) {
      nextTick(() => ruleFormRef.value?.validateField("beginGetDate"));
    }
  }
);

watch(
  () => couponModel.value.hasMinimumSpend,
  newVal => {
    if (isInitializing.value) return;
    if (newVal === 0) {
      couponModel.value.minimumSpendingAmount = "";
      nextTick(() => ruleFormRef.value?.clearValidate("minimumSpendingAmount"));
    }
  }
);

// 切换优惠券类型时清空另一类字段并清校验
watch(
  () => couponModel.value.couponType,
  newVal => {
    if (isInitializing.value) return;
    if (newVal === 1) {
      couponModel.value.discountRate = "";
      nextTick(() => ruleFormRef.value?.clearValidate("discountRate"));
    } else {
      couponModel.value.nominalValue = "";
      nextTick(() => ruleFormRef.value?.clearValidate("nominalValue"));
    }
  }
);

onMounted(async () => {
  id.value = (route.query.id as string) || "";
  type.value = (route.query.type as string) || "add";
  if (type.value !== "add" && id.value) {
    const res: any = await getCouponDetail({ counponId: id.value });
    const data = res.data || {};
    couponModel.value = {
      ...couponModel.value,
      ...data,
      couponType: data.couponType ?? 1,
      discountRate: data.discountRate != null ? (Number(data.discountRate) / 10).toString() : "",
      hasMinimumSpend: Number(data.minimumSpendingAmount) > 0 ? 1 : 0
    };
  } else {
    couponModel.value.couponType = couponModel.value.couponType ?? 2;
  }
  await nextTick();
  ruleFormRef.value?.clearValidate();
  isInitializing.value = false;
});

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

const ruleFormRef = ref<FormInstance>();

const handleSubmit = async (submitType?: string) => {
  const params: any = {
    ...couponModel.value,
    storeId: localGet("createdId"),
    couponId: type.value === "edit" ? id.value : "",
    couponStatus: submitType ? 0 : 1,
    restrictedQuantity: 0,
    expirationDate: 0,
    getStatus: 1,
    type: 1
  };
  // 折扣券：discountRate 后端多为 1-100（如 85 表示 8.5 折），此处按 0.1-9.9 输入则乘 10
  if (params.couponType === 2 && params.discountRate !== "" && params.discountRate != null) {
    const rate = Number(params.discountRate);
    params.discountRate = !isNaN(rate) ? Math.round(rate * 10) : null;
  }
  if (params.couponType === 1) {
    params.discountRate = null;
  }
  if (!params.hasMinimumSpend) {
    params.minimumSpendingAmount = 0;
  }

  if (submitType) {
    if (!couponModel.value.name?.trim()) {
      ElMessage.warning("请填写优惠券名称");
      return;
    }
    if (type.value === "add") {
      const res: any = await addDiscountCoupon(params);
      if (res?.code == 200) {
        ElMessage.success("草稿保存成功");
        goBack();
      }
    } else {
      params.couponId = id.value;
      const res: any = await editDiscountCoupon(params);
      if (res?.code == 200) {
        ElMessage.success("草稿保存成功");
        goBack();
      }
    }
    return;
  }

  ruleFormRef.value!.validate(async (valid: boolean) => {
    if (!valid) return;
    if (type.value === "add") {
      const res: any = await addDiscountCoupon(params);
      if (res?.code == 200) {
        ElMessage.success("创建成功");
        goBack();
      }
    } else {
      params.couponId = id.value;
      const res: any = await editDiscountCoupon(params);
      if (res?.code == 200) {
        ElMessage.success("修改成功");
        goBack();
      }
    }
  });
};

const disabledStartDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

const disabledEndDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  if (time.getTime() < today.getTime()) return true;
  if (couponModel.value.beginGetDate) {
    const startDate = new Date(couponModel.value.beginGetDate);
    startDate.setHours(0, 0, 0, 0);
    return time.getTime() < startDate.getTime();
  }
  return false;
};
</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;
  border-bottom: 1px solid #e4e7ed;
}
.title {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
.content {
  display: flex;
  flex: 1;
  column-gap: 24px;
  width: 98%;
  margin: 20px auto;
  .contentLeft {
    width: 50%;
  }
  .contentRight {
    width: 50%;
  }
}
.formBox {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100%;
}
.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  &.block {
    flex-direction: column;
    gap: 4px;
  }
}
.claim-rule-item :deep(.el-form-item__label) {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.label-tip {
  margin-left: 4px;
  font-size: 12px;
  font-weight: normal;
  color: #909399;
}
.no-label :deep(.el-form-item__label) {
  width: 0 !important;
  padding: 0;
  margin: 0;
}
.button-container {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  margin-top: 20px;
}
</style>
