import type { Ref } from 'vue';

/**
 * 文件职责：堂食管理数据动作。
 * 1. 加载门店列表与门店堂食设置。
 * 2. 保存基础设置并维护快照。
 */
import type { StoreListItemDto } from '#/api/store';
import type {
  DineInAreaDto,
  DineInBasicSettingsDto,
  DineInTableDto,
} from '#/api/store-dinein';
import type { DineInSettingsSnapshot } from '#/views/store/dine-in/types';

import { message } from 'ant-design-vue';

import { getStoreListApi } from '#/api/store';
import {
  getStoreDineInSettingsApi,
  saveStoreDineInBasicSettingsApi,
} from '#/api/store-dinein';

import {
  cloneBasicSettings,
  createSettingsSnapshot,
  sortAreas,
  sortTables,
} from './helpers';

interface CreateDataActionsOptions {
  areas: Ref<DineInAreaDto[]>;
  basicSettings: DineInBasicSettingsDto;
  clearSettings: () => void;
  isConfigured: Ref<boolean>;
  isPageLoading: Ref<boolean>;
  isSavingBasic: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  loadedStoreId: Ref<string>;
  selectedAreaId: Ref<string>;
  selectedStoreId: Ref<string>;
  snapshot: Ref<DineInSettingsSnapshot | null>;
  stores: Ref<StoreListItemDto[]>;
  tables: Ref<DineInTableDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  /** 同步基础设置，保持 reactive 引用不变。 */
  function syncBasicSettings(next: DineInBasicSettingsDto) {
    options.basicSettings.enabled = next.enabled;
    options.basicSettings.defaultDiningMinutes = next.defaultDiningMinutes;
    options.basicSettings.overtimeReminderMinutes =
      next.overtimeReminderMinutes;
  }

  /** 构建当前快照。 */
  function buildCurrentSnapshot() {
    return createSettingsSnapshot({
      areas: options.areas.value,
      tables: options.tables.value,
      basicSettings: options.basicSettings,
    });
  }

  /** 根据当前区域合法性回填选中值。 */
  function fixSelectedArea() {
    if (options.areas.value.length === 0) {
      options.selectedAreaId.value = '';
      return;
    }
    const hasSelected = options.areas.value.some(
      (area) => area.id === options.selectedAreaId.value,
    );
    if (!hasSelected) {
      options.selectedAreaId.value = options.areas.value[0]?.id ?? '';
    }
  }

  /** 加载门店堂食设置。 */
  async function loadStoreSettings(storeId: string) {
    options.isPageLoading.value = true;
    try {
      const currentStoreId = storeId;
      const result = await getStoreDineInSettingsApi(storeId);
      if (options.selectedStoreId.value !== currentStoreId) return;

      if (!result.isConfigured) {
        options.clearSettings();
        options.isConfigured.value = false;
        options.loadedStoreId.value = currentStoreId;
        options.snapshot.value = buildCurrentSnapshot();
        return;
      }

      options.areas.value = sortAreas(result.areas ?? []);
      options.tables.value = sortTables(result.tables ?? []);
      if (result.basicSettings) {
        syncBasicSettings(cloneBasicSettings(result.basicSettings));
      }
      fixSelectedArea();
      options.isConfigured.value = true;
      options.loadedStoreId.value = currentStoreId;

      options.snapshot.value = buildCurrentSnapshot();
    } catch (error) {
      console.error(error);
      options.isConfigured.value = false;
      options.loadedStoreId.value = '';
      options.snapshot.value = null;
      options.clearSettings();
      message.error('加载堂食设置失败，请稍后重试');
    } finally {
      options.isPageLoading.value = false;
    }
  }

  /** 加载门店列表。 */
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        keyword: undefined,
        businessStatus: undefined,
        auditStatus: undefined,
        serviceType: undefined,
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];

      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        options.isConfigured.value = false;
        options.clearSettings();
        options.snapshot.value = null;
        return;
      }

      const hasSelectedStore = options.stores.value.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!hasSelectedStore) {
        const firstStore = options.stores.value[0];
        if (firstStore) options.selectedStoreId.value = firstStore.id;
        return;
      }
      if (options.selectedStoreId.value) {
        await loadStoreSettings(options.selectedStoreId.value);
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败，请稍后重试');
      options.stores.value = [];
      options.selectedStoreId.value = '';
      options.isConfigured.value = false;
      options.clearSettings();
      options.snapshot.value = null;
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  /** 保存基础设置。 */
  async function saveBasicSettings() {
    if (!options.selectedStoreId.value) return;
    options.isSavingBasic.value = true;
    try {
      await saveStoreDineInBasicSettingsApi({
        storeId: options.selectedStoreId.value,
        basicSettings: cloneBasicSettings(options.basicSettings),
      });
      options.isConfigured.value = true;
      options.snapshot.value = buildCurrentSnapshot();
      message.success('堂食设置已保存');
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingBasic.value = false;
    }
  }

  /** 重置基础设置到最近快照。 */
  function resetBasicSettings() {
    if (!options.snapshot.value) {
      message.warning('暂无可恢复的已保存配置');
      return;
    }
    syncBasicSettings(options.snapshot.value.basicSettings);
    message.success('已恢复到最近一次保存状态');
  }

  return {
    buildCurrentSnapshot,
    fixSelectedArea,
    loadStoreSettings,
    loadStores,
    resetBasicSettings,
    saveBasicSettings,
  };
}
