<script setup lang="ts">
import { Page } from '@vben/common-ui';

import { Button, Card, Empty, Popconfirm, Spin } from 'ant-design-vue';

import CopyToStoresModal from '../../shared/components/CopyToStoresModal.vue';
import StoreScopeToolbar from '../../shared/components/StoreScopeToolbar.vue';
import AddSlotDrawer from './components/AddSlotDrawer.vue';
import DayEditDrawer from './components/DayEditDrawer.vue';
import HolidayDrawer from './components/HolidayDrawer.vue';
import { useStoreHoursPage } from './composables/useStoreHoursPage';

const {
  DAY_NAMES,
  HolidayType,
  SLOT_TYPE_OPTIONS,
  SlotType,
  addDaySlotRow,
  addSlotForm,
  copyCandidates,
  copyTargetStoreIds,
  currentDayMeta,
  dayEditForm,
  deletingHolidayId,
  formatHolidayDate,
  formatHolidayTime,
  getHolidayTagStyle,
  getHolidayTypeText,
  getLegendDotColor,
  getSlotStyle,
  getSlotTypeLabel,
  getSlotTypePillClass,
  handleAddSlotSubmit,
  handleCopyCheckAll,
  handleCopySubmit,
  handleDeleteHoliday,
  handleHolidaySubmit,
  handleSaveDay,
  holidayDrawerTitle,
  holidayForm,
  holidayRows,
  holidaySubmitText,
  isAddDaySelected,
  isAddDrawerOpen,
  isCopyAllChecked,
  isCopyIndeterminate,
  isCopyModalOpen,
  isCopySubmitting,
  isDayDrawerOpen,
  isHolidayDrawerOpen,
  isHolidaySubmitting,
  isHoursLoading,
  isStoreLoading,
  isWeeklySubmitting,
  openAddSlotDrawer,
  openCopyModal,
  openDayDrawer,
  openHolidayDrawer,
  quickSelectAddDays,
  removeDaySlot,
  selectedStoreId,
  selectedStoreName,
  setAddSlotCapacity,
  setAddSlotEndTime,
  setAddSlotRemark,
  setAddSlotStartTime,
  setAddSlotType,
  setDayEditOpen,
  setDaySlotCapacity,
  setDaySlotEndTime,
  setDaySlotStartTime,
  setDaySlotType,
  setHolidayDateMode,
  setHolidayEndTime,
  setHolidayRangeEnd,
  setHolidayRangeStart,
  setHolidayReason,
  setHolidayRemark,
  setHolidaySingleDate,
  setHolidayStartTime,
  setHolidayType,
  storeOptions,
  toggleAddDay,
  toggleCopyStore,
  weekRows,
} = useStoreHoursPage();
</script>

<template>
  <Page title="营业时间" content-class="space-y-4 page-hours">
    <StoreScopeToolbar
      :selected-store-id="selectedStoreId"
      :store-options="storeOptions"
      :is-store-loading="isStoreLoading"
      :copy-disabled="!selectedStoreId || copyCandidates.length === 0"
      @update:selected-store-id="(value) => (selectedStoreId = value)"
      @copy="openCopyModal"
    />

    <template v-if="storeOptions.length === 0">
      <Card :bordered="false">
        <Empty description="暂无门店，请先创建门店" />
      </Card>
    </template>

    <template v-else>
      <Spin :spinning="isHoursLoading">
        <Card :bordered="false">
          <template #title>
            <span class="section-title">每周营业时间</span>
          </template>
          <template #extra>
            <Button
              type="primary"
              :disabled="!selectedStoreId"
              @click="openAddSlotDrawer"
            >
              添加时段
            </Button>
          </template>

          <div class="legend-row">
            <span
              v-for="item in SLOT_TYPE_OPTIONS"
              :key="item.value"
              class="legend-item"
            >
              <span
                class="legend-dot"
                :style="{ background: getLegendDotColor(item.value) }"
              ></span>
              {{ item.label }}
            </span>
          </div>

          <div class="week-grid">
            <div v-for="day in weekRows" :key="day.dayOfWeek" class="week-row">
              <div class="week-day">
                {{ day.label }}
                <div class="week-day-en">{{ day.labelEn }}</div>
              </div>

              <div class="week-slots">
                <template v-if="day.isOpen && day.slots.length > 0">
                  <div
                    v-for="slot in day.slots"
                    :key="slot.id"
                    class="time-slot"
                    :style="getSlotStyle(slot.type)"
                  >
                    <span class="slot-type">{{
                      getSlotTypeLabel(slot.type)
                    }}</span>
                    <span class="slot-time">
                      {{ slot.startTime }}-{{ slot.endTime }}
                    </span>
                    <span
                      v-if="slot.type === SlotType.Delivery && slot.capacity"
                      class="slot-cap"
                    >
                      {{ slot.capacity }}单/h
                    </span>
                  </div>
                </template>
                <span v-else class="week-closed">休息</span>
              </div>

              <div class="week-actions">
                <Button
                  type="text"
                  size="small"
                  @click="openDayDrawer(day.dayOfWeek)"
                >
                  编辑
                </Button>
              </div>
            </div>
          </div>
        </Card>

        <Card :bordered="false">
          <template #title>
            <span class="section-title">节假日 / 特殊日期</span>
          </template>
          <template #extra>
            <Button
              type="primary"
              :disabled="!selectedStoreId"
              @click="openHolidayDrawer('create')"
            >
              添加日期
            </Button>
          </template>

          <div class="holiday-table-wrap">
            <table class="holiday-table">
              <thead>
                <tr>
                  <th>日期</th>
                  <th>类型</th>
                  <th>时间</th>
                  <th>原因</th>
                  <th class="op-column">操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="holidayRows.length === 0">
                  <td colspan="5">
                    <Empty description="暂无节假日配置" />
                  </td>
                </tr>
                <tr v-for="holiday in holidayRows" v-else :key="holiday.id">
                  <td>{{ formatHolidayDate(holiday) }}</td>
                  <td>
                    <span
                      class="holiday-tag"
                      :style="getHolidayTagStyle(holiday.type)"
                    >
                      {{ getHolidayTypeText(holiday.type) }}
                    </span>
                  </td>
                  <td>{{ formatHolidayTime(holiday) }}</td>
                  <td>{{ holiday.reason || '--' }}</td>
                  <td class="holiday-op-cell">
                    <div class="holiday-actions">
                      <Button
                        type="link"
                        size="small"
                        class="holiday-action-btn"
                        @click="openHolidayDrawer('edit', holiday)"
                      >
                        编辑
                      </Button>
                      <Popconfirm
                        title="确认删除该日期配置吗？"
                        ok-text="确认"
                        cancel-text="取消"
                        @confirm="handleDeleteHoliday(holiday.id)"
                      >
                        <Button
                          type="link"
                          size="small"
                          danger
                          class="holiday-action-btn holiday-delete-btn"
                          :loading="deletingHolidayId === holiday.id"
                        >
                          删除
                        </Button>
                      </Popconfirm>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </Card>
      </Spin>
    </template>

    <AddSlotDrawer
      v-model:open="isAddDrawerOpen"
      :add-slot-form="addSlotForm"
      :day-names="DAY_NAMES"
      :get-slot-type-pill-class="getSlotTypePillClass"
      :is-add-day-selected="isAddDaySelected"
      :is-weekly-submitting="isWeeklySubmitting"
      :on-set-capacity="setAddSlotCapacity"
      :on-set-end-time="setAddSlotEndTime"
      :on-set-remark="setAddSlotRemark"
      :on-set-start-time="setAddSlotStartTime"
      :on-set-type="setAddSlotType"
      :slot-type-delivery="SlotType.Delivery"
      :slot-type-options="SLOT_TYPE_OPTIONS"
      @quick-select="quickSelectAddDays"
      @submit="handleAddSlotSubmit"
      @toggle-day="toggleAddDay"
    />

    <DayEditDrawer
      v-model:open="isDayDrawerOpen"
      :day-edit-form="dayEditForm"
      :is-weekly-submitting="isWeeklySubmitting"
      :on-set-day-open="setDayEditOpen"
      :on-set-slot-capacity="setDaySlotCapacity"
      :on-set-slot-end-time="setDaySlotEndTime"
      :on-set-slot-start-time="setDaySlotStartTime"
      :on-set-slot-type="setDaySlotType"
      :slot-type-delivery="SlotType.Delivery"
      :slot-type-options="SLOT_TYPE_OPTIONS"
      :title="`编辑时段 - ${currentDayMeta.label}`"
      @add-slot-row="addDaySlotRow"
      @remove-slot="removeDaySlot"
      @save="handleSaveDay"
    />

    <HolidayDrawer
      v-model:open="isHolidayDrawerOpen"
      :holiday-form="holidayForm"
      :holiday-type-closed="HolidayType.Closed"
      :holiday-type-special="HolidayType.Special"
      :is-holiday-submitting="isHolidaySubmitting"
      :on-set-date-mode="setHolidayDateMode"
      :on-set-end-time="setHolidayEndTime"
      :on-set-range-end="setHolidayRangeEnd"
      :on-set-range-start="setHolidayRangeStart"
      :on-set-reason="setHolidayReason"
      :on-set-remark="setHolidayRemark"
      :on-set-single-date="setHolidaySingleDate"
      :on-set-start-time="setHolidayStartTime"
      :on-set-type="setHolidayType"
      :submit-text="holidaySubmitText"
      :title="holidayDrawerTitle"
      @submit="handleHolidaySubmit"
    />

    <CopyToStoresModal
      v-model:open="isCopyModalOpen"
      :copy-candidates="copyCandidates"
      :target-store-ids="copyTargetStoreIds"
      :is-all-checked="isCopyAllChecked"
      :is-indeterminate="isCopyIndeterminate"
      :is-submitting="isCopySubmitting"
      :selected-store-name="selectedStoreName"
      title="复制营业时间到其他门店"
      confirm-text="确认复制"
      @check-all="handleCopyCheckAll"
      @submit="handleCopySubmit"
      @toggle-store="
        ({ storeId, checked }) => toggleCopyStore(storeId, checked)
      "
    />
  </Page>
</template>

<style lang="less">
@import './styles/index.less';
</style>
