<script setup lang="ts">
/**
 * 文件职责：配送设置页面主视图。
 * 1. 组合配送模式、梯度/区域、通用设置子组件。
 * 2. 承接门店维度切换与复制弹窗。
 */
import { Page } from '@vben/common-ui';

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

import CopyToStoresModal from '../../shared/components/CopyToStoresModal.vue';
import StoreScopeToolbar from '../../shared/components/StoreScopeToolbar.vue';
import DeliveryCommonSettingsCard from './components/DeliveryCommonSettingsCard.vue';
import DeliveryModeCard from './components/DeliveryModeCard.vue';
import DeliveryTierDrawer from './components/DeliveryTierDrawer.vue';
import DeliveryZoneDrawer from './components/DeliveryZoneDrawer.vue';
import PolygonZoneSection from './components/PolygonZoneSection.vue';
import RadiusTierSection from './components/RadiusTierSection.vue';
import { useStoreDeliveryPage } from './composables/useStoreDeliveryPage';

const {
  DELIVERY_MODE_OPTIONS,
  canOperate,
  copyCandidates,
  copyTargetStoreIds,
  deliveryMode,
  editingMode,
  formatCurrency,
  formatDistanceRange,
  generalSettings,
  handleCopyCheckAll,
  handleCopySubmit,
  handleDeleteTier,
  handleDeleteZone,
  handleTierSubmit,
  handleZoneSubmit,
  isCopyAllChecked,
  isCopyIndeterminate,
  isCopyModalOpen,
  isCopySubmitting,
  isConfigured,
  hasLoadedStoreSettings,
  isPageLoading,
  isRadiusMode,
  isSaving,
  isStoreLoading,
  isTierDrawerOpen,
  isZoneDrawerOpen,
  mapCenterAddress,
  mapCenterLatitude,
  mapCenterLongitude,
  mapFallbackCityText,
  openCopyModal,
  openTierDrawer,
  openZoneDrawer,
  polygonZones,
  radiusCenterLatitude,
  radiusCenterLongitude,
  radiusTiers,
  resetFromSnapshot,
  saveCurrentSettings,
  selectedStoreId,
  selectedStoreName,
  setDeliveryMode,
  setEditingMode,
  setEtaAdjustmentMinutes,
  setFreeDeliveryThreshold,
  setHourlyCapacityLimit,
  setMaxDeliveryDistance,
  setRadiusCenterLatitude,
  setRadiusCenterLongitude,
  setSelectedStoreId,
  setTierColor,
  setTierDeliveryFee,
  setTierDrawerOpen,
  setTierEtaMinutes,
  setTierMaxDistance,
  setTierMinDistance,
  setTierMinOrderAmount,
  setZoneColor,
  setZoneDeliveryFee,
  setZoneDrawerOpen,
  setZoneEtaMinutes,
  setZoneMinOrderAmount,
  setZoneName,
  setZonePolygonGeoJson,
  setZonePriority,
  storeOptions,
  tierColorPalette,
  tierDrawerTitle,
  tierForm,
  toggleCopyStore,
  zoneDrawerTitle,
  zoneForm,
} = useStoreDeliveryPage();
</script>

<template>
  <Page title="配送设置" content-class="space-y-4 page-store-delivery">
    <StoreScopeToolbar
      :selected-store-id="selectedStoreId"
      :store-options="storeOptions"
      :is-store-loading="isStoreLoading"
      :copy-disabled="
        !canOperate || !isConfigured || copyCandidates.length === 0
      "
      @update:selected-store-id="setSelectedStoreId"
      @copy="openCopyModal"
    />

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

    <template v-else>
      <Spin :spinning="isPageLoading">
        <Card v-if="hasLoadedStoreSettings && !isConfigured" :bordered="false">
          <Empty
            description="当前门店尚未配置配送规则。请先填写规则并保存，之后可执行复制。"
          />
        </Card>

        <div class="delivery-cards-stack">
          <DeliveryModeCard
            :active-mode="deliveryMode"
            :config-mode="editingMode"
            :radius-center-latitude="radiusCenterLatitude"
            :radius-center-longitude="radiusCenterLongitude"
            :mode-options="DELIVERY_MODE_OPTIONS"
            @change-active-mode="setDeliveryMode"
            @change-config-mode="setEditingMode"
            @change-radius-center-latitude="setRadiusCenterLatitude"
            @change-radius-center-longitude="setRadiusCenterLongitude"
          />

          <RadiusTierSection
            v-if="isRadiusMode"
            :tiers="radiusTiers"
            :format-currency="formatCurrency"
            :format-distance-range="formatDistanceRange"
            :is-saving="isSaving"
            @add="openTierDrawer('create')"
            @edit="(tier) => openTierDrawer('edit', tier)"
            @delete="handleDeleteTier"
          />

          <PolygonZoneSection
            v-else
            :zones="polygonZones"
            :format-currency="formatCurrency"
            :is-saving="isSaving"
            @add="openZoneDrawer('create')"
            @edit="(zone) => openZoneDrawer('edit', zone)"
            @delete="handleDeleteZone"
          />

          <DeliveryCommonSettingsCard
            :settings="generalSettings"
            :is-saving="isSaving"
            :on-set-free-delivery-threshold="setFreeDeliveryThreshold"
            :on-set-max-delivery-distance="setMaxDeliveryDistance"
            :on-set-hourly-capacity-limit="setHourlyCapacityLimit"
            :on-set-eta-adjustment-minutes="setEtaAdjustmentMinutes"
            @reset="resetFromSnapshot"
            @save="saveCurrentSettings"
          />
        </div>
      </Spin>
    </template>

    <DeliveryTierDrawer
      :open="isTierDrawerOpen"
      :title="tierDrawerTitle"
      :form="tierForm"
      :color-palette="tierColorPalette"
      :on-set-min-distance="setTierMinDistance"
      :on-set-max-distance="setTierMaxDistance"
      :on-set-delivery-fee="setTierDeliveryFee"
      :on-set-eta-minutes="setTierEtaMinutes"
      :on-set-min-order-amount="setTierMinOrderAmount"
      :on-set-color="setTierColor"
      @update:open="setTierDrawerOpen"
      @submit="handleTierSubmit"
    />

    <DeliveryZoneDrawer
      :open="isZoneDrawerOpen"
      :title="zoneDrawerTitle"
      :form="zoneForm"
      :color-palette="tierColorPalette"
      :on-set-name="setZoneName"
      :on-set-delivery-fee="setZoneDeliveryFee"
      :on-set-min-order-amount="setZoneMinOrderAmount"
      :on-set-eta-minutes="setZoneEtaMinutes"
      :on-set-priority="setZonePriority"
      :on-set-color="setZoneColor"
      :on-set-polygon-geo-json="setZonePolygonGeoJson"
      :initial-center-latitude="mapCenterLatitude"
      :initial-center-longitude="mapCenterLongitude"
      :initial-center-address="mapCenterAddress"
      :fallback-city-text="mapFallbackCityText"
      @update:open="setZoneDrawerOpen"
      @submit="handleZoneSubmit"
    />

    <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>
