<template>
  <el-dialog :title="form.id ? '编辑点单智能' : '添加点单智能'" width="600px" v-model="visible" @closed="onClosed">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <el-form-item label="模版名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入模版名称" :maxlength="20" style="width: 300px;"></el-input>
      </el-form-item>
      <el-form-item label="选择商品" prop="foods">
        <!-- <el-cascader v-model="goodsTypeCascaderValue" :options="goodsList" :props="cascaderProps"
          :show-all-levels="false" :max-collapse-tags="3" collapse-tags clearable style="width: 300px"
          @change="selectFoodsConfirm" placeholder="请选择商品"></el-cascader> -->
        <el-select v-model="form.foods" placeholder="请选择商品" style="width: 300px;">
          <el-option v-for="item in allGoods" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="自定义引导语" prop="guideDetail">
        <el-input v-model="form.guideDetail" placeholder="请输入自定义引导语" :maxlength="12" style="width: 300px;"></el-input>
      </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="useTimeScope">
        <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>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false;">取 消</el-button>
        <el-button type="primary" @click="handleOk" :loading="confirmLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import dayjs from "dayjs";
import { ref, onMounted } from "vue";
import { suggestPostPut, getProductList, getCategoryList } from "@/api/coupon/index.js";

const visible = ref(false);
const confirmLoading = ref(false);
const formRef = ref(null);
const shopInfo = ref(JSON.parse(localStorage.getItem("userInfo")) || {});

const form = ref({
  id: '',
  shopId: '',
  title: '',
  foods: '',
  guideDetail: '',
  useDays: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
  useTimeType: 'all',
  useStartTime: '',
  useEndTime: '',
});

const resetForm = ref('')

const rules = ref({
  title: [
    { required: true, message: "请输入模版名称", trigger: "blur" },
  ],
  foods: [
    { required: true, message: "请选择商品", trigger: "change" },
  ],
  useDays: [{ required: true, message: "可用周期", trigger: "change" }],
  guideDetail: [
    { required: true, message: "请输入自定义引导语", trigger: "blur" },
  ],
  useTimeScope: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (useTimeScope.value.length == 0) {
          callback(new Error('请选择指定时间段'))
        } else {
          callback()
        }
      },
      trigger: "change",
    },
  ],
})

// 可用时间
const useTimeScope = ref([]);
function useTimeScopeChange(e) {
  if (e && e.length) {
    form.value.useStartTime = dayjs(e[0]).format("HH:mm:ss");
    form.value.useEndTime = dayjs(e[1]).format("HH:mm:ss");
  } else {
    form.value.useStartTime = "";
    form.value.useEndTime = "";
  }
}

// 获取商品列表
const cascaderProps = ref({
  multiple: true,
  emitPath: false,
  value: "id",
  label: "name",
});
const goodsList = ref([]);
const allGoods = ref([]);
async function getProductListAjax() {
  try {
    const categorys = await getCategoryList();
    const products = await getProductList();
    allGoods.value = products;

    console.log(allGoods.value);

    goodsList.value = formatCategoryWithProducts(categorys, products);
  } catch (err) {
    console.log(err);
  }
}

// 给分类组合相应的商品
function formatCategoryWithProducts(categories, products) {
  // 步骤1：遍历所有分类，为每个分类匹配对应的商品
  const allCategoriesWithProducts = categories.map((category) => {
    // 匹配当前分类下的商品（通过category.id === product.categoryId关联）
    const matchedProducts = products
      .filter((product) => product.categoryId === category.id) // 关键：按分类ID匹配商品
      .map((product) => ({
        id: product.id,
        name: product.name, // 提取商品的id和name
      }));

    // 组装单个分类的结构
    return {
      id: category.id,
      name: category.name,
      children: matchedProducts, // 该分类下的商品（空数组表示无商品）
    };
  });

  // 步骤2：过滤掉“无商品”的分类（children为空数组的分类）
  return allCategoriesWithProducts.filter((item) => item.children.length > 0);
}

// 选择指定商品
const goodsTypeCascaderValue = ref([]);
function selectFoodsConfirm(e) {
  console.log(JSON.stringify(e));
  form.value.foods = e.join(",");
}

// 开始提交
const emit = defineEmits(['success']);
const handleOk = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        confirmLoading.value = true;
        const data = { ...form.value };
        data.shopId = shopInfo.value.shopId;
        data.useDays = form.value.useDays.join(",");
        await suggestPostPut(data, form.value.id ? 'put' : 'post');
        emit('success');
        visible.value = false;
      } catch (error) {
        console.log('error', error);
      }
      setTimeout(() => {
        confirmLoading.value = false;
      }, 500);
    }
  });
};

// 弹窗关闭后
const onClosed = () => {
  visible.value = false;
  form.value = { ...resetForm.value };
  formRef.value.resetFields()
};

function show(obj) {
  visible.value = true;
  console.log(obj);
  if (obj && obj.id) {
    form.value = { ...obj };
    form.value.useDays = obj.useDays ? obj.useDays.split(",") : [];

    if (form.value.useTimeType == "custom") {
      useTimeScope.value = [
        convertTimeToDate(form.value.useStartTime),
        convertTimeToDate(form.value.useEndTime),
      ];

      console.log(useTimeScope.value);
    }
  } else {
    form.value = { ...resetForm.value };
  }
}


/**
 * 将时分秒字符串转换为完整日期格式
 * @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);
}

defineExpose({
  show,
});

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

<style scoped lang="scss"></style>