<template>
  <div class="store-info-container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="store-form">
      <div class="form-content">
        <!-- 左侧列 -->
        <div class="form-left">
          <!-- 店铺名称 -->
          <el-form-item label="店铺名称" prop="storeName">
            <el-input v-model="formData.storeName" placeholder="请输入店铺名称" clearable maxlength="50" />
          </el-form-item>

          <!-- 容纳人数 -->
          <el-form-item label="容纳人数" prop="storeCapacity">
            <el-input-number v-model="formData.storeCapacity" :min="1" :max="10000" style="width: 100%" />
          </el-form-item>

          <!-- 门店电话 -->
          <el-form-item label="门店电话" prop="storeTel">
            <el-input v-model="formData.storeTel" placeholder="请输入门店电话" clearable maxlength="20" />
          </el-form-item>

          <!-- 门店面积 -->
          <el-form-item label="门店面积" prop="storeArea">
            <el-radio-group v-model="formData.storeArea">
              <el-radio :value="1"> 小于20平米 </el-radio>
              <el-radio :value="2"> 20-50平米 </el-radio>
              <el-radio :value="3"> 50-100平米 </el-radio>
              <el-radio :value="4"> 100-300平米 </el-radio>
              <el-radio :value="5"> 300-500平米 </el-radio>
              <el-radio :value="6"> 500-1000平米 </el-radio>
              <el-radio :value="7"> 大于1000平米 </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 营业状态 -->
          <el-form-item label="营业状态" prop="businessStatus">
            <el-radio-group v-model="formData.businessStatus">
              <div class="radio-item">
                <el-radio :value="0">
                  <span class="radio-label">正常营业</span>
                </el-radio>
                <div class="radio-desc">门店正常开放,能够为顾客提供服务</div>
              </div>
              <div class="radio-item">
                <el-radio :value="1">
                  <span class="radio-label">暂停营业</span>
                </el-radio>
                <div class="radio-desc">门店因节假日、装修等原因,短期内止营业,预计一段时问后可恢复营业</div>
              </div>
              <div class="radio-item">
                <el-radio :value="2">
                  <span class="radio-label">筹建中</span>
                </el-radio>
                <div class="radio-desc">门店正在筹备阶段,暂时不能提供服务,完成准备后可以证实为顾客提供服务</div>
              </div>
              <div class="radio-item">
                <el-radio :value="99">
                  <span class="radio-label">永久关门</span>
                </el-radio>
                <div class="radio-desc">门店已经关门、转让或搬迁,长时间没有回复营业的计划,无法提供服务</div>
              </div>
            </el-radio-group>
          </el-form-item>

          <!-- 所在地区 -->
          <el-form-item label="所在地区" required>
            <div class="region-selector">
              <el-select
                v-model="formData.administrativeRegionProvinceAdcode"
                placeholder="请选择省"
                clearable
                style="width: 33.33%"
                @change="handleProvinceChange"
              >
                <el-option
                  v-for="province in provinceOptions"
                  :key="province.adcode"
                  :label="province.name"
                  :value="province.adcode"
                />
              </el-select>
              <el-select
                v-model="formData.administrativeRegionCityAdcode"
                placeholder="请选择市"
                clearable
                style="width: 33.33%"
                :disabled="!formData.administrativeRegionProvinceAdcode"
                @change="handleCityChange"
              >
                <el-option v-for="city in cityOptions" :key="city.adcode" :label="city.name" :value="city.adcode" />
              </el-select>
              <el-select
                v-model="formData.administrativeRegionDistrictAdcode"
                placeholder="请选择区"
                clearable
                style="width: 33.33%"
                :disabled="!formData.administrativeRegionCityAdcode"
              >
                <el-option
                  v-for="district in districtOptions"
                  :key="district.adcode"
                  :label="district.name"
                  :value="district.adcode"
                />
              </el-select>
            </div>
          </el-form-item>

          <!-- 详细地址 -->
          <el-form-item label="详细地址" prop="storeAddress">
            <el-input
              v-model="formData.storeAddress"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 右侧列 -->
        <div class="form-right">
          <!-- 门店简介 -->
          <el-form-item label="门店简介" prop="storeBlurb">
            <el-input
              v-model="formData.storeBlurb"
              type="textarea"
              :rows="4"
              placeholder="请输入门店简介"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          <!-- 经纬度查询 -->
          <!-- <el-form-item label="经纬度查询" prop="address">
            <el-select
              v-model="formData.storePosition"
              filterable
              placeholder="请输入地址进行查询"
              remote
              reserve-keyword
              :remote-method="getLonAndLat"
              @change="selectAddress"
            >
              <el-option v-for="item in addressList" :key="item.id" :label="item.name" :value="item.location">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">{{ item.district }}</span>
              </el-option>
            </el-select>
          </el-form-item> -->
          <!-- 经纬度展示 -->
          <el-form-item label="经纬度展示">
            <el-input v-model="formData.storePosition" disabled class="readonly-input">
              <template #prefix>
                <el-icon>
                  <Lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <!-- 店铺评价 -->
          <el-form-item label="店铺评价" prop="storeEvaluate">
            <el-input v-model="storeEvaluate1" type="text" :rows="1" placeholder="请输入评价1" show-word-limit />
            <el-input
              style="margin: 10px 0"
              v-model="storeEvaluate2"
              type="text"
              :rows="1"
              placeholder="请输入评价2"
              show-word-limit
            />
            <el-input v-model="storeEvaluate3" type="text" :rows="1" placeholder="请输入评价3" show-word-limit />
          </el-form-item>
          <!-- 经营板块 -->
          <el-form-item label="经营板块" prop="businessSection">
            <el-radio-group v-model="formData.businessSection" class="business-section-radio-group" disabled>
              <div v-for="section in businessSectionList" :key="section.dictId" class="businessSection-item">
                <el-radio :value="section.dictId" :label="section.dictDetail">
                  {{ section.dictDetail }}
                </el-radio>
              </div>
            </el-radio-group>
          </el-form-item>

          <!-- 标签选择（仅当经营板块为生活服务时显示） -->
          <el-form-item v-if="formData.businessSection === 3" label="标签选择" prop="storeTickets" required>
            <el-radio-group v-model="formData.storeTickets" disabled>
              <el-radio :value="1"> 装修公司 </el-radio>
              <el-radio :value="0"> 其他 </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 经营种类 -->
          <el-form-item label="经营种类" prop="businessTypeName">
            <el-input v-model="formData.businessTypeName" placeholder="请输入经营种类" clearable maxlength="50" />
          </el-form-item>

          <!-- 经营类目 -->
          <el-form-item label="经营类目" prop="businessCategoryName">
            <el-input v-model="formData.businessCategoryName" placeholder="请输入经营类目" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="预定服务" prop="bookingService">
            <el-radio-group v-model="formData.bookingService">
              <el-radio :value="1"> 提供 </el-radio>
              <el-radio :value="0"> 不提供 </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="营业时间">
            <div style="color: #6c8ff8; cursor: pointer" @click="handleViewBusinessHours">查看</div>
          </el-form-item>
          <!-- 到期时间（只读） -->
          <!--          <el-form-item label="到期时间">-->
          <!--            <el-input v-model="formData.expirationTime" disabled class="readonly-input">-->
          <!--              <template #prefix>-->
          <!--                <el-icon>-->
          <!--                  <Lock />-->
          <!--                </el-icon>-->
          <!--              </template>-->
          <!--            </el-input>-->
          <!--          </el-form-item>-->

          <!--          &lt;!&ndash; 食品经营许可证到期时间（只读） &ndash;&gt;-->
          <!--          <el-form-item label="食品经营许可证到期时间">-->
          <!--            <el-input v-model="formData.foodLicenceExpirationTime" disabled class="readonly-input">-->
          <!--              <template #prefix>-->
          <!--                <el-icon>-->
          <!--                  <Lock />-->
          <!--                </el-icon>-->
          <!--              </template>-->
          <!--            </el-input>-->
          <!--          </el-form-item>-->
        </div>
      </div>

      <!-- 保存按钮 -->
      <div class="form-footer">
        <el-button type="primary" size="large" :loading="loading" @click="handleSubmit"> 保存 </el-button>
      </div>
    </el-form>
    <!-- 营业时间弹窗（查看/编辑） -->
    <el-dialog
      v-model="businessHoursDialogVisible"
      title="营业时间"
      width="560px"
      destroy-on-close
      append-to-body
      @open="onBusinessHoursDialogOpen"
    >
      <p class="business-hours-tip">
        特殊营业时间适用于特殊日期(如:春节/国庆/其他指定日期)，设置成功后会在指定日期调整前台营业时间时显示
      </p>
      <div v-if="businessHoursDisplayList.length > 0" class="business-hours-list">
        <div v-for="(item, index) in businessHoursDisplayList" :key="item.key" class="business-hours-item">
          <div class="business-hours-item-header">
            <span class="item-title">{{ item.title }}</span>
            <el-tag :type="item.businessType === 1 ? 'success' : 'danger'" size="small">
              {{ item.businessType === 1 ? "正常" : "特殊" }}
            </el-tag>
          </div>
          <div class="business-hours-item-time">
            {{ item.timeText }}
          </div>
          <div class="business-hours-item-actions">
            <el-button type="primary" link @click="handleEditBusinessHours(item, index)"> 编辑 </el-button>
            <el-button type="primary" link @click="handleDeleteBusinessHours(item, index)"> 删除 </el-button>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂未添加营业时间" :image-size="80" />
      <template #footer>
        <div class="business-hours-dialog-footer">
          <el-button @click="openAddNormalBusinessHours"> 添加正常营业时间 </el-button>
          <el-button @click="openAddSpecialBusinessHours"> 添加特殊营业时间 </el-button>
          <el-button type="primary" :loading="businessHoursSaving" @click="handleSaveBusinessHours"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加/编辑 正常营业时间 -->
    <el-dialog
      v-model="normalBusinessHoursDialogVisible"
      title="正常营业时间"
      width="500px"
      append-to-body
      @close="resetNormalBusinessHoursForm"
    >
      <el-form label-width="120px">
        <el-form-item label="请选择营业日">
          <div class="day-buttons">
            <el-button
              v-for="day in weekDays"
              :key="day.value"
              :type="normalBusinessHoursForm.selectedDays.includes(day.value) ? 'primary' : 'default'"
              @click="toggleNormalDay(day.value)"
            >
              {{ day.label }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="营业时间段">
          <el-radio-group v-model="normalBusinessHoursForm.timeType">
            <el-radio :value="'custom'"> 自定义 </el-radio>
            <el-radio :value="'24hours'"> 24小时 </el-radio>
          </el-radio-group>
          <div v-if="normalBusinessHoursForm.timeType === 'custom'" class="time-picker-row">
            <el-time-picker
              v-model="normalBusinessHoursForm.startTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="开始时间"
              style="width: 140px"
            />
            <span class="time-sep">至</span>
            <el-time-picker
              v-model="normalBusinessHoursForm.endTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="结束时间"
              style="width: 140px"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="normalBusinessHoursDialogVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="confirmNormalBusinessHours"> 确定 </el-button>
      </template>
    </el-dialog>
    <!-- 添加/编辑 特殊营业时间 -->
    <el-dialog
      v-model="specialBusinessHoursDialogVisible"
      title="特殊营业时间"
      width="500px"
      append-to-body
      @close="resetSpecialBusinessHoursForm"
    >
      <el-form label-width="120px">
        <el-form-item label="请选择营业日">
          <div class="day-buttons holiday-buttons">
            <el-button
              v-for="h in holidays"
              :key="h.value"
              :type="specialBusinessHoursForm.selectedHolidays.includes(h.value) ? 'primary' : 'default'"
              @click="toggleSpecialHoliday(h.value)"
            >
              {{ h.label }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="营业时间段">
          <el-radio-group v-model="specialBusinessHoursForm.timeType">
            <el-radio :value="'custom'"> 自定义 </el-radio>
            <el-radio :value="'24hours'"> 24小时 </el-radio>
          </el-radio-group>
          <div v-if="specialBusinessHoursForm.timeType === 'custom'" class="time-picker-row">
            <el-time-picker
              v-model="specialBusinessHoursForm.startTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="开始时间"
              style="width: 140px"
            />
            <span class="time-sep">至</span>
            <el-time-picker
              v-model="specialBusinessHoursForm.endTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="结束时间"
              style="width: 140px"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="specialBusinessHoursDialogVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="confirmSpecialBusinessHours"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import { ElMessage, ElNotification, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Search, Lock } from "@element-plus/icons-vue";
import {
  getDistrict,
  getStoreDetail,
  saveStoreInfo,
  editStoreInfo,
  getStoreInfoBusinessHours,
  addOrEditBusinessTime,
  getHolidayList
} from "@/api/modules/storeDecoration";
import { getInputPrompt } from "@/api/modules/newLoginApi";
import { useRoute } from "vue-router";
import { localGet } from "@/utils";

// ========== 营业时间弹窗（参考 1.vue + businessHours 页） ==========
const weekDays = [
  { label: "周一", value: 1 },
  { label: "周二", value: 2 },
  { label: "周三", value: 3 },
  { label: "周四", value: 4 },
  { label: "周五", value: 5 },
  { label: "周六", value: 6 },
  { label: "周日", value: 7 }
];
const holidays = ref<{ label: string; value: string }[]>([]);
const fetchHolidayList = async () => {
  try {
    let params = {
      year: new Date().getFullYear(),
      page: 1,
      size: 500,
      openFlag: 1,
      holidayName: ""
    };
    const res: any = await getHolidayList(params);
    const list = res?.data?.records ?? res?.data ?? (Array.isArray(res?.data) ? res.data : []);
    holidays.value = (Array.isArray(list) ? list : []).map((item: any) => ({
      label: item.festivalName ?? item.name ?? item.label ?? String(item.id ?? ""),
      value: item.festivalName ?? item.name ?? item.label ?? String(item.id ?? "")
    }));
  } catch {
    holidays.value = [];
  }
};
interface NormalHoursItem {
  id?: number | null;
  days: number[];
  timeType: "custom" | "24hours";
  startTime?: string;
  endTime?: string;
}
interface SpecialHoursItem {
  id?: number | null;
  holidays: string[];
  timeType: "custom" | "24hours";
  startTime?: string;
  endTime?: string;
  /** 接口返回的节日名称，用于回显 */
  festivalName?: string;
}
const businessHoursDialogVisible = ref(false);
const normalHours = ref<NormalHoursItem[]>([]);
const specialHours = ref<SpecialHoursItem[]>([]);
const businessHoursSaving = ref(false);

const formatTimeRange = (startTime?: string, endTime?: string) => {
  if (!startTime || !endTime) return "";
  if (endTime <= startTime) return `${startTime}-次日${endTime}`;
  return `${startTime}-${endTime}`;
};

const getBusinessHoursDisplayTitle = (item: NormalHoursItem | SpecialHoursItem, type: 1 | 2) => {
  if (type === 1) {
    const normal = item as NormalHoursItem;
    const sorted = [...normal.days].sort((a, b) => a - b);
    if (sorted.length === 7) return "全年";
    const labels = sorted.map(d => weekDays.find(w => w.value === d)?.label).filter(Boolean);
    return labels.join("、");
  }
  const special = item as SpecialHoursItem;
  return special.festivalName || special.holidays.join("、");
};

const getBusinessHoursTimeText = (item: NormalHoursItem | SpecialHoursItem) => {
  if (item.timeType === "24hours") return "24小时";
  const start = item.startTime || "00:00";
  const end = item.endTime || "00:00";
  return formatTimeRange(start, end);
};

const businessHoursDisplayList = computed(() => {
  const list: {
    key: string;
    title: string;
    businessType: 1 | 2;
    timeText: string;
    source: "normal" | "special";
    index: number;
  }[] = [];
  normalHours.value.forEach((item, i) => {
    list.push({
      key: `normal-${i}`,
      title: getBusinessHoursDisplayTitle(item, 1),
      businessType: 1,
      timeText: getBusinessHoursTimeText(item),
      source: "normal",
      index: i
    });
  });
  specialHours.value.forEach((item, i) => {
    list.push({
      key: `special-${i}`,
      title: getBusinessHoursDisplayTitle(item, 2),
      businessType: 2,
      timeText: getBusinessHoursTimeText(item),
      source: "special",
      index: i
    });
  });
  return list;
});

const convertApiDataToDisplay = (apiData: any[]) => {
  const normalList: NormalHoursItem[] = [];
  const specialList: SpecialHoursItem[] = [];
  apiData.forEach((item: any) => {
    if (item.businessType === 1) {
      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);
      });
      const is24Hours = item.startTime === "00:00" && (item.endTime === "23:59" || item.endTime === "02:00");
      normalList.push({
        id: item.id,
        days,
        timeType: is24Hours ? "24hours" : "custom",
        startTime: is24Hours ? undefined : item.startTime,
        endTime: is24Hours ? undefined : item.endTime
      });
    } else if (item.businessType === 2) {
      const businessDate = item.businessDate || "";
      const holidayLabels = businessDate.split("、").map((h: string) => h.trim());
      const is24Hours = item.startTime === "00:00" && (item.endTime === "23:59" || item.endTime === "02:00");
      const festivalName = item.festivalName ?? item.holidayInfo?.festivalName ?? "";
      specialList.push({
        id: item.id,
        holidays: holidayLabels,
        timeType: is24Hours ? "24hours" : "custom",
        startTime: is24Hours ? undefined : item.startTime,
        endTime: is24Hours ? undefined : item.endTime,
        festivalName: festivalName || undefined
      });
    }
  });
  return { normalList, specialList };
};

const convertDisplayDataToApi = () => {
  const apiDataList: any[] = [];
  const storeId = localGet("geeker-user")?.userInfo?.storeId || localGet("createdId");
  if (!storeId) return apiDataList;
  normalHours.value.forEach(item => {
    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("、");
    const startTime = item.timeType === "24hours" ? "00:00" : item.startTime || "00:00";
    const endTime = item.timeType === "24hours" ? "23:59" : item.endTime || "23:59";
    apiDataList.push({
      storeId: Number(storeId),
      businessType: 1,
      businessDate,
      startTime,
      endTime,
      deleteFlag: 0,
      createdTime: "",
      createdUserId: 0,
      updatedTime: "",
      updatedUserId: 0
    });
  });
  specialHours.value.forEach(item => {
    const businessDate = item.holidays.join("、");
    const startTime = item.timeType === "24hours" ? "00:00" : item.startTime || "00:00";
    const endTime = item.timeType === "24hours" ? "23:59" : item.endTime || "23:59";
    apiDataList.push({
      storeId: Number(storeId),
      businessType: 2,
      businessDate,
      startTime,
      endTime,
      deleteFlag: 0,
      createdTime: "",
      createdUserId: 0,
      updatedTime: "",
      updatedUserId: 0
    });
  });
  return apiDataList;
};

const handleViewBusinessHours = () => {
  businessHoursDialogVisible.value = true;
};

const onBusinessHoursDialogOpen = () => {
  fetchBusinessTimeList();
  fetchHolidayList();
};

const fetchBusinessTimeList = async () => {
  const storeId = localGet("geeker-user")?.userInfo?.storeId || localGet("createdId");
  if (!storeId) {
    ElMessage.warning("未找到店铺信息");
    return;
  }
  try {
    const res: any = await getStoreInfoBusinessHours({ id: storeId });
    const ok = res && (res.code === 200 || res.code === "200" || res.success) && res.data != null;
    if (ok) {
      const dataList = Array.isArray(res.data) ? res.data : res.data.list || [];
      const { normalList, specialList } = convertApiDataToDisplay(dataList);
      normalHours.value = normalList;
      specialHours.value = specialList;
    } else {
      normalHours.value = [];
      specialHours.value = [];
    }
  } catch {
    normalHours.value = [];
    specialHours.value = [];
  }
};

const normalBusinessHoursDialogVisible = ref(false);
const normalBusinessHoursEditIndex = ref<number | null>(null);
const normalBusinessHoursForm = reactive({
  selectedDays: [] as number[],
  timeType: "custom" as "custom" | "24hours",
  startTime: "",
  endTime: ""
});

const specialBusinessHoursDialogVisible = ref(false);
const specialBusinessHoursEditIndex = ref<number | null>(null);
const specialBusinessHoursForm = reactive({
  selectedHolidays: [] as string[],
  timeType: "custom" as "custom" | "24hours",
  startTime: "",
  endTime: ""
});

const resetNormalBusinessHoursForm = () => {
  normalBusinessHoursForm.selectedDays = [];
  normalBusinessHoursForm.timeType = "custom";
  normalBusinessHoursForm.startTime = "";
  normalBusinessHoursForm.endTime = "";
  normalBusinessHoursEditIndex.value = null;
};

const resetSpecialBusinessHoursForm = () => {
  specialBusinessHoursForm.selectedHolidays = [];
  specialBusinessHoursForm.timeType = "custom";
  specialBusinessHoursForm.startTime = "";
  specialBusinessHoursForm.endTime = "";
  specialBusinessHoursEditIndex.value = null;
};

const toggleNormalDay = (day: number) => {
  const idx = normalBusinessHoursForm.selectedDays.indexOf(day);
  if (idx > -1) normalBusinessHoursForm.selectedDays.splice(idx, 1);
  else normalBusinessHoursForm.selectedDays.push(day);
};

const toggleSpecialHoliday = (holiday: string) => {
  const idx = specialBusinessHoursForm.selectedHolidays.indexOf(holiday);
  if (idx > -1) specialBusinessHoursForm.selectedHolidays.splice(idx, 1);
  else specialBusinessHoursForm.selectedHolidays.push(holiday);
};

const openAddNormalBusinessHours = () => {
  if (normalHours.value.length > 0) {
    ElMessage.warning("已有正常营业时间");
    return;
  }
  normalBusinessHoursEditIndex.value = null;
  resetNormalBusinessHoursForm();
  normalBusinessHoursDialogVisible.value = true;
};

const openAddSpecialBusinessHours = () => {
  if (specialHours.value.length >= 5) {
    ElMessage.warning("最多添加5个特殊营业时间");
    return;
  }
  specialBusinessHoursEditIndex.value = null;
  resetSpecialBusinessHoursForm();
  specialBusinessHoursDialogVisible.value = true;
};

const handleEditBusinessHours = (row: { source: "normal" | "special"; index: number }, _listIndex: number) => {
  if (row.source === "normal") {
    const item = normalHours.value[row.index];
    normalBusinessHoursEditIndex.value = row.index;
    normalBusinessHoursForm.selectedDays = [...item.days];
    normalBusinessHoursForm.timeType = item.timeType;
    normalBusinessHoursForm.startTime = item.startTime || "";
    normalBusinessHoursForm.endTime = item.endTime || "";
    normalBusinessHoursDialogVisible.value = true;
  } else {
    const item = specialHours.value[row.index];
    specialBusinessHoursEditIndex.value = row.index;
    specialBusinessHoursForm.selectedHolidays = [...item.holidays];
    specialBusinessHoursForm.timeType = item.timeType;
    specialBusinessHoursForm.startTime = item.startTime || "";
    specialBusinessHoursForm.endTime = item.endTime || "";
    specialBusinessHoursDialogVisible.value = true;
  }
};

const confirmNormalBusinessHours = () => {
  if (normalBusinessHoursForm.selectedDays.length === 0) {
    ElMessage.warning("请选择营业日");
    return;
  }
  if (normalBusinessHoursForm.timeType === "custom" && (!normalBusinessHoursForm.startTime || !normalBusinessHoursForm.endTime)) {
    ElMessage.warning("请选择营业时间段");
    return;
  }
  const newItem: NormalHoursItem = {
    days: [...normalBusinessHoursForm.selectedDays],
    timeType: normalBusinessHoursForm.timeType,
    startTime: normalBusinessHoursForm.timeType === "custom" ? normalBusinessHoursForm.startTime : "00:00",
    endTime: normalBusinessHoursForm.timeType === "custom" ? normalBusinessHoursForm.endTime : "23:59"
  };
  if (normalBusinessHoursEditIndex.value !== null) {
    newItem.id = normalHours.value[normalBusinessHoursEditIndex.value].id;
    normalHours.value[normalBusinessHoursEditIndex.value] = newItem;
    ElMessage.success("编辑成功");
  } else {
    normalHours.value.push(newItem);
    ElMessage.success("添加成功");
  }
  normalBusinessHoursDialogVisible.value = false;
  resetNormalBusinessHoursForm();
};

const checkSpecialDateDuplicate = (holidays: string[]): boolean => {
  const other = specialHours.value.filter((_, i) => i !== specialBusinessHoursEditIndex.value);
  return other.some(item => holidays.some(h => item.holidays.includes(h)));
};

const confirmSpecialBusinessHours = () => {
  if (specialBusinessHoursForm.selectedHolidays.length === 0) {
    ElMessage.warning("请选择营业日");
    return;
  }
  if (
    specialBusinessHoursForm.timeType === "custom" &&
    (!specialBusinessHoursForm.startTime || !specialBusinessHoursForm.endTime)
  ) {
    ElMessage.warning("请选择营业时间段");
    return;
  }
  if (checkSpecialDateDuplicate(specialBusinessHoursForm.selectedHolidays)) {
    ElMessage.warning("特殊营业时间的日期不能重复");
    return;
  }
  const newItem: SpecialHoursItem = {
    holidays: [...specialBusinessHoursForm.selectedHolidays],
    timeType: specialBusinessHoursForm.timeType,
    startTime: specialBusinessHoursForm.timeType === "custom" ? specialBusinessHoursForm.startTime : "00:00",
    endTime: specialBusinessHoursForm.timeType === "custom" ? specialBusinessHoursForm.endTime : "23:59"
  };
  if (specialBusinessHoursEditIndex.value !== null) {
    newItem.id = specialHours.value[specialBusinessHoursEditIndex.value].id;
    specialHours.value[specialBusinessHoursEditIndex.value] = newItem;
    ElMessage.success("编辑成功");
  } else {
    specialHours.value.push(newItem);
    ElMessage.success("添加成功");
  }
  specialBusinessHoursDialogVisible.value = false;
  resetSpecialBusinessHoursForm();
};

const handleDeleteBusinessHours = (row: { source: "normal" | "special"; index: number }, _listIndex: number) => {
  const isNormal = row.source === "normal";
  const doDelete = () => {
    if (isNormal) {
      if (normalHours.value.length <= 1) {
        ElMessage.warning("至少存在一条营业时间");
        return;
      }
      normalHours.value.splice(row.index, 1);
    } else {
      specialHours.value.splice(row.index, 1);
    }
    ElMessage.success("删除成功");
  };
  ElMessageBox.confirm("确认要删除当前营业时间吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(doDelete)
    .catch(() => {});
};

const handleSaveBusinessHours = async () => {
  if (normalHours.value.length === 0) {
    ElMessage.warning("至少添加一条营业时间");
    return;
  }
  const storeId = localGet("geeker-user")?.userInfo?.storeId || localGet("createdId");
  if (!storeId) {
    ElMessage.warning("未找到店铺信息");
    return;
  }
  businessHoursSaving.value = true;
  try {
    const apiDataList = convertDisplayDataToApi();
    const result: any = await addOrEditBusinessTime(apiDataList);
    if (result && (result.code === 200 || result.code === "200")) {
      ElMessage.success("保存成功");
      await fetchBusinessTimeList();
      businessHoursDialogVisible.value = false;
    } else {
      ElMessage.error(result?.msg || "保存失败");
      businessHoursDialogVisible.value = false;
    }
  } catch {
    ElMessage.error("保存失败");
    businessHoursDialogVisible.value = false;
  } finally {
    businessHoursSaving.value = false;
  }
};

//地址集合
const addressList = ref<any[]>([]);
const addressMap = new Map();

const route = useRoute();
const formRef = ref<FormInstance>();
const loading = ref(false);
// 标记是否正在加载详情数据，用于防止触发 watch
const isLoadingDetail = ref(false);

// 店铺评价三个输入框的独立变量
const storeEvaluate1 = ref("");
const storeEvaluate2 = ref("");
const storeEvaluate3 = ref("");

// 表单数据
const formData = reactive({
  id: "",
  storeName: "",
  storeCapacity: 0 as number,
  storeTel: "",
  storeArea: "",
  businessStatus: "",
  administrativeRegionProvinceAdcode: "",
  administrativeRegionCityAdcode: "",
  administrativeRegionDistrictAdcode: "",
  storeAddress: "",
  storeBlurb: "",
  storeEvaluate: "",
  queryAddress: "",
  businessSection: "" as number | "",
  businessSectionName: "",
  businessTypeName: "",
  businessCategoryName: "",
  expirationTime: "",
  foodLicenceExpirationTime: "",
  storePosition: "",
  storePositionLongitude: "",
  storePositionLatitude: "",
  isChain: 0,
  storeTickets: "" as number | "",
  /** 预定服务：1 提供 / 0 不提供（与 go-flow 入驻 bookingService 一致） */
  bookingService: 0 as 0 | 1
});

// 经纬度查询
const getLonAndLat = async (keyword: string) => {
  if (keyword) {
    console.log("地址查询", keyword);
    let param = {
      addressName: keyword
    };
    let res: any = await getInputPrompt(param as any);
    if (res.code == "200") {
      res.data.tips.forEach((item: any) => {
        addressMap.set(item.location, item.name);
      });
      addressList.value = res?.data?.tips || [];
      console.log("res", res);
    } else {
      ElMessage.error("新增失败！");
    }
  } else {
    addressList.value = [];
  }
};
const selectAddress = async (param: any) => {
  // 安全检查：确保 address 存在且是字符串类型
  if (!formData.storePosition || typeof formData.storePosition !== "string") {
    ElMessage.warning("地址格式不正确，请重新选择");
    return;
  }

  // 检查是否包含逗号（经纬度格式应该是 "经度,纬度"）
  if (!formData.storePosition.includes(",")) {
    ElMessage.warning("地址格式不正确，缺少经纬度信息");
    return;
  }

  // 安全地分割地址字符串
  let locationList = formData.storePosition.split(",");

  // 检查分割后的数组长度
  // if (locationList.length < 2) {
  //   ElMessage.warning("地址格式不正确，无法获取经纬度");
  //   return;
  // }

  // 查找对应的地址名称
  addressList.value.forEach((item: any) => {
    if (item.location == formData.storePosition) {
      formData.queryAddress = item.name;
      // queryAddress.value = item.name;
    }
  });
  formData.storePositionLongitude = locationList[0]?.trim();
  formData.storePositionLatitude = locationList[1]?.trim();
  // 设置经纬度，并去除可能的空格
  // formData.storePosition = locationList[0]?.trim() +","+locationList[1]?.trim()
};

// 表单验证规则
const rules = reactive<FormRules>({
  storeName: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
  storeCapacity: [{ required: true, message: "请输入容纳人数", trigger: "blur" }],
  storeTel: [
    { required: true, message: "请输入门店电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  storeArea: [{ required: true, message: "请选择门店面积", trigger: "change" }],
  businessStatus: [{ required: true, message: "请选择营业状态", trigger: "change" }],
  administrativeRegionProvinceAdcode: [{ required: true, message: "请选择省", trigger: "change" }],
  administrativeRegionCityAdcode: [{ required: true, message: "请选择市", trigger: "change" }],
  administrativeRegionDistrictAdcode: [{ required: true, message: "请选择区", trigger: "change" }],
  storeAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  storeBlurb: [{ required: true, message: "请输入门店简介", trigger: "blur" }],
  storeEvaluate: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!storeEvaluate1.value || !storeEvaluate2.value || !storeEvaluate3.value) {
          callback(new Error("请填写完整的店铺评价（三个评价都需要填写）"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  queryAddress: [{ required: true, message: "请输入地址进行经纬度查询", trigger: "blur" }],
  businessSection: [{ required: true, message: "请选择经营板块", trigger: "change" }],
  storeTickets: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // 仅当经营板块为生活服务（值为3）时，storeTickets为必填
        if (formData.businessSection === 3) {
          if (value === "" || value === null || value === undefined) {
            callback(new Error("请选择标签"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  businessTypeName: [{ required: true, message: "请输入经营种类", trigger: "blur" }],
  businessCategoryName: [{ required: true, message: "请输入经营类目", trigger: "blur" }]
});

// 地区选项
const provinceOptions = ref<any[]>([]);
const cityOptions = ref<any[]>([]);
const districtOptions = ref<any[]>([]);

// 经营板块列表 - 固定三个选项：特色美食:1, 休闲娱乐:2, 生活服务:3
const businessSectionList = ref<any[]>([
  { dictId: 1, dictDetail: "特色美食" },
  { dictId: 2, dictDetail: "休闲娱乐" },
  { dictId: 3, dictDetail: "生活服务" }
]);

// 获取省份数据
const getProvinceData = async () => {
  try {
    const { data } = await getDistrict();
    const dataAny = data as any;

    // 根据API返回结构：data.districts[0] 是"中华人民共和国"，data.districts[0].districts 是省份列表
    if (dataAny && dataAny.districts && Array.isArray(dataAny.districts) && dataAny.districts.length > 0) {
      const chinaData = dataAny.districts[0];
      if (chinaData && chinaData.districts && Array.isArray(chinaData.districts)) {
        provinceOptions.value = chinaData.districts;
      }
    }
  } catch (error) {
    console.error("获取省份数据失败:", error);
  }
};

// 省份变化时获取城市数据
const handleProvinceChange = async (provinceCode: string) => {
  formData.administrativeRegionCityAdcode = "";
  formData.administrativeRegionDistrictAdcode = "";
  cityOptions.value = [];
  districtOptions.value = [];

  if (!provinceCode) return;

  try {
    // 根据adcode查询下级（城市）
    const { data } = await getDistrict({ adCode: provinceCode } as any);
    const dataAny = data as any;

    // 根据API返回结构：data.districts[0] 是省份，data.districts[0].districts 是城市列表
    if (dataAny && dataAny.districts && Array.isArray(dataAny.districts) && dataAny.districts.length > 0) {
      const provinceData = dataAny.districts[0];
      if (provinceData && provinceData.districts && Array.isArray(provinceData.districts)) {
        cityOptions.value = provinceData.districts;
      }
    }
  } catch (error) {
    console.error("获取城市数据失败:", error);
  }
};

// 城市变化时获取区县数据
const handleCityChange = async (cityCode: string) => {
  formData.administrativeRegionDistrictAdcode = "";
  districtOptions.value = [];

  if (!cityCode) return;

  try {
    // 根据adcode查询下级（区县）
    const { data } = await getDistrict({ adCode: cityCode } as any);
    const dataAny = data as any;

    // 根据API返回结构：data.districts[0] 是城市，data.districts[0].districts 是区县列表
    if (dataAny && dataAny.districts && Array.isArray(dataAny.districts) && dataAny.districts.length > 0) {
      const cityData = dataAny.districts[0];
      if (cityData && cityData.districts && Array.isArray(cityData.districts)) {
        districtOptions.value = cityData.districts;
      }
    }
  } catch (error) {
    console.error("获取区县数据失败:", error);
  }
};
// 门店面积映射：字符串 -> 数字
const storeAreaMap: Record<string, number> = {
  小于20平米: 1,
  "20-50平米": 2,
  "50-100平米": 3,
  "100-300平米": 4,
  "300-500平米": 5,
  "500-1000平米": 6,
  大于1000平米: 7
};

// 门店面积反向映射：数字 -> 字符串
const storeAreaReverseMap: Record<number, string> = {
  1: "小于20平米",
  2: "20-50平米",
  3: "50-100平米",
  4: "100-300平米",
  5: "300-500平米",
  6: "500-1000平米",
  7: "大于1000平米"
};

// 营业状态映射：字符串 -> 数字
const businessStatusMap: Record<string, number> = {
  正常营业: 0,
  暂停营业: 1,
  筹建中: 2,
  永久关门: 3
};

// 营业状态反向映射：数字 -> 字符串
const businessStatusReverseMap: Record<number, string> = {
  0: "正常营业",
  1: "暂停营业",
  2: "筹建中",
  3: "永久关门"
};

// 经纬度查询（用户手动触发）
// const handleLocationQuery = async () => {
//   if (!formData.queryAddress) {
//     ElMessage.warning("请输入地址进行查询");
//     return;
//   }
//   const success = await queryLocation();
//   if (success) {
//     ElMessage.success("查询成功");
//   } else {
//     ElMessage.warning("未找到相关地址信息，请检查地址是否正确");
//   }
// };

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  // 先验证三个店铺评价字段是否都填写
  if (!storeEvaluate1.value || !storeEvaluate2.value || !storeEvaluate3.value) {
    ElMessage.warning("请填写完整的店铺评价（三个评价都需要填写）");
    // 手动触发验证，显示错误提示
    formRef.value.validateField("storeEvaluate", () => {});
    return;
  }

  // 验证标签选择（当经营板块为生活服务时）
  if (formData.businessSection === 3) {
    if (formData.storeTickets === "" || formData.storeTickets === null || formData.storeTickets === undefined) {
      ElMessage.warning("请选择标签");
      formRef.value.validateField("storeTickets", () => {});
      return;
    }
  }

  await formRef.value.validate(async valid => {
    if (!valid) {
      ElMessage.warning("请完善表单信息");
      return;
    }

    loading.value = true;
    try {
      // 保存前先调用经纬度查询接口
      if (formData.queryAddress) {
        // const locationQuerySuccess = await queryLocation();
        // if (!locationQuerySuccess) {
        //   ElMessage.warning("经纬度查询失败，请检查地址是否正确，将继续保存其他信息");
        // }
      }

      // 映射门店面积为数字
      const storeAreaNum = storeAreaMap[formData.storeArea] || 0;
      // 映射营业状态为数字
      const businessStatusNum = businessStatusMap[formData.businessStatus] ?? 0;

      // 获取经营板块名称
      const selectedSection = businessSectionList.value.find(item => item.dictId === formData.businessSection);

      // 将三个店铺评价用逗号拼接
      formData.storeEvaluate = [storeEvaluate1.value, storeEvaluate2.value, storeEvaluate3.value]
        .filter(item => item && item.trim())
        .join(",");

      const submitData = {
        id: formData.id ? Number(formData.id) : undefined,
        isChain: formData.isChain,
        storeName: formData.storeName,
        storeCapacity: String(formData.storeCapacity ?? ""),
        storeTel: formData.storeTel,
        storeAddress: formData.storeAddress,
        storeArea: formData.storeArea,
        storeBlurb: formData.storeBlurb,
        storeEvaluate: formData.storeEvaluate,
        queryAddress: formData.queryAddress,
        administrativeRegionProvinceAdcode: formData.administrativeRegionProvinceAdcode ?? "",
        administrativeRegionCityAdcode: formData.administrativeRegionCityAdcode ?? "",
        administrativeRegionDistrictAdcode: formData.administrativeRegionDistrictAdcode ?? "",
        storePosition: formData.storePosition,
        storePositionLongitude: formData.storePositionLongitude,
        storePositionLatitude: formData.storePositionLatitude,
        businessStatus: formData.businessStatus,
        // 经营板块相关参数（与移动端保持一致）
        businessSection: formData.businessSection,
        businessSectionName: selectedSection ? selectedSection.dictDetail : "",
        businessTypeName: formData.businessTypeName,
        businessCategoryName: formData.businessCategoryName,
        bookingService: formData.bookingService,
        // 标签选择（仅当经营板块为生活服务时）
        storeTickets:
          formData.businessSection === 3 ? (formData.storeTickets !== "" ? formData.storeTickets : undefined) : undefined
      };

      let result;
      if (formData.id) {
        // 编辑
        result = await editStoreInfo(submitData);
      } else {
        // 新增
        result = await saveStoreInfo(submitData);
      }

      if (result && result.code === 200) {
        ElNotification({
          title: "保存成功",
          type: "success",
          duration: 3000
        });
        // 如果是新增，获取返回的ID
        if (result.data && result.data.id) {
          formData.id = result.data.id;
        }
      } else {
        ElMessage.error(result?.msg || "保存失败");
      }
    } catch (error: any) {
      console.error("保存失败:", error);
      ElMessage.error(error?.msg || "保存失败，请稍后重试");
    } finally {
      loading.value = false;
    }
  });
};

const userInfo = localGet("geeker-user")?.userInfo || {};
// 获取店铺详情（编辑时使用）
const getStoreDetailData = async () => {
  isLoadingDetail.value = true; // 标记开始加载详情
  try {
    const { data } = await getStoreDetail({ id: userInfo.storeId } as any);
    if (data) {
      const storeData = data as any;
      console.log(storeData.businessStatus ?? "", "-------参数");
      formData.id = storeData.id ?? "";
      formData.storeName = storeData.storeName ?? "";
      formData.storeCapacity = Number(storeData.storeCapacity) ?? 0;
      formData.storeTel = storeData.storeTel ?? "";
      // 将数字映射回字符串
      formData.storeArea = storeData.storeArea ?? "";
      // 将数字映射回字符串
      formData.businessStatus = storeData.businessStatus ?? "";
      formData.storeAddress = storeData.storeAddress ?? "";
      formData.storeBlurb = storeData.storeBlurb ?? "";
      // 处理店铺评价：用逗号切割并分别赋值给三个输入框
      if (storeData.storeEvaluate) {
        const evaluateArray = storeData.storeEvaluate.split(",");
        storeEvaluate1.value = evaluateArray[0]?.trim() || "";
        storeEvaluate2.value = evaluateArray[1]?.trim() || "";
        storeEvaluate3.value = evaluateArray[2]?.trim() || "";
        formData.storeEvaluate = storeData.storeEvaluate;
      } else {
        storeEvaluate1.value = "";
        storeEvaluate2.value = "";
        storeEvaluate3.value = "";
        formData.storeEvaluate = "";
      }
      formData.expirationTime = storeData.expirationTime ?? "";
      formData.foodLicenceExpirationTime = storeData.foodLicenceExpirationTime ?? "";
      formData.storePosition = storeData.storePosition ?? "";
      formData.storePositionLongitude = storeData.storePositionLongitude ?? "";
      formData.storePositionLatitude = storeData.storePositionLatitude ?? "";
      formData.isChain = storeData.isChain ?? 0;
      formData.queryAddress = storeData.queryAddress;
      await getLonAndLat(storeData.queryAddress);
      // 设置地区
      const provinceCode = storeData.administrativeRegionProvinceAdcode ?? "";
      const cityCode = storeData.administrativeRegionCityAdcode ?? "";
      const districtCode = storeData.administrativeRegionDistrictAdcode ?? "";

      if (provinceCode) {
        formData.administrativeRegionProvinceAdcode = provinceCode;
        await handleProvinceChange(provinceCode);
        if (cityCode) {
          formData.administrativeRegionCityAdcode = cityCode;
          await handleCityChange(cityCode);
          if (districtCode) {
            formData.administrativeRegionDistrictAdcode = districtCode;
          }
        }
      }
      console.log(formData, "----参数3");
      // 设置经营板块和种类
      if (storeData.businessSection) {
        formData.businessSection = storeData.businessSection;
        formData.businessSectionName = storeData.businessSectionName ?? "";
      }
      // 设置标签选择（仅当经营板块为生活服务时）
      if (storeData.businessSection === 3) {
        formData.storeTickets =
          storeData.storeTickets !== undefined && storeData.storeTickets !== null ? Number(storeData.storeTickets) : "";
      } else {
        formData.storeTickets = "";
      }
      formData.businessTypeName = storeData.businessTypeName ?? "";
      // 如果 businessCategoryName 是 0，转换为空字符串
      const categoryName = storeData.businessCategoryName;
      formData.businessCategoryName = categoryName === 0 || categoryName === "0" ? "" : categoryName || "";
      formData.bookingService = storeData.bookingService === 1 || storeData.bookingService === "1" ? 1 : 0;
    }
  } catch (error) {
    console.error("获取店铺详情失败:", error);
  } finally {
    isLoadingDetail.value = false; // 标记加载完成
  }
};

// 监听经营板块变化，更新经营板块名称（由于已禁用，此 watch 主要用于初始化）
watch(
  () => formData.businessSection,
  newValue => {
    // 如果正在加载详情数据，不触发 watch（避免重复请求）
    if (isLoadingDetail.value) {
      return;
    }

    // 更新经营板块名称
    if (newValue) {
      const selectedSection = businessSectionList.value.find(item => item.dictId === newValue);
      formData.businessSectionName = selectedSection ? selectedSection.dictDetail : "";
      // 当切换到生活服务时，如果经营类目是 0，清空它
      if (newValue === 3 && formData.businessCategoryName === "0") {
        formData.businessCategoryName = "";
      }
      // 当切换到非生活服务时，清空标签选择
      if (newValue !== 3) {
        formData.storeTickets = "";
      }
    } else {
      // 如果经营板块为空，也清空标签选择
      formData.storeTickets = "";
    }
  }
);

onMounted(async () => {
  await getProvinceData();
  await getStoreDetailData();
});
</script>

<style scoped lang="scss">
.store-info-container {
  min-height: calc(100vh - 100px);
  padding: 20px;
  background-color: #ffffff;
  .store-form {
    .form-content {
      display: flex;
      gap: 40px;
      margin-bottom: 40px;
      .form-left,
      .form-right {
        flex: 1;
        min-width: 0;
      }
      .form-right {
        :deep(.el-form-item__label) {
          width: 180px !important;
        }
      }
    }
    .radio-item {
      width: 100%;
      margin-bottom: 16px;
      .radio-label {
        font-weight: 500;
      }
      .radio-desc {
        margin-top: 4px;
        margin-left: 24px;
        font-size: 12px;
        line-height: 1.5;
        color: #909399;
      }
    }
    .readonly-input {
      :deep(.el-input__inner) {
        color: #909399;
        cursor: not-allowed;
        background-color: #f5f7fa;
      }
    }
    .region-selector {
      display: flex;
      gap: 8px;
      width: 100%;
      .el-select {
        flex: 1;
      }
    }
    .form-footer {
      display: flex;
      justify-content: center;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
      .el-button {
        min-width: 120px;
      }
    }
  }
}

// 响应式布局
@media (width <=1200px) {
  .store-info-container {
    .store-form {
      .form-content {
        flex-direction: column;
        gap: 20px;
      }
    }
  }
}

// 经营板块单选按钮样式
.business-section-radio-group {
  display: flex;
  gap: 40px;
  .businessSection-item {
    flex: 0 0 auto;
  }
}

// 营业时间弹窗
.business-hours-tip {
  margin: 0 0 16px;
  font-size: 13px;
  line-height: 1.5;
  color: #334154;
}
.business-hours-list {
  max-height: 400px;
  overflow-y: auto;
}
.business-hours-item {
  padding: 14px 16px;
  margin-bottom: 12px;
  background: #fafafa;
  border: 1px solid #f2f2f2;
  border-radius: 8px;
  .business-hours-item-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .item-title {
      max-width: 75%;
      overflow: hidden;
      font-size: 14px;
      font-weight: 600;
      color: #334154;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .business-hours-item-time {
    margin-top: 8px;
    font-size: 13px;
    color: #334154;
  }
  .business-hours-item-actions {
    padding-top: 8px;
    margin-top: 8px;
    border-top: 1px solid #f2f2f2;
    .el-button {
      padding-left: 0;
    }
  }
}
.business-hours-dialog-footer {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-end;
}
.day-buttons,
.holiday-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  .el-button {
    margin: 0;
  }
}
.time-picker-row {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 8px;
}
.time-sep {
  font-size: 14px;
  color: #606266;
}
</style>
