<template>
  <el-dialog v-model="dialogVisible" :title="titleOptions.title" width="80%" top="4vh" @closed="closedReset">
    <div class="scroll" ref="scrollRef">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="160px" class="dialog-form">
        <el-form-item label="满减优惠" prop="thresholds">
          <div class="thresholds_list">
            <div class="item" v-for="(item, index) in form.thresholds" :key="index">
              <div class="ipt">
                <el-input v-model.trim="item.fullAmount" input-style="text-align: center;">
                  <template #prepend>满</template>
                  <template #append>元</template>
                </el-input>
              </div>
              <div class="ipt">
                <el-input v-model.trim="item.discountAmount" input-style="text-align: center;">
                  <template #prepend>减</template>
                  <template #append>元</template>
                </el-input>
              </div>
              <el-button link type="danger" v-if="index > 0" @click="form.thresholds.splice(index, 1)">删除</el-button>
            </div>
            <div class="item">
              <el-button type="primary" icon="CirclePlus" @click="addThresholdsObjHandle">添加</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="活动日期" prop="validDays">
          <div style="width: 300px;">
            <el-date-picker v-model="validityScope" type="daterange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" @change="validityScopeChange" />
          </div>
        </el-form-item>
        <el-form-item label="可用周期" prop="useDays">
          <el-checkbox-group v-model="form.useDays">
            <el-checkbox value="周一" label="周一" />
            <el-checkbox value="周二" label="周二" />
            <el-checkbox value="周三" label="周三" />
            <el-checkbox value="周四" label="周四" />
            <el-checkbox value="周五" label="周五" />
            <el-checkbox value="周六" label="周六" />
            <el-checkbox value="周日" label="周日" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="指定时间段">
          <el-radio-group v-model="form.useTimeType">
            <el-radio label="全时段可用" value="all"></el-radio>
            <el-radio label="指定时间段可用" value="custom"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.useTimeType == 'custom'" prop="useTimeType">
          <div style="width: 200px">
            <el-time-picker v-model="useTimeScope" is-range range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" @change="useTimeScopeChange" />
          </div>
        </el-form-item>
        <el-form-item label="可使用类型" prop="useType">
          <el-checkbox-group v-model="form.useType">
            <el-checkbox value="dine-in" label="堂食" />
            <el-checkbox value="take-out" label="外带" />
            <el-checkbox value="take-away" label="外卖" />
            <el-checkbox value="post" label="配送" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排序">
          <div class="column">
            <div>
              <el-input v-model="form.sort" placeholder="默认值：0" @input="e => form.sort = filterNumberInput(e, true)"
                style="width: 200px;"></el-input>
            </div>
            <div style="color: #FF2F2F;font-size: 12px;">数值越大，排序越靠前。重复时段下，按照排序值最高的活动减免</div>
          </div>
        </el-form-item>
        <el-form-item label="与优惠券同享">
          <div class="column">
            <div class="center">
              <el-switch disabled v-model="form.couponShare" :active-value="1" :inactive-value="0" />
              <span>不能和优惠券同时使用</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="与限时折扣同享">
          <div class="column">
            <div class="center">
              <el-switch v-model="form.discountShare" disabled :active-value="1" :inactive-value="0" />
              <span>计算门槛时将会按照折扣价计算</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="与会员价同享">
          <div class="column">
            <div class="center">
              <el-switch v-model="form.vipPriceShare" disabled :active-value="1" :inactive-value="0" />
              <span>计算门槛时将会按照会员价计算</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="与积分抵扣同享">
          <div class="column">
            <div class="center">
              <el-switch v-model="form.pointsShare" :active-value="1" :inactive-value="0" />
              <span>开启后，可和积分抵扣同时使用</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer" v-if="shopInfo.isHeadShop || shopInfo.shopType == 'only'">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitHandle">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import _ from "lodash";
import { dayjs } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { filterNumberInput } from "@/utils";
import { discountActivity } from "@/api/coupon/index.js";

const shopInfo = ref("");
const dialogVisible = ref(false);

const titleOptions = reactive({
  title: "添加优惠券"
});

// 有效期时间
const validityScope = ref([]);
function validityScopeChange(e) {
  console.log("validityScopeChange===", e);
  if (e && e.length) {
    form.value.validStartTime = dayjs(e[0]).format("YYYY-MM-DD");
    form.value.validEndTime = dayjs(e[1]).format("YYYY-MM-DD");
  } else {
    form.value.validStartTime = "";
    form.value.validEndTime = "";
  }
}
// 可用时间
const useTimeScope = ref([]);
function useTimeScopeChange(e) {
  console.log("useTimeScopeChange===", e);
  if (e && e.length) {
    form.value.useStartTime = dayjs(e[0]).format("HH:mm");
    form.value.useEndTime = dayjs(e[1]).format("HH:mm");
  } else {
    form.value.useStartTime = "";
    form.value.useEndTime = "";
  }
}

const formRef = ref(null);
const addThresholdsObj = ref({
  fullAmount: '', // 满多少金额
  discountAmount: '' // 减多少金额
})

const form = ref({
  id: '',
  shopId: '',
  validStartTime: '',
  validEndTime: '',
  useDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  useTimeType: 'all',
  useStartTime: '',
  useEndTime: '',
  useType: ['dine-in', 'take-out'],
  sort: '',
  couponShare: '',
  discountShare: 1,
  vipPriceShare: 1,
  pointsShare: 1,
  status: 1, // 状态：1未开始，2进行中，3已结束
  thresholds: [
    { ...addThresholdsObj.value }
  ]
});

// 添加
function addThresholdsObjHandle() {
  form.value.thresholds.push({ ...addThresholdsObj.value })
}

// 初始化
const resetForm = ref(null);
function reset() {
  validityScope.value = [];
  useTimeScope.value = [];
  form.value = { ...resetForm.value };
}

// 自定义校验固定有效期范围内可用
const useTimeTypeValidate = (rule, value, callback) => {
  if (!form.value.useStartTime) {
    callback(new Error("请选择指定可用时间段"));
  } else {
    callback();
  }
};

// 验证满减规则数组的函数
function validateDiscountRules(rules) {
  console.log(rules);


  // 检查是否为空数组
  if (!rules || rules.length === 0) {
    return { valid: false, message: '请添加满减规则' };
  }

  // 遍历每个规则进行验证
  for (let i = 0; i < rules.length; i++) {
    const rule = rules[i];
    const index = i + 1; // 显示给用户的序号（从1开始）

    // 检查fullAmount是否填写
    if (!rule.fullAmount) {
      return {
        valid: false,
        message: `第${index}条规则：请填写满减金额`
      };
    }

    // 检查discountAmount是否填写
    if (!rule.discountAmount) {
      return {
        valid: false,
        message: `第${index}条规则：请填写减免金额`
      };
    }

    // 转换为数字进行比较
    const full = Number(rule.fullAmount);
    const discount = Number(rule.discountAmount);

    // 检查是否为有效数字
    if (isNaN(full) || full <= 0) {
      return {
        valid: false,
        message: `第${index}条规则：满减金额必须是有效的正数`
      };
    }

    if (isNaN(discount) || discount <= 0) {
      return {
        valid: false,
        message: `第${index}条规则：减免金额必须是有效的正数`
      };
    }

    // 检查减免金额是否大于满减金额
    if (discount > full) {
      return {
        valid: false,
        message: `第${index}条规则：减免金额不能大于满减金额`
      };
    }
  }

  // 所有规则都通过验证
  return { valid: true };
}

const formRules = reactive({
  thresholds: [{
    required: true,
    validator: (rule, value, callback) => {
      let result = validateDiscountRules(form.value.thresholds)
      if (!result.valid) {
        callback(result.message)
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  validDays: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (validityScope.value.length == 0) {
          callback(new Error("请选择日期范围"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  useDays: [{ required: true, message: "请选择可用周期", trigger: "change" }],
  useTimeType: [
    {
      validator: useTimeTypeValidate,
      trigger: "change",
    },
  ],
});

// 开始提交
const emits = defineEmits(["success"]);
const loading = ref(false);
function submitHandle() {
  formRef.value.validate(async (valid) => {
    try {
      if (valid) {
        loading.value = true;

        let data = { ...form.value }
        data.useDays = data.useDays.join(',')
        data.useType = data.useType.join(',')

        await discountActivity(data, data.id ? 'put' : 'post');
        emits("success");
        dialogVisible.value = false;
      }
    } catch (err) {
      console.log(err);
    }
    loading.value = false;
  });
}

// 从本地获取商户信息
function getLocalShopInfo() {
  shopInfo.value = JSON.parse(localStorage.getItem("userInfo"));
}

// 显示弹窗
const scrollRef = ref(null);
function show(obj = null) {
  nextTick(() => {
    if (scrollRef.value) {
      setTimeout(() => {
        scrollRef.value.scrollTop = 0;
      }, 50);
    }
  });
  if (obj && obj.id) {
    titleOptions.title = `编辑满减活动`;

    form.value = { ...obj };


    form.value.useDays = form.value.useDays.split(',');
    form.value.useType = form.value.useType.split(',');

    if (form.value.useTimeType == "custom") {
      useTimeScope.value = [
        convertTimeToDate(`${form.value.useStartTime}:00`),
        convertTimeToDate(`${form.value.useEndTime}:00`),
      ];

      console.log(useTimeScope.value);
    }

    validityScope.value = [form.value.validStartTime, form.value.validEndTime]
  } else {
    reset();
    titleOptions.title = `添加满减活动`;
  }
  dialogVisible.value = true;
}

// 关闭后重置表单验证
function closedReset() {
  formRef.value.resetFields();
}

/**
 * 将时分秒字符串转换为完整日期格式
 * @param {string} timeStr - 时分秒字符串，格式需为 HH:mm:ss（如 '00:53:00'）
 * @param {Object} options - 可选配置项
 * @param {string} [options.customDate] - 自定义日期，格式为 YYYY-MM-DD（默认使用当前日期）
 * @param {string} [options.format='YYYY-MM-DD HH:mm:ss'] - 输出的日期格式
 * @returns {string|null} 转换后的日期字符串，失败时返回 null
 */
function convertTimeToDate(timeStr, options = {}) {
  // 解构配置项，设置默认值
  const { customDate, format = "YYYY-MM-DD HH:mm:ss" } = options;

  // 1. 校验时分秒格式（必须为 HH:mm:ss，允许数字1-2位）
  const timeRegex = /^\d{1,2}:\d{1,2}:\d{1,2}$/;
  if (!timeRegex.test(timeStr)) {
    console.error("时分秒格式错误，请使用 HH:mm:ss 格式（如 00:53:00）");
    return null;
  }

  // 2. 确定日期部分（自定义日期或当前日期）
  let datePart;
  if (customDate) {
    // 校验自定义日期格式
    if (!dayjs(customDate, "YYYY-MM-DD", true).isValid()) {
      console.error("自定义日期格式错误，请使用 YYYY-MM-DD 格式（如 2024-05-20）");
      return null;
    }
    datePart = customDate;
  } else {
    // 使用当前日期（格式：YYYY-MM-DD）
    datePart = dayjs().format("YYYY-MM-DD");
  }

  // 3. 组合日期和时分秒，生成完整日期对象
  const fullDateTime = `${datePart} ${timeStr}`;
  const dateObj = dayjs(fullDateTime);

  // 4. 校验完整日期是否有效（如避免 2024-02-30 这种无效日期）
  if (!dateObj.isValid()) {
    console.error("生成的日期无效，请检查日期或时分秒是否合理");
    return null;
  }

  // 5. 按指定格式返回日期字符串
  return dateObj.format(format);
}

// input过滤
const time = 500;
const discountNumInput = _.debounce(function (value) {
  form.value.discountNum = filterNumberInput(value, 1);
  if (form.value.discountNum == "") {
    form.value.discountNum = 1;
  }
}, time);

defineExpose({
  show,
});

onMounted(() => {
  resetForm.value = { ...form.value };
  getLocalShopInfo();
});
</script>

<style scoped lang="scss">
.title {
  color: #000;
  padding: 14px;
  background-color: #f8f8f8;
  margin-bottom: 14px;
  font-size: 16px;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;

  .item {
    flex: 1;
  }
}

.center {
  display: flex;
  align-items: center;
  gap: 10px;
}

.scroll {
  height: 76vh;
  padding-bottom: 60px;
  overflow-y: auto;
}

.dialog-footer {
  position: relative;

  &::after {
    content: "";
    width: 100%;
    height: 60px;
    position: absolute;
    left: 0;
    bottom: calc(100% + var(--el-dialog-padding-primary));
    z-index: 9;
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
  }
}

.textarea-num {
  color: #999;
  display: flex;
  justify-content: flex-end;
}

.thresholds_list {
  .item {
    display: flex;
    gap: 14px;

    &:not(:first-child) {
      margin-top: 14px;
    }

    .ipt {
      width: 200px;
    }
  }
}
</style>
