/**
 * 文件职责：堂食管理页面主编排。
 * 1. 维护页面级状态（门店、区域、桌位、设置、抽屉、弹窗）。
 * 2. 组合数据加载、复制、区域/桌位动作。
 * 3. 对外暴露视图层可直接消费的状态与方法。
 */
import type { StoreListItemDto } from '#/api/store';
import type {
  DineInAreaDto,
  DineInBasicSettingsDto,
  DineInTableDto,
} from '#/api/store-dinein';
import type {
  DineInAreaDrawerMode,
  DineInAreaFormState,
  DineInBatchFormState,
  DineInSettingsSnapshot,
  DineInTableDrawerMode,
  DineInTableFormState,
} from '#/views/store/dine-in/types';

import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';

import { createAreaActions } from './dinein-page/area-actions';
import {
  DINE_IN_SEATS_OPTIONS,
  DINE_IN_STATUS_MAP,
  TABLE_TAG_SUGGESTIONS,
} from './dinein-page/constants';
import { createCopyActions } from './dinein-page/copy-actions';
import { createDataActions } from './dinein-page/data-actions';
import {
  cloneBasicSettings,
  countAreaTables,
  generateBatchCodes,
  resolveStatusClassName,
} from './dinein-page/helpers';
import { createTableActions } from './dinein-page/table-actions';

const EMPTY_BASIC_SETTINGS: DineInBasicSettingsDto = {
  enabled: false,
  defaultDiningMinutes: 0,
  overtimeReminderMinutes: 0,
};

export function useStoreDineInPage() {
  // 1. 页面 loading / submitting 状态。
  const isStoreLoading = ref(false);
  const isPageLoading = ref(false);
  const isSavingBasic = ref(false);
  const isSavingArea = ref(false);
  const isSavingTable = ref(false);
  const isSavingBatch = ref(false);
  const isCopySubmitting = ref(false);
  const isConfigured = ref(false);

  // 2. 页面核心业务数据。
  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const loadedStoreId = ref('');
  const areas = ref<DineInAreaDto[]>([]);
  const tables = ref<DineInTableDto[]>([]);
  const basicSettings = reactive<DineInBasicSettingsDto>(
    cloneBasicSettings(EMPTY_BASIC_SETTINGS),
  );
  const selectedAreaId = ref('');
  const snapshot = ref<DineInSettingsSnapshot | null>(null);

  // 3. 复制弹窗状态。
  const isCopyModalOpen = ref(false);
  const copyTargetStoreIds = ref<string[]>([]);

  // 4. 区域抽屉状态。
  const isAreaDrawerOpen = ref(false);
  const areaDrawerMode = ref<DineInAreaDrawerMode>('create');
  const areaForm = reactive<DineInAreaFormState>({
    id: '',
    name: '',
    description: '',
    sort: 1,
  });

  // 5. 桌位抽屉与批量弹窗状态。
  const isTableDrawerOpen = ref(false);
  const tableDrawerMode = ref<DineInTableDrawerMode>('create');
  const tableForm = reactive<DineInTableFormState>({
    id: '',
    code: '',
    areaId: selectedAreaId.value,
    seats: 4,
    tags: [],
    sourceStatus: 'free',
    isDisabled: false,
  });
  const isBatchModalOpen = ref(false);
  const batchForm = reactive<DineInBatchFormState>({
    areaId: selectedAreaId.value,
    codePrefix: 'A',
    startNumber: 1,
    count: 4,
    seats: 4,
  });

  // 6. 页面衍生视图数据。
  const storeOptions = computed(() =>
    stores.value.map((store) => ({ label: store.name, value: store.id })),
  );

  const selectedStoreName = computed(
    () =>
      stores.value.find((store) => store.id === selectedStoreId.value)?.name ??
      '',
  );
  const hasSelectedStore = computed(() => Boolean(selectedStoreId.value));
  const hasLoadedStoreSettings = computed(() => snapshot.value !== null);
  const canOperate = computed(
    () =>
      hasSelectedStore.value &&
      loadedStoreId.value === selectedStoreId.value &&
      hasLoadedStoreSettings.value &&
      !isStoreLoading.value &&
      !isPageLoading.value &&
      !isSavingArea.value &&
      !isSavingTable.value &&
      !isSavingBatch.value &&
      !isSavingBasic.value,
  );

  const selectedArea = computed(
    () =>
      areas.value.find((area) => area.id === selectedAreaId.value) ??
      areas.value[0],
  );

  const selectedAreaTableCount = computed(() => {
    const area = selectedArea.value;
    if (!area) return 0;
    return countAreaTables(area.id, tables.value);
  });

  const filteredTables = computed(() => {
    const area = selectedArea.value;
    if (!area) return [];
    return tables.value.filter((table) => table.areaId === area.id);
  });

  const areaOptions = computed(() =>
    areas.value.map((area) => ({ label: area.name, value: area.id })),
  );

  const copyCandidates = computed(() =>
    stores.value.filter((store) => store.id !== selectedStoreId.value),
  );

  const isCopyAllChecked = computed(
    () =>
      copyCandidates.value.length > 0 &&
      copyTargetStoreIds.value.length === copyCandidates.value.length,
  );

  const isCopyIndeterminate = computed(
    () =>
      copyTargetStoreIds.value.length > 0 &&
      copyTargetStoreIds.value.length < copyCandidates.value.length,
  );

  const batchPreviewCodes = computed(() => generateBatchCodes(batchForm));

  const areaDrawerTitle = computed(() =>
    areaDrawerMode.value === 'edit' ? '编辑区域' : '添加区域',
  );

  const areaSubmitText = computed(() =>
    areaDrawerMode.value === 'edit' ? '保存修改' : '确认添加',
  );

  const tableDrawerTitle = computed(() =>
    tableDrawerMode.value === 'edit'
      ? `编辑桌位 - ${tableForm.code || '--'}`
      : '添加桌位',
  );

  const tableSubmitText = computed(() =>
    tableDrawerMode.value === 'edit' ? '保存修改' : '确认添加',
  );

  function clearSettings() {
    loadedStoreId.value = '';
    areas.value = [];
    tables.value = [];
    selectedAreaId.value = '';
    basicSettings.enabled = EMPTY_BASIC_SETTINGS.enabled;
    basicSettings.defaultDiningMinutes =
      EMPTY_BASIC_SETTINGS.defaultDiningMinutes;
    basicSettings.overtimeReminderMinutes =
      EMPTY_BASIC_SETTINGS.overtimeReminderMinutes;
  }

  // 7. 数据域动作装配。
  const {
    buildCurrentSnapshot,
    fixSelectedArea,
    loadStoreSettings,
    loadStores,
    resetBasicSettings,
    saveBasicSettings,
  } = createDataActions({
    areas,
    basicSettings,
    clearSettings,
    isConfigured,
    isPageLoading,
    isSavingBasic,
    isStoreLoading,
    loadedStoreId,
    selectedAreaId,
    selectedStoreId,
    snapshot,
    stores,
    tables,
  });

  const {
    handleCopyCheckAll,
    handleCopySubmit,
    openCopyModal,
    toggleCopyStore,
  } = createCopyActions({
    copyCandidates,
    copyTargetStoreIds,
    isCopyModalOpen,
    isCopySubmitting,
    selectedStoreId,
  });

  /** 更新快照供重置使用。 */
  function updateSnapshot() {
    snapshot.value = buildCurrentSnapshot();
  }

  const {
    handleDeleteArea,
    handleSubmitArea,
    openAreaDrawer,
    setAreaDescription,
    setAreaDrawerOpen,
    setAreaName,
    setAreaSort,
  } = createAreaActions({
    areaDrawerMode,
    areaForm,
    areas,
    fixSelectedArea,
    isAreaDrawerOpen,
    isSavingArea,
    selectedAreaId,
    selectedStoreId,
    tables,
    updateSnapshot,
  });

  const {
    handleDeleteTable,
    handleSubmitBatch,
    handleSubmitTable,
    openBatchModal,
    openTableDrawer,
    setBatchAreaId,
    setBatchCodePrefix,
    setBatchCount,
    setBatchModalOpen,
    setBatchSeats,
    setBatchStartNumber,
    setTableAreaId,
    setTableCode,
    setTableDisabled,
    setTableDrawerOpen,
    setTableSeats,
    setTableTags,
  } = createTableActions({
    areas,
    batchForm,
    isBatchModalOpen,
    isSavingBatch,
    isSavingTable,
    isTableDrawerOpen,
    selectedStoreId,
    selectedTableAreaId: selectedAreaId,
    tableDrawerMode,
    tableForm,
    tables,
    updateSnapshot,
  });

  // 8. 页面字段更新方法。
  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  function setSelectedAreaId(value: string) {
    selectedAreaId.value = value;
  }

  function setDineInEnabled(value: boolean) {
    basicSettings.enabled = Boolean(value);
  }

  function setDefaultDiningMinutes(value: number) {
    basicSettings.defaultDiningMinutes = Math.max(
      1,
      Math.floor(Number(value || 1)),
    );
  }

  function setOvertimeReminderMinutes(value: number) {
    basicSettings.overtimeReminderMinutes = Math.max(
      0,
      Math.floor(Number(value || 0)),
    );
  }

  // 9. 门店切换时自动刷新配置。
  watch(selectedStoreId, async (storeId) => {
    if (!storeId) {
      clearSettings();
      isConfigured.value = false;
      snapshot.value = null;
      return;
    }
    isConfigured.value = false;
    await loadStoreSettings(storeId);
  });

  // 10. 页面首屏初始化。
  onMounted(loadStores);
  // 11. 路由回到当前页时刷新门店列表，避免使用旧缓存。
  onActivated(loadStores);

  return {
    DINE_IN_SEATS_OPTIONS,
    DINE_IN_STATUS_MAP,
    TABLE_TAG_SUGGESTIONS,
    areaDrawerTitle,
    areaForm,
    areaOptions,
    areaSubmitText,
    areas,
    basicSettings,
    batchForm,
    batchPreviewCodes,
    canOperate,
    copyCandidates,
    copyTargetStoreIds,
    filteredTables,
    handleCopyCheckAll,
    handleCopySubmit,
    handleDeleteArea,
    handleDeleteTable,
    handleSubmitArea,
    handleSubmitBatch,
    handleSubmitTable,
    isAreaDrawerOpen,
    isBatchModalOpen,
    isCopyAllChecked,
    isCopyIndeterminate,
    isCopyModalOpen,
    isCopySubmitting,
    isConfigured,
    isPageLoading,
    isSavingArea,
    isSavingBasic,
    isSavingBatch,
    isSavingTable,
    isStoreLoading,
    isTableDrawerOpen,
    openAreaDrawer,
    openBatchModal,
    openCopyModal,
    openTableDrawer,
    resetBasicSettings,
    resolveStatusClassName,
    saveBasicSettings,
    selectedArea,
    selectedAreaId,
    selectedAreaTableCount,
    hasSelectedStore,
    hasLoadedStoreSettings,
    loadedStoreId,
    selectedStoreId,
    selectedStoreName,
    setAreaDescription,
    setAreaDrawerOpen,
    setAreaName,
    setAreaSort,
    setBatchAreaId,
    setBatchCodePrefix,
    setBatchCount,
    setBatchModalOpen,
    setBatchSeats,
    setBatchStartNumber,
    setDefaultDiningMinutes,
    setDineInEnabled,
    setOvertimeReminderMinutes,
    setSelectedAreaId,
    setSelectedStoreId,
    setTableAreaId,
    setTableCode,
    setTableDisabled,
    setTableDrawerOpen,
    setTableSeats,
    setTableTags,
    storeOptions,
    tableDrawerTitle,
    tableForm,
    tableSubmitText,
    tables,
    toggleCopyStore,
  };
}
