<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>
    <el-form :model="voucherModel" 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="name">
              <el-input maxlength="20" v-model="voucherModel.name" placeholder="请输入" clearable />
            </el-form-item>
            <!-- 抵扣价格 -->
            <el-form-item label="抵扣价格(¥)" prop="offprice">
              <el-input v-model="voucherModel.offprice" maxlength="15" placeholder="请输入" clearable />
            </el-form-item>
            <!-- 售卖价格 -->
            <el-form-item label="售卖价格(¥)" prop="price">
              <el-input v-model="voucherModel.price" maxlength="15" placeholder="请输入" clearable />
            </el-form-item>
            <!-- 开始售卖时间 -->
            <el-form-item label="开始售卖时间" prop="startDate">
              <el-date-picker
                v-model="voucherModel.startDate"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始售卖时间"
                :disabled-date="disabledStartDate"
              />
            </el-form-item>
            <!-- 结束售卖时间 -->
            <el-form-item label="结束售卖时间" prop="endDate">
              <el-date-picker
                v-model="voucherModel.endDate"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束售卖时间"
                :disabled-date="disabledEndDate"
              />
            </el-form-item>
          </div>
          <!-- 购买须知模块 -->
          <div class="model">
            <h3 style="font-weight: bold">购买须知：</h3>
            <!-- 使用时间 -->
            <el-form-item label="使用时间" prop="usageTime">
              <div class="time-range-container">
                <el-select v-model="voucherModel.buyUseStartTime" placeholder="开始时间" class="time-picker">
                  <el-option v-for="hour in hourOptions" :key="hour.value" :label="hour.label" :value="hour.value" />
                </el-select>
                <span class="time-separator">至</span>
                <el-select v-model="voucherModel.buyUseEndTime" placeholder="结束时间" class="time-picker">
                  <el-option v-for="hour in hourOptions" :key="hour.value" :label="hour.label" :value="hour.value" />
                </el-select>
              </div>
            </el-form-item>
            <!-- 有效期 -->
            <el-form-item label="有效期" prop="expirationType">
              <el-radio-group v-model="voucherModel.expirationType" class="ml-4">
                <el-radio v-for="status in validityPeriodList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" prop="expirationDate" v-if="voucherModel.expirationType == 0">
              <div class="expiration-date-container">
                <span class="expiration-label">用户购买</span>
                <el-input-number
                  v-model="voucherModel.expirationDate"
                  placeholder="请输入"
                  :min="0"
                  :max="10000"
                  class="expiration-input"
                />
                <span class="expiration-label">天内有效</span>
              </div>
            </el-form-item>
            <el-form-item label="" prop="validityPeriod" v-else>
              <el-date-picker
                v-model="voucherModel.validityPeriod"
                type="daterange"
                value-format="x"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :disabled-date="disabledValidityDate"
              />
            </el-form-item>
            <!-- 不可用日期 -->
            <el-form-item label="不可用日期" prop="unusedType">
              <el-radio-group v-model="voucherModel.unusedType" class="ml-4">
                <el-radio v-for="status in unavailableDateTypeList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="voucherModel.unusedType == 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="voucherModel.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="voucherModel.unavailableHolidays?.includes(String(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="voucherModel.unusedType == 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 voucherModel.disableDateList" :key="index" class="date-item">
                  <el-date-picker
                    v-model="voucherModel.disableDateList[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="voucherModel.disableDateList.length > 1"
                  />
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
        <!-- 右侧内容区域 -->
        <div class="contentRight">
          <!-- 库存模块 -->
          <div class="model">
            <h3 style="font-weight: bold">库存：</h3>
            <el-form-item label="库存" prop="singleQty">
              <el-input v-model="voucherModel.singleQty" maxlength="15" placeholder="请输入" clearable />
            </el-form-item>
          </div>
          <!-- 使用规则模块 -->
          <div class="model">
            <h3 style="font-weight: bold">使用规则：</h3>
            <!-- 单次可用数量 -->
            <el-form-item label="单次可用数量" prop="singleCanUse">
              <el-input v-model="voucherModel.singleCanUse" maxlength="15" placeholder="请输入" clearable />
            </el-form-item>
            <!-- 限购数量 -->
            <el-form-item label="限购数量" prop="purchaseLimitCode">
              <el-input v-model="voucherModel.purchaseLimitCode" maxlength="15" placeholder="请输入" clearable />
            </el-form-item>
            <!-- 适用范围 -->
            <el-form-item label="适用范围" prop="applyType">
              <el-radio-group v-model="voucherModel.applyType" class="ml-4">
                <el-radio v-for="status in applicableScopeList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" prop="applyDesc" v-if="voucherModel.applyType == 2">
              <el-input
                maxlength="50"
                v-model="voucherModel.applyDesc"
                :rows="3"
                type="textarea"
                placeholder="请输入"
                show-word-limit
              />
            </el-form-item>
          </div>
          <!-- 补充说明模块 -->
          <div class="model">
            <h3 style="font-weight: bold">补充说明：</h3>
            <el-form-item label="补充说明" prop="supplement">
              <el-input
                maxlength="300"
                v-model="voucherModel.supplement"
                :rows="4"
                type="textarea"
                placeholder="请输入"
                show-word-limit
              />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <!-- 底部按钮区域 -->
    <div class="button-container">
      <el-button @click="handleSubmit('draft')"> 存草稿 </el-button>
      <el-button type="primary" @click="handleSubmit()"> 新建代金券 </el-button>
    </div>
  </div>
</template>

<script setup lang="tsx" name="newVoucher">
/**
 * 代金券管理 - 新增/编辑页面
 * 功能：支持代金券的新增和编辑操作
 */
import { ref, reactive, watch, nextTick, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { getVoucherDetail, getHolidayList, addOrUpdateCoupon } from "@/api/modules/voucherManagement";
import {
  validatePositiveNumber,
  validatePositiveInteger,
  validateDateRange,
  validateDateRangeArray,
  validateConditionalRequired,
  validateArrayMinLength,
  validateDateListArray,
  validatePriceFormat,
  validatePriceComparison
} from "@/utils/eleValidate";
import { localGet } from "@/utils";

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

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

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

// ==================== 表单验证规则 ====================
const rules = reactive({
  name: [{ required: true, message: "请输入代金券名称" }],
  offprice: [
    { required: true, message: "请输入抵扣价格" },
    {
      validator: validatePositiveNumber("抵扣价格必须为正数"),
      trigger: "blur"
    },
    {
      validator: validatePriceFormat("整数部分最多6位，小数部分最多2位"),
      trigger: "blur"
    },
    {
      validator: validatePriceComparison(
        () => voucherModel.value.offprice,
        () => voucherModel.value.price,
        "抵扣价格不能低于售卖价格"
      ),
      trigger: "blur"
    }
  ],
  price: [
    { required: true, message: "请输入售卖价格" },
    {
      validator: validatePositiveNumber("售卖价格必须为正数"),
      trigger: "blur"
    },
    {
      validator: validatePriceFormat("整数部分最多6位，小数部分最多2位"),
      trigger: "blur"
    },
    {
      validator: validatePriceComparison(
        () => voucherModel.value.offprice,
        () => voucherModel.value.price,
        "抵扣价格不能低于售卖价格"
      ),
      trigger: "blur"
    }
  ],
  startDate: [
    { required: true, message: "请选择开始售卖时间" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback();
          return;
        }
        const selectedDate = new Date(value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        // 验证不能早于今天
        if (selectedDate < today) {
          callback(new Error("开始售卖时间不能早于当前时间"));
          return;
        }
        // 验证开始时间必须早于结束时间
        const endDate = voucherModel.value.endDate;
        if (endDate) {
          const end = new Date(endDate);
          if (selectedDate >= end) {
            callback(new Error("开始售卖时间必须早于结束售卖时间"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  endDate: [
    { required: true, message: "请选择结束售卖时间" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback();
          return;
        }
        const selectedDate = new Date(value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        // 验证不能早于今天
        if (selectedDate < today) {
          callback(new Error("结束售卖时间不能早于当前时间"));
          return;
        }
        // 验证结束时间必须晚于开始时间
        const startDate = voucherModel.value.startDate;
        if (startDate) {
          const start = new Date(startDate);
          if (selectedDate <= start) {
            callback(new Error("开始售卖时间必须早于结束售卖时间"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  usageTime: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!voucherModel.value.buyUseStartTime || !voucherModel.value.buyUseEndTime) {
          callback(new Error("请选择使用时间"));
          return;
        }
        callback();
      },
      trigger: []
    }
  ],
  expirationType: [{ required: true, message: "请选择有效期类型" }],
  expirationDate: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.expirationType == 0) {
          if (value === null || value === undefined || value === "") {
            callback(new Error("请输入用户购买天数"));
            return;
          }
          // 先验证是否为正整数
          validatePositiveInteger("用户购买天数必须为正整数", { required: false, checkLeadingZero: false })(
            rule,
            value,
            (error: any) => {
              if (error) {
                callback(error);
                return;
              }
              // 验证最大值
              const numValue = Number(value);
              if (!isNaN(numValue) && numValue > 10000) {
                callback(new Error("有效期不得大于10000"));
                return;
              }
              callback();
            }
          );
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  validityPeriod: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.expirationType == 1) {
          if (!value || value.length !== 2) {
            callback(new Error("请选择指定时间段"));
            return;
          }
          validateDateRangeArray("开始时间必须早于结束时间", true, "时间不能早于当前时间")(rule, value, callback);
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  unusedType: [{ required: true, message: "请选择不可用日期类型" }],
  unavailableWeekdays: [
    {
      validator: validateConditionalRequired(() => voucherModel.value.unusedType == 1, "至少需要选择一个星期"),
      trigger: "change"
    }
  ],
  unavailableHolidays: [
    {
      validator: validateConditionalRequired(() => voucherModel.value.unusedType == 1, "至少需要选择一个节日"),
      trigger: "change"
    }
  ],
  customUnavailableDates: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.unusedType == 2) {
          if (!voucherModel.value.disableDateList || voucherModel.value.disableDateList.length === 0) {
            callback(new Error("至少需要添加一个自定义不可用日期"));
            return;
          }
          validateDateListArray(
            () => voucherModel.value.disableDateList,
            "日期项未完整填写",
            "开始时间必须早于结束时间",
            true
          )(rule, value, callback);
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  singleQty: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // 非必填，如果为空则直接通过
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        // 先验证是否为正整数
        validatePositiveInteger("库存必须为正整数", { required: false })(rule, value, (error: any) => {
          if (error) {
            callback(error);
            return;
          }
          // 验证最大值
          if (value) {
            const numValue = Number(value);
            if (!isNaN(numValue) && numValue > 10000) {
              callback(new Error("库存不得大于10000"));
              return;
            }
          }
          callback();
        });
      },
      trigger: "blur"
    }
  ],
  singleCanUse: [
    {
      validator: validatePositiveInteger("单日可用数量必须为正整数", { required: false }),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 如果值为空，不进行验证
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        const stock = voucherModel.value.singleQty;
        // 如果库存为空，不进行验证（由库存的验证规则处理）
        if (!stock || stock.toString().trim() === "") {
          callback();
          return;
        }
        const useNum = Number(value);
        const stockNum = Number(stock);
        // 如果转换失败，不进行验证（由其他验证规则处理）
        if (isNaN(useNum) || isNaN(stockNum)) {
          callback();
          return;
        }
        // 验证单日可用数量不能多于库存
        if (useNum > stockNum) {
          callback(new Error("单日可用数量不能多于库存"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  purchaseLimitCode: [
    {
      validator: validatePositiveInteger("限购数量必须为正整数", { required: false }),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 如果值为空，不进行验证
        if (!value || value.toString().trim() === "") {
          callback();
          return;
        }
        const stock = voucherModel.value.singleQty;
        // 如果库存为空，不进行验证（由库存的验证规则处理）
        if (!stock || stock.toString().trim() === "") {
          callback();
          return;
        }
        const limitNum = Number(value);
        const stockNum = Number(stock);
        // 如果转换失败，不进行验证（由其他验证规则处理）
        if (isNaN(limitNum) || isNaN(stockNum)) {
          callback();
          return;
        }
        // 验证限购数量不能多于库存
        if (limitNum > stockNum) {
          callback(new Error("限购数量不能多于库存"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  applyDesc: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.applyType == 2) {
          if (!value || value.toString().trim() === "") {
            callback(new Error("请输入适用范围"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ]
});

// ==================== 代金券信息数据模型 ====================
const voucherModel = ref<any>({
  // 代金券名称
  name: "",
  // 抵扣价格
  offprice: "",
  // 售卖价格
  price: "",
  // 开始售卖时间
  startDate: "",
  // 结束售卖时间
  endDate: "",
  // 使用时间 - 开始时间
  buyUseStartTime: "",
  // 使用时间 - 结束时间
  buyUseEndTime: "",
  // 使用时间（虚拟字段，用于表单验证）
  usageTime: null,
  // 有效期类型：0-指定天数，1-指定时间段内可用
  expirationType: "0",
  // 有效期天数（当expirationType为0时使用）
  expirationDate: 0,
  // 有效期时间段（当expirationType为1时使用）
  validityPeriod: [],
  // 不可用日期类型：0-全部日期可用，1-限制日期
  unusedType: "0",
  // 限制日期 - 星期选择（数组，存储选中的星期值）
  unavailableWeekdays: [],
  // 限制日期 - 节日选择（数组，存储选中的节日值）
  unavailableHolidays: [],
  // 自定义不可用日期列表（数组，每个元素是一个日期范围 [startDate, endDate]）
  disableDateList: [],
  // 库存
  singleQty: "",
  // 单日可用数量
  singleCanUse: "",
  // 限购数量
  purchaseLimitCode: "",
  // 适用范围类型：0-全场通用，1-部分不可用
  applyType: "1",
  // 适用范围（当applyType为1时使用）
  applyDesc: "",
  // 补充说明
  supplement: ""
});

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

// 小时选项列表（0-23点）
const hourOptions = ref(
  Array.from({ length: 24 }, (_, i) => ({
    value: String(i),
    label: `${i}点`
  }))
);

// 有效期类型列表
const validityPeriodList = ref([
  { value: "0", label: "指定天数" },
  { value: "1", label: "指定时间段内可用" }
]);

// 不可用日期类型列表
const unavailableDateTypeList = ref([
  { value: "0", label: "全部日期可用" },
  { value: "1", label: "限制日期" }
  // { value: '2', label: "自定义不可用日期" }
]);

// 适用范围类型列表
const applicableScopeList = ref([
  { value: "1", label: "全场通用" },
  { value: "2", label: "部分不可用" }
]);

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

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

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

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

/**
 * 监听抵扣价格变化
 * 当抵扣价格改变时，重新验证售卖价格
 */
watch(
  () => voucherModel.value.offprice,
  () => {
    if (voucherModel.value.price) {
      nextTick(() => {
        ruleFormRef.value?.validateField("price");
      });
    }
  }
);

/**
 * 监听售卖价格变化
 * 当售卖价格改变时，重新验证抵扣价格
 */
watch(
  () => voucherModel.value.price,
  () => {
    if (voucherModel.value.offprice) {
      nextTick(() => {
        ruleFormRef.value?.validateField("offprice");
      });
    }
  }
);

/**
 * 监听库存变化
 * 当库存改变时，重新验证单日可用数量和限购数量
 */
watch(
  () => voucherModel.value.singleQty,
  () => {
    if (voucherModel.value.singleCanUse) {
      nextTick(() => {
        ruleFormRef.value?.validateField("singleCanUse");
      });
    }
    if (voucherModel.value.purchaseLimitCode) {
      nextTick(() => {
        ruleFormRef.value?.validateField("purchaseLimitCode");
      });
    }
  }
);

/**
 * 监听使用开始时间变化
 * 更新虚拟字段以支持表单验证
 */
watch(
  () => voucherModel.value.buyUseStartTime,
  () => {
    // 更新虚拟字段
    voucherModel.value.usageTime =
      voucherModel.value.buyUseStartTime && voucherModel.value.buyUseEndTime
        ? [voucherModel.value.buyUseStartTime, voucherModel.value.buyUseEndTime]
        : null;
  }
);

/**
 * 监听使用结束时间变化
 * 更新虚拟字段以支持表单验证
 */
watch(
  () => voucherModel.value.buyUseEndTime,
  () => {
    // 更新虚拟字段
    voucherModel.value.usageTime =
      voucherModel.value.buyUseStartTime && voucherModel.value.buyUseEndTime
        ? [voucherModel.value.buyUseStartTime, voucherModel.value.buyUseEndTime]
        : null;
  }
);

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

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

/**
 * 组件挂载时初始化
 * 从路由参数中获取页面类型和ID
 */
onMounted(async () => {
  id.value = (route.query.id as string) || "";
  type.value = (route.query.type as string) || "";

  // 加载节日列表
  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;
  }

  // 编辑模式下加载数据
  if (type.value != "add") {
    let res: any = await getVoucherDetail({ id: id.value });
    voucherModel.value = { ...voucherModel.value, ...res.data };
    // 处理有效期时间段：将时间戳字符串转换为数字数组
    if (voucherModel.value.validityPeriod && voucherModel.value.expirationType == 1) {
      const periodArray = voucherModel.value.validityPeriod.split(",");
      voucherModel.value.validityPeriod = periodArray
        .map((item: string) => Number(item.trim()))
        .filter((item: number) => !isNaN(item));
    } else {
      voucherModel.value.validityPeriod = [];
    }
    // 确保星期和节日字段存在;
    if (voucherModel.value.unusedType == 1) {
      const listVal = voucherModel.value.unusedDate ? voucherModel.value.unusedDate.split(";") : [];
      voucherModel.value.unavailableWeekdays = listVal[0] ? listVal[0].split(",").filter((item: string) => item) : [];
      voucherModel.value.unavailableHolidays = listVal[1] ? listVal[1].split(",").filter((item: string) => item) : [];
    }
    // 确保自定义不可用日期字段存在;
    if (voucherModel.value.unusedType === 2) {
      if (!voucherModel.value.disableDateList || voucherModel.value.disableDateList.length === 0) {
        voucherModel.value.disableDateList = [null];
      }
    }
    console.log(voucherModel.value);
  }
});

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

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

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

/**
 * 切换节日选择
 * @param value 节日值
 */
const toggleHoliday = (value: string | number) => {
  if (!voucherModel.value.unavailableHolidays) {
    voucherModel.value.unavailableHolidays = [];
  }
  // 统一转换为字符串进行比较
  const valueStr = String(value);
  const index = voucherModel.value.unavailableHolidays.findIndex((item: any) => String(item) === valueStr);
  if (index > -1) {
    voucherModel.value.unavailableHolidays.splice(index, 1);
  } else {
    voucherModel.value.unavailableHolidays.push(valueStr);
  }
  // 触发表单验证
  nextTick(() => {
    ruleFormRef.value?.validateField("unavailableHolidays");
  });
};

/**
 * 添加自定义不可用日期
 */
const addDate = () => {
  if (!voucherModel.value.disableDateList) {
    voucherModel.value.disableDateList = [];
  }
  voucherModel.value.disableDateList.push(null);
};

/**
 * 删除自定义不可用日期
 * @param index 要删除的日期索引
 */
const removeDate = (index: number) => {
  if (voucherModel.value.disableDateList.length <= 1) {
    ElMessage.warning("至少需要保留一个日期项");
    return;
  }
  voucherModel.value.disableDateList.splice(index, 1);
  // 删除日期项后，重新验证表单以清除旧的验证错误
  nextTick(() => {
    ruleFormRef.value?.validateField("customUnavailableDates");
  });
};

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

/**
 * 提交数据（新增/编辑）
 * 验证表单，通过后调用相应的API接口
 */
const handleSubmit = async (submitType?: string) => {
  // 组装提交参数
  let params: any = { ...voucherModel.value };
  params.storeId = localGet("createdId");
  params.status = 1;
  // 处理有效期：只有当expirationType为1（指定时间段内可用）时才处理validityPeriod
  if (params.expirationType == 1 && params.validityPeriod && Array.isArray(params.validityPeriod)) {
    params.validityPeriod = params.validityPeriod.join(",");
  } else if (params.expirationType == 0) {
    // 指定天数模式，不需要validityPeriod字段
    params.validityPeriod = "";
  }
  // 处理不可用日期
  if (params.unusedType == 1) {
    params.unusedDate = params.unavailableWeekdays.join(",") + ";" + params.unavailableHolidays.join(",");
  } else if (params.unusedType == 2) {
    // 处理自定义不可用日期
    if (params.disableDateList && params.disableDateList.length > 0) {
      params.unusedDate = params.disableDateList
        .map((dateRange: any) => (dateRange && dateRange.length === 2 ? dateRange.join(",") : ""))
        .filter((item: string) => item)
        .join(";");
    }
  }
  params.dataType = submitType ? 1 : 0;
  delete params.unavailableWeekdays;
  delete params.unavailableHolidays;
  delete params.disableDateList;
  console.log("提交参数:", params);
  if (submitType) {
    if (!voucherModel.value.name) {
      ElMessage.warning("请填写代金券名称");
      return;
    }
    let res: any = await addOrUpdateCoupon(params);
    if (res && res.code == 200) {
      ElMessage.success("保存成功");
      goBack();
    }
    return;
  }
  // 验证表单
  ruleFormRef.value!.validate(async (valid: boolean) => {
    if (!valid) return;
    let res: any = await addOrUpdateCoupon(params);
    if (res && 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 (voucherModel.value.startDate) {
    const startDate = new Date(voucherModel.value.startDate);
    startDate.setHours(0, 0, 0, 0);
    return time.getTime() <= startDate.getTime();
  }
  return false;
};

/**
 * 禁用有效期时间段的日期
 * 不能选择早于当前时间的日期
 * @param time 日期对象
 * @returns 是否禁用该日期
 */
const disabledValidityDate = (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();
};
</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: 20px;
  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;
}

/* 有效期天数容器 */
.expiration-date-container {
  display: flex;
  gap: 12px;
  align-items: center;
  width: fit-content;
  padding: 8px 12px;
  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.1s;
}

/* 日期选择器容器 */
.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;
  border-radius: 4px;
  transition: background-color 0.1s;
  &:hover {
    background-color: #ecf5ff;
  }
}

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

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

/* 时间范围容器 */
.time-range-container {
  display: flex;
  gap: 12px;
  align-items: center;
  width: 100%;
}

/* 时间选择器 */
.time-picker {
  flex: 1;
  max-width: 200px;
}

/* 时间分隔符 */
.time-separator {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}
</style>
