<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">{{ type == "add" ? "新建" : "编辑" }}代金券</h2>
    </div>
    <el-form :model="voucherModel" ref="ruleFormRef" :rules="rules" label-width="130px" 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="price">
              <el-input v-model="voucherModel.price" maxlength="15" 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="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 == 1">
              <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 == 2">
              <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 == 3">
              <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
                :validate-event="!isInitializing"
              />
            </el-form-item>
          </div>
          <!-- 使用规则模块 -->
          <div class="model">
            <h3 style="font-weight: bold">使用规则：</h3>
            <!-- 单日可用数量 -->
            <el-form-item label="单日可用数量(张)" prop="singleCanUseType">
              <el-radio-group v-model="voucherModel.singleCanUseType" class="ml-4">
                <el-radio v-for="status in dailyUseLimitList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" prop="singleCanUse" v-if="voucherModel.singleCanUseType == 2">
              <el-input v-model="voucherModel.singleCanUse" maxlength="15" placeholder="请输入" clearable />
            </el-form-item>
            <!-- 限购数量 -->
            <el-form-item label="限购数量(张)" prop="purchaseLimitType">
              <el-radio-group v-model="voucherModel.purchaseLimitType" class="ml-4">
                <el-radio v-for="status in purchaseLimitList" :value="status.value" :key="status.value">
                  {{ status.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" prop="purchaseLimitCode" v-if="voucherModel.purchaseLimitType == 2">
              <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: "请输入代金券名称" }],
  price: [
    { required: true, message: "请输入抵扣价格" },
    {
      validator: validatePositiveNumber("抵扣价格必须为正数"),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === undefined || value === null || value === "") {
          callback();
          return;
        }
        const num = Number(value);
        if (isNaN(num) || num < 1) {
          callback(new Error("抵扣价格不能低于1元"));
          return;
        }
        callback();
      },
      trigger: "blur"
    },
    {
      validator: validatePriceFormat("整数部分最多6位，小数部分最多2位"),
      trigger: "blur"
    },
    {
      validator: validatePriceComparison(
        () => voucherModel.value.price,
        () => voucherModel.value.offprice,
        "抵扣价格不能低于售卖价格"
      ),
      trigger: "blur"
    }
  ],
  offprice: [
    { required: true, message: "请输入售卖价格" },
    {
      validator: validatePositiveNumber("售卖价格必须为正数"),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === undefined || value === null || value === "") {
          callback();
          return;
        }
        const num = Number(value);
        if (isNaN(num) || num < 1) {
          callback(new Error("售卖价格不能低于1元"));
          return;
        }
        callback();
      },
      trigger: "blur"
    },
    {
      validator: validatePriceFormat("整数部分最多6位，小数部分最多2位"),
      trigger: "blur"
    },
    {
      validator: validatePriceComparison(
        () => voucherModel.value.price,
        () => voucherModel.value.offprice,
        "抵扣价格不能低于售卖价格"
      ),
      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 == 1) {
          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 == 2) {
          if (!value || value.length !== 2) {
            callback(new Error("请选择指定时间段"));
            return;
          }
          validateDateRangeArray("开始时间必须早于结束时间", true, "时间不能早于当前时间")(rule, value, callback);
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  unusedType: [{ required: true, message: "请选择不可用日期类型" }],
  unavailableWeekdays: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.unusedType == 2) {
          const weekdays = voucherModel.value.unavailableWeekdays || [];
          const holidays = voucherModel.value.unavailableHolidays || [];
          if (weekdays.length === 0 && holidays.length === 0) {
            callback(new Error("至少需要选择一个星期或节日"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  unavailableHolidays: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.unusedType == 2) {
          const weekdays = voucherModel.value.unavailableWeekdays || [];
          const holidays = voucherModel.value.unavailableHolidays || [];
          if (weekdays.length === 0 && holidays.length === 0) {
            callback(new Error("至少需要选择一个星期或节日"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  customUnavailableDates: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.unusedType == 3) {
          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: [
    { required: true, message: "请输入库存数量" },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 先验证是否为正整数
        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"
    }
  ],
  singleCanUseType: [{ required: true, message: "请选择单日可用数量类型" }],
  singleCanUse: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.singleCanUseType == 2) {
          if (!value || value.toString().trim() === "") {
            callback(new Error("请输入单日可用数量"));
            return;
          }
          // 验证是否为正整数
          validatePositiveInteger("单日可用数量必须为正整数", { required: false })(rule, value, (error: any) => {
            if (error) {
              callback(error);
              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();
          });
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  purchaseLimitType: [{ required: true, message: "请选择限购数量类型" }],
  purchaseLimitCode: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (voucherModel.value.purchaseLimitType == 2) {
          if (!value || value.toString().trim() === "") {
            callback(new Error("请输入限购数量"));
            return;
          }
          // 验证是否为正整数
          validatePositiveInteger("限购数量必须为正整数", { required: false })(rule, value, (error: any) => {
            if (error) {
              callback(error);
              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();
          });
        } else {
          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: "",
  // 抵扣价格
  price: "",
  // 售卖价格
  offprice: "",
  // 开始售卖时间
  startDate: "",
  // 结束售卖时间
  endDate: "",
  // 使用时间 - 开始时间
  buyUseStartTime: "",
  // 使用时间 - 结束时间
  buyUseEndTime: "",
  // 使用时间（虚拟字段，用于表单验证）
  usageTime: null,
  // 有效期类型：1-指定天数，2-指定时间段内可用
  expirationType: "1",
  // 有效期天数（当expirationType为1时使用）
  expirationDate: 0,
  // 有效期时间段（当expirationType为2时使用）
  validityPeriod: [],
  // 不可用日期类型：1-全部日期可用，2-限制日期
  unusedType: "1",
  // 限制日期 - 星期选择（数组，存储选中的星期值）
  unavailableWeekdays: [],
  // 限制日期 - 节日选择（数组，存储选中的节日值）
  unavailableHolidays: [],
  // 自定义不可用日期列表（数组，每个元素是一个日期范围 [startDate, endDate]）
  disableDateList: [],
  // 库存
  singleQty: "",
  // 单日可用数量类型：1-不限制，2-限制
  singleCanUseType: "1",
  // 单日可用数量
  singleCanUse: "",
  // 限购数量类型：1-不限制，2-限制
  purchaseLimitType: "1",
  // 限购数量
  purchaseLimitCode: "",
  // 适用范围类型：0-全场通用，1-部分不可用
  applyType: "1",
  // 适用范围（当applyType为1时使用）
  applyDesc: "",
  // 补充说明
  supplement: ""
});

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

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

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

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

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

// 单日可用数量类型列表
const dailyUseLimitList = ref([
  { value: "1", label: "不限制" },
  { value: "2", label: "限制" }
]);

// 限购数量类型列表
const purchaseLimitList = 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([]);

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

// 初始化标志，用于防止初始化时触发验证
const isInitializing = ref(true);

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

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

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

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

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

/**
 * 监听单日可用数量类型变化
 * 当切换到"不限制"时，清空输入框的值
 */
watch(
  () => voucherModel.value.singleCanUseType,
  newVal => {
    if (newVal == 1) {
      voucherModel.value.singleCanUse = "";
      nextTick(() => {
        ruleFormRef.value?.clearValidate("singleCanUse");
      });
    }
  }
);

/**
 * 监听限购数量类型变化
 * 当切换到"不限制"时，清空输入框的值
 */
watch(
  () => voucherModel.value.purchaseLimitType,
  newVal => {
    if (newVal == 1) {
      voucherModel.value.purchaseLimitCode = "";
      nextTick(() => {
        ruleFormRef.value?.clearValidate("purchaseLimitCode");
      });
    }
  }
);

/**
 * 监听适用范围类型变化
 * 当切换到"全场通用"时，清空输入框的值
 */
watch(
  () => voucherModel.value.applyType,
  newVal => {
    if (newVal == 1) {
      voucherModel.value.applyDesc = "";
      nextTick(() => {
        ruleFormRef.value?.clearValidate("applyDesc");
      });
    }
  }
);

/**
 * 监听使用开始时间变化
 * 更新虚拟字段以支持表单验证
 */
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 == 3) {
      // 切换到自定义不可用日期时，如果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 == 2) {
      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 == 2) {
      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 === 3) {
      if (!voucherModel.value.disableDateList || voucherModel.value.disableDateList.length === 0) {
        voucherModel.value.disableDateList = [null];
      }
    }
    // 处理单日可用数量类型：如果有值，设置为"限制"，否则设置为"不限制"
    if (
      voucherModel.value.singleCanUse !== null &&
      voucherModel.value.singleCanUse !== undefined &&
      voucherModel.value.singleCanUse.toString().trim() !== ""
    ) {
      voucherModel.value.singleCanUseType = "2";
    } else {
      voucherModel.value.singleCanUseType = "1";
      voucherModel.value.singleCanUse = "";
    }
    // 处理限购数量类型：如果有值，设置为"限制"，否则设置为"不限制"
    if (
      voucherModel.value.purchaseLimitCode !== null &&
      voucherModel.value.purchaseLimitCode !== undefined &&
      voucherModel.value.purchaseLimitCode.toString().trim() !== ""
    ) {
      voucherModel.value.purchaseLimitType = "2";
    } else {
      voucherModel.value.purchaseLimitType = "1";
      voucherModel.value.purchaseLimitCode = "";
    }
    // 处理适用范围类型：如果有值，设置为"部分不可用"，否则设置为"全场通用"
    if (
      voucherModel.value.applyDesc !== null &&
      voucherModel.value.applyDesc !== undefined &&
      voucherModel.value.applyDesc.toString().trim() !== ""
    ) {
      voucherModel.value.applyType = "2";
    } else {
      voucherModel.value.applyType = "1";
      voucherModel.value.applyDesc = "";
    }
    console.log(voucherModel.value);
  }

  await nextTick();
  ruleFormRef.value?.clearValidate();
  isInitializing.value = false;
});

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

/**
 * 返回上一页
 */
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");
    ruleFormRef.value?.validateField("unavailableHolidays");
  });
};

/**
 * 切换节日选择
 * @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("unavailableWeekdays");
    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为2（指定时间段内可用）时才处理validityPeriod
  if (params.expirationType == 2 && params.validityPeriod && Array.isArray(params.validityPeriod)) {
    params.validityPeriod = params.validityPeriod.join(",");
  } else if (params.expirationType == 1) {
    // 指定天数模式，不需要validityPeriod字段
    params.validityPeriod = "";
  }
  // 处理不可用日期
  if (params.unusedType == 2) {
    // 对 unavailableWeekdays 按照 weekdayList 中的索引顺序排序
    if (params.unavailableWeekdays && params.unavailableWeekdays.length > 0) {
      params.unavailableWeekdays = params.unavailableWeekdays.sort((a: string, b: string) => {
        const indexA = weekdayList.value.findIndex(item => item.oName === a);
        const indexB = weekdayList.value.findIndex(item => item.oName === b);
        return indexA - indexB;
      });
    }
    // 对 unavailableHolidays 按照 holidayList 中的索引顺序排序
    if (params.unavailableHolidays && params.unavailableHolidays.length > 0) {
      params.unavailableHolidays = params.unavailableHolidays.sort((a: string | number, b: string | number) => {
        const indexA = holidayList.value.findIndex(item => String(item.id) === String(a));
        const indexB = holidayList.value.findIndex(item => String(item.id) === String(b));
        return indexA - indexB;
      });
    }
    // 节日名称 = 用 ID 到 holidayList 中映射
    const holidayNames = (params.unavailableHolidays || [])
      .map(id => {
        const hit = holidayList.value.find(item => item.id == id);
        return hit ? hit.festivalName : null;
      })
      .filter(Boolean);
    const holidayIds = (params.unavailableHolidays || [])
      .map(id => {
        const hit = holidayList.value.find(item => item.id == id);
        return hit ? hit.id : null;
      })
      .filter(Boolean);
    // 组装 unusedDate（星期名称 + 节日名称）并去重
    const unusedDate = [...new Set([...(params.unavailableWeekdays || []), ...holidayNames])];
    params.unusedDate = unusedDate.join(",");
    // // 保存选中的节日ID到 useFestival 字段
    params.useFestival = (params.unavailableHolidays || []).join(",");
    params.unavaiLableDate = params.unavailableWeekdays.join(",") + ";" + holidayIds.join(",");
  } else if (params.unusedType == 3) {
    // 处理自定义不可用日期
    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(";");
    }
  }
  // 处理单日可用数量：如果选择"不限制"，清空值
  if (params.singleCanUseType == 1) {
    params.singleCanUse = "";
  }
  // 处理限购数量：如果选择"不限制"，清空值
  if (params.purchaseLimitType == 1) {
    params.purchaseLimitCode = "";
  }
  params.dataType = submitType ? 1 : 0;
  // 是否可叠加 不知道有什么用 预留
  params.stackingType = 0;
  // 是否全场通用 不知道有什么用 预留
  params.generalType = 0;
  delete params.unavailableWeekdays;
  delete params.unavailableHolidays;
  delete params.disableDateList;
  delete params.singleCanUseType;
  delete params.purchaseLimitType;
  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>
