<template>
  <div class="business-hours-container">
    <h2 class="page-title">营业时间</h2>

    <!-- 正常营业时间 -->
    <div class="section">
      <h3 class="section-title">正常营业时间</h3>
      <div class="hours-list">
        <div v-for="(item, index) in normalHours" :key="index" class="hours-item">
          <span class="hours-text">{{ formatNormalHours(item) }}</span>
          <div class="action-buttons">
            <el-button type="primary" link @click="editNormalHours(index)"> 编辑 </el-button>
            <el-button type="primary" link @click="deleteNormalHours(index)"> 删除 </el-button>
          </div>
        </div>
      </div>
      <el-button type="primary" @click="openAddNormalDialog"> 添加正常营业时间 </el-button>
    </div>

    <!-- 特殊营业时间 -->
    <div class="section">
      <h3 class="section-title">特殊营业时间</h3>
      <div class="hours-list">
        <div v-for="(item, index) in specialHours" :key="index" class="hours-item">
          <span class="hours-text">{{ formatSpecialHours(item) }}</span>
          <div class="action-buttons">
            <el-button type="primary" link @click="editSpecialHours(index)"> 编辑 </el-button>
            <el-button type="primary" link @click="deleteSpecialHours(index)"> 删除 </el-button>
          </div>
        </div>
      </div>
      <el-button type="primary" @click="openAddSpecialDialog"> 添加特殊营业时间 </el-button>
    </div>

    <!-- 保存按钮 -->
    <div class="footer">
      <el-button type="primary" size="large" @click="handleSave"> 保存 </el-button>
    </div>

    <!-- 正常营业时间对话框 -->
    <el-dialog v-model="normalDialogVisible" :title="normalDialogTitle" width="600px" @close="resetNormalForm">
      <el-form :model="normalForm" label-width="140px">
        <el-form-item label="请选择营业日">
          <div class="day-buttons">
            <el-button
              v-for="day in weekDays"
              :key="day.value"
              :type="normalForm.selectedDays.includes(day.value) ? 'primary' : 'default'"
              @click="toggleDay(day.value)"
            >
              {{ day.label }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="请选择营业时间段">
          <el-radio-group v-model="normalForm.timeType">
            <el-radio :value="'custom'"> 自定义 </el-radio>
            <el-radio :value="'24hours'"> 24小时 </el-radio>
          </el-radio-group>
          <div v-if="normalForm.timeType === 'custom'" class="time-picker-group">
            <el-time-picker
              v-model="normalForm.startTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="开始时间"
              style="width: 150px"
            />
            <span class="time-separator">至</span>
            <el-time-picker
              v-model="normalForm.endTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="结束时间"
              style="width: 150px"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetNormalForm"> 重置 </el-button>
          <el-button type="primary" @click="confirmNormalHours"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 特殊营业时间对话框 -->
    <el-dialog v-model="specialDialogVisible" title="添加特殊营业时间" width="600px" @close="resetSpecialForm">
      <el-form :model="specialForm" label-width="140px">
        <el-form-item label="请选择营业日">
          <div class="holiday-buttons">
            <el-button
              v-for="holiday in holidays"
              :key="holiday.value"
              :type="specialForm.selectedHolidays.includes(holiday.value) ? 'primary' : 'default'"
              @click="toggleHoliday(holiday.value)"
            >
              {{ holiday.label }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="请选择营业时间段">
          <el-radio-group v-model="specialForm.timeType">
            <el-radio :value="'custom'"> 自定义 </el-radio>
            <el-radio :value="'24hours'"> 24小时 </el-radio>
          </el-radio-group>
          <div v-if="specialForm.timeType === 'custom'" class="time-picker-group">
            <el-time-picker
              v-model="specialForm.startTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="开始时间"
              style="width: 150px"
            />
            <span class="time-separator">至</span>
            <el-time-picker
              v-model="specialForm.endTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="结束时间"
              style="width: 150px"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetSpecialForm"> 重置 </el-button>
          <el-button type="primary" @click="confirmSpecialHours"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import { getBusinessTimeList, addOrEditBusinessTime } from "@/api/modules/storeDecoration";
import { localGet } from "@/utils";

// 周一到周日
const weekDays = [
  { label: "周一", value: 1 },
  { label: "周二", value: 2 },
  { label: "周三", value: 3 },
  { label: "周四", value: 4 },
  { label: "周五", value: 5 },
  { label: "周六", value: 6 },
  { label: "周日", value: 7 }
];

// 节假日列表
// TODO: 如果节假日列表需要从接口获取，请调用 getHolidayList API 并在 onMounted 中初始化
const holidays = ref([
  { label: "元旦", value: "元旦" },
  { label: "春节", value: "春节" },
  { label: "情人节", value: "情人节" },
  { label: "元宵节", value: "元宵节" },
  { label: "清明节", value: "清明节" },
  { label: "劳动节", value: "劳动节" },
  { label: "儿童节", value: "儿童节" },
  { label: "端午节", value: "端午节" },
  { label: "七夕", value: "七夕" },
  { label: "中秋节", value: "中秋节" },
  { label: "国庆节", value: "国庆节" },
  { label: "冬至", value: "冬至" },
  { label: "平安夜", value: "平安夜" },
  { label: "圣诞节", value: "圣诞节" }
]);

// 正常营业时间列表
interface NormalHoursItem {
  id?: number | null;
  days: number[];
  timeType: "custom" | "24hours";
  startTime?: string;
  endTime?: string;
}

const normalHours = ref<NormalHoursItem[]>([]);

// 特殊营业时间列表
interface SpecialHoursItem {
  id?: number | null;
  holidays: string[];
  timeType: "custom" | "24hours";
  startTime?: string;
  endTime?: string;
}

const specialHours = ref<SpecialHoursItem[]>([]);

// 正常营业时间对话框
const normalDialogVisible = ref(false);
const normalEditIndex = ref<number | null>(null);
const normalDialogTitle = computed(() => (normalEditIndex.value !== null ? "正常营业时间" : "正常营业时间"));

const normalForm = reactive({
  selectedDays: [] as number[],
  timeType: "custom" as "custom" | "24hours",
  startTime: "",
  endTime: ""
});

// 特殊营业时间对话框
const specialDialogVisible = ref(false);
const specialEditIndex = ref<number | null>(null);

const specialForm = reactive({
  selectedHolidays: [] as string[],
  timeType: "custom" as "custom" | "24hours",
  startTime: "",
  endTime: ""
});

// 格式化正常营业时间显示
const formatNormalHours = (item: NormalHoursItem) => {
  const sortedDays = [...item.days].sort((a, b) => a - b);

  // 如果是连续的天数，使用"至"连接
  let dayLabels = "";
  if (sortedDays.length === 7) {
    dayLabels = "周一至周日";
  } else if (sortedDays.length > 1 && sortedDays[sortedDays.length - 1] - sortedDays[0] === sortedDays.length - 1) {
    // 连续的天数
    const startDay = weekDays.find(d => d.value === sortedDays[0])?.label;
    const endDay = weekDays.find(d => d.value === sortedDays[sortedDays.length - 1])?.label;
    dayLabels = `${startDay}至${endDay}`;
  } else {
    // 不连续的天数，用顿号连接
    dayLabels = sortedDays.map(day => weekDays.find(d => d.value === day)?.label).join("、");
  }

  if (item.timeType === "24hours") {
    return `${dayLabels} 24小时`;
  }
  return `${dayLabels} ${item.startTime}-${item.endTime}`;
};

// 格式化特殊营业时间显示
const formatSpecialHours = (item: SpecialHoursItem) => {
  const holidayLabels = item.holidays.join("、");
  if (item.timeType === "24hours") {
    return `${holidayLabels} 24小时`;
  }
  return `${holidayLabels} ${item.startTime}-${item.endTime}`;
};

// 切换选择日期
const toggleDay = (day: number) => {
  const index = normalForm.selectedDays.indexOf(day);
  if (index > -1) {
    normalForm.selectedDays.splice(index, 1);
  } else {
    normalForm.selectedDays.push(day);
  }
};

// 切换选择节假日
const toggleHoliday = (holiday: string) => {
  const index = specialForm.selectedHolidays.indexOf(holiday);
  if (index > -1) {
    specialForm.selectedHolidays.splice(index, 1);
  } else {
    specialForm.selectedHolidays.push(holiday);
  }
};

// 打开添加正常营业时间对话框
const openAddNormalDialog = () => {
  // 检查是否已有正常营业时间（添加时检查，编辑时不检查）
  if (normalHours.value.length > 0) {
    ElMessage.warning("已有正常营业时间");
    return;
  }
  normalEditIndex.value = null;
  resetNormalForm();
  normalDialogVisible.value = true;
};

// 编辑正常营业时间
const editNormalHours = (index: number) => {
  normalEditIndex.value = index;
  const item = normalHours.value[index];
  normalForm.selectedDays = [...item.days];
  normalForm.timeType = item.timeType;
  // 如果是24小时模式，不设置时间；如果是自定义模式，设置时间
  if (item.timeType === "custom") {
    normalForm.startTime = item.startTime || "";
    normalForm.endTime = item.endTime || "";
  } else {
    normalForm.startTime = "";
    normalForm.endTime = "";
  }
  normalDialogVisible.value = true;
};

// 删除正常营业时间（删除逻辑：不在保存数组里的就是删除了）
const deleteNormalHours = (index: number) => {
  // 禁止删除最后一条
  if (normalHours.value.length <= 1) {
    ElMessage.warning("至少存在一条营业时间");
    return;
  }
  normalHours.value.splice(index, 1);
  ElMessage.success("删除成功");
};

// 重置正常营业时间表单
const resetNormalForm = () => {
  normalForm.selectedDays = [];
  normalForm.timeType = "custom";
  normalForm.startTime = "";
  normalForm.endTime = "";
  normalEditIndex.value = null;
};

// 确认正常营业时间
const confirmNormalHours = () => {
  if (normalForm.selectedDays.length === 0) {
    ElMessage.warning("请选择营业日");
    return;
  }
  if (normalForm.timeType === "custom" && (!normalForm.startTime || !normalForm.endTime)) {
    ElMessage.warning("请选择营业时间段");
    return;
  }

  const newItem: NormalHoursItem = {
    days: [...normalForm.selectedDays],
    timeType: normalForm.timeType,
    startTime: normalForm.timeType === "custom" ? normalForm.startTime : "00:00",
    endTime: normalForm.timeType === "custom" ? normalForm.endTime : "23:59"
  };

  if (normalEditIndex.value !== null) {
    // 编辑时保留id
    newItem.id = normalHours.value[normalEditIndex.value].id;
    normalHours.value[normalEditIndex.value] = newItem;
    ElMessage.success("编辑成功");
  } else {
    normalHours.value.push(newItem);
    ElMessage.success("添加成功");
  }

  normalDialogVisible.value = false;
  resetNormalForm();
};

// 打开添加特殊营业时间对话框
const openAddSpecialDialog = () => {
  // 检查是否已有5个特殊营业时间（添加时检查，编辑时不检查）
  if (specialHours.value.length >= 5) {
    ElMessage.warning("最多添加5个特殊营业时间");
    return;
  }
  specialEditIndex.value = null;
  resetSpecialForm();
  specialDialogVisible.value = true;
};

// 编辑特殊营业时间
const editSpecialHours = (index: number) => {
  specialEditIndex.value = index;
  const item = specialHours.value[index];
  specialForm.selectedHolidays = [...item.holidays];
  specialForm.timeType = item.timeType;
  // 如果是24小时模式，不设置时间；如果是自定义模式，设置时间
  if (item.timeType === "custom") {
    specialForm.startTime = item.startTime || "";
    specialForm.endTime = item.endTime || "";
  } else {
    specialForm.startTime = "";
    specialForm.endTime = "";
  }
  specialDialogVisible.value = true;
};

// 删除特殊营业时间（删除逻辑：不在保存数组里的就是删除了）
const deleteSpecialHours = (index: number) => {
  // 特殊营业时间可以全部删除，不需要限制
  specialHours.value.splice(index, 1);
  ElMessage.success("删除成功");
};

// 重置特殊营业时间表单
const resetSpecialForm = () => {
  specialForm.selectedHolidays = [];
  specialForm.timeType = "custom";
  specialForm.startTime = "";
  specialForm.endTime = "";
  specialEditIndex.value = null;
};

// 检查特殊营业时间日期是否重复
const checkDateDuplicate = (holidays: string[]): boolean => {
  // 过滤出其他特殊营业时间（排除当前编辑的项）
  const otherSpecialHours = specialHours.value.filter((item, index) => index !== specialEditIndex.value);

  // 检查新添加/编辑的特殊营业时间的日期是否与其他特殊营业时间的日期有重复
  for (let i = 0; i < otherSpecialHours.length; i++) {
    const item = otherSpecialHours[i];
    // 检查是否有任何节假日重复
    if (holidays.some(holiday => item.holidays.includes(holiday))) {
      return true;
    }
  }

  return false;
};

// 确认特殊营业时间
const confirmSpecialHours = () => {
  if (specialForm.selectedHolidays.length === 0) {
    ElMessage.warning("请选择营业日");
    return;
  }
  if (specialForm.timeType === "custom" && (!specialForm.startTime || !specialForm.endTime)) {
    ElMessage.warning("请选择营业时间段");
    return;
  }

  // 检查日期是否重复
  if (checkDateDuplicate(specialForm.selectedHolidays)) {
    ElMessage.warning("特殊营业时间的日期不能重复");
    return;
  }

  const newItem: SpecialHoursItem = {
    holidays: [...specialForm.selectedHolidays],
    timeType: specialForm.timeType,
    startTime: specialForm.timeType === "custom" ? specialForm.startTime : "00:00",
    endTime: specialForm.timeType === "custom" ? specialForm.endTime : "23:59"
  };

  if (specialEditIndex.value !== null) {
    // 编辑时保留id
    newItem.id = specialHours.value[specialEditIndex.value].id;
    specialHours.value[specialEditIndex.value] = newItem;
    ElMessage.success("编辑成功");
  } else {
    specialHours.value.push(newItem);
    ElMessage.success("添加成功");
  }

  specialDialogVisible.value = false;
  resetSpecialForm();
};

// 将接口数据转换为页面显示格式
const convertApiDataToDisplay = (apiData: any[]) => {
  const normalList: NormalHoursItem[] = [];
  const specialList: SpecialHoursItem[] = [];

  apiData.forEach((item: any) => {
    if (item.businessType === 1) {
      // 正常营业时间
      // 将businessDate字符串转换为days数组
      const businessDate = item.businessDate || "";
      const dayLabels = businessDate.split("、");
      const days: number[] = [];
      dayLabels.forEach((label: string) => {
        const day = weekDays.find(d => d.label === label.trim());
        if (day) {
          days.push(day.value);
        }
      });

      // 判断是否为24小时：startTime为00:00且endTime为23:59或02:00（跨天情况）
      const is24Hours = item.startTime === "00:00" && (item.endTime === "23:59" || item.endTime === "02:00");

      normalList.push({
        id: item.id,
        days: days,
        timeType: is24Hours ? "24hours" : "custom",
        startTime: is24Hours ? undefined : item.startTime,
        endTime: is24Hours ? undefined : item.endTime
      });
    } else if (item.businessType === 2) {
      // 特殊营业时间
      // 将businessDate字符串转换为holidays数组
      const businessDate = item.businessDate || "";
      const holidayLabels = businessDate.split("、").map((h: string) => h.trim());

      // 判断是否为24小时
      const is24Hours = item.startTime === "00:00" && (item.endTime === "23:59" || item.endTime === "02:00");

      specialList.push({
        id: item.id,
        holidays: holidayLabels,
        timeType: is24Hours ? "24hours" : "custom",
        startTime: is24Hours ? undefined : item.startTime,
        endTime: is24Hours ? undefined : item.endTime
      });
    }
  });

  return { normalList, specialList };
};

// 获取营业时间数据
const getBusinessTimeData = async () => {
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      console.warn("未找到店铺ID");
      return;
    }

    const res: any = await getBusinessTimeList({ storeId: Number(storeId) });
    if (res && (res.code === 200 || res.code === "200") && res.data) {
      const dataList = Array.isArray(res.data) ? res.data : res.data.list || [];
      const { normalList, specialList } = convertApiDataToDisplay(dataList);
      normalHours.value = normalList;
      specialHours.value = specialList;
    }
  } catch (error) {
    console.error("获取营业时间失败:", error);
  }
};

// 页面初始化时获取数据
onMounted(async () => {
  await getBusinessTimeData();
});

// 将页面数据转换为接口格式
const convertDisplayDataToApi = () => {
  const apiDataList: any[] = [];
  const userInfo: any = localGet("geeker-user")?.userInfo || {};
  const storeId = userInfo.storeId;

  // 转换正常营业时间
  normalHours.value.forEach(item => {
    // 将days数组转换为businessDate字符串
    const sortedDays = [...item.days].sort((a, b) => a - b);
    const dayLabels = sortedDays.map(day => weekDays.find(d => d.value === day)?.label).filter(Boolean);
    const businessDate = dayLabels.join("、");

    // 处理24小时：设置为00:00到23:59
    const startTime = item.timeType === "24hours" ? "00:00" : item.startTime || "00:00";
    const endTime = item.timeType === "24hours" ? "23:59" : item.endTime || "23:59";

    apiDataList.push({
      // id: item.id || 0,
      storeId: Number(storeId),
      businessType: 1,
      businessDate: businessDate,
      startTime: startTime,
      endTime: endTime,
      deleteFlag: 0,
      createdTime: "",
      createdUserId: 0,
      updatedTime: "",
      updatedUserId: 0
    });
  });

  // 转换特殊营业时间
  specialHours.value.forEach(item => {
    // 将holidays数组转换为businessDate字符串
    const businessDate = item.holidays.join("、");

    // 处理24小时：设置为00:00到23:59
    const startTime = item.timeType === "24hours" ? "00:00" : item.startTime || "00:00";
    const endTime = item.timeType === "24hours" ? "23:59" : item.endTime || "23:59";

    apiDataList.push({
      // id: item.id || 0,
      storeId: Number(storeId),
      businessType: 2,
      businessDate: businessDate,
      startTime: startTime,
      endTime: endTime,
      deleteFlag: 0,
      createdTime: "",
      createdUserId: 0,
      updatedTime: "",
      updatedUserId: 0
    });
  });

  return apiDataList;
};

// 保存
const handleSave = async () => {
  try {
    // 保存前检查：至少需要有一条正常营业时间
    if (normalHours.value.length === 0) {
      ElMessage.warning("至少存在一条营业时间");
      return;
    }

    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID，请先完成店铺信息填写");
      return;
    }

    // 转换为接口格式（包含所有正常营业时间和特殊营业时间）
    // 不在这个数组里的数据会被删除
    const apiDataList = convertDisplayDataToApi();

    // 批量保存（一次性提交整个数组）
    const result: any = await addOrEditBusinessTime(apiDataList);

    if (result && (result.code === 200 || result.code === "200")) {
      ElNotification({
        title: "保存成功",
        type: "success",
        duration: 3000
      });

      // 保存成功后重新获取数据，更新id
      await getBusinessTimeData();
    } else {
      ElMessage.error(result?.msg || "保存失败");
    }
  } catch (error: any) {
    console.error("保存失败:", error);
    ElMessage.error(error?.msg || "保存失败，请重试");
  }
};
</script>

<style scoped lang="scss">
.business-hours-container {
  min-height: 100%;
  padding: 20px;
  background-color: white;
  .page-title {
    margin-bottom: 24px;
    font-size: 18px;
    font-weight: bold;
    color: #000000;
  }
  .section {
    margin-bottom: 32px;
    .section-title {
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #000000;
    }
    .hours-list {
      margin-bottom: 16px;
      .hours-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        .hours-text {
          font-size: 14px;
          color: #000000;
        }
        .action-buttons {
          display: flex;
          gap: 8px;
        }
      }
    }
  }
  .footer {
    display: flex;
    justify-content: center;
    margin-top: 40px;
  }
}
.day-buttons,
.holiday-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  .el-button {
    margin: 0;
  }
}
.time-picker-group {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 12px;
  .time-separator {
    color: #606266;
  }
}
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
