import type { Ref } from 'vue';

import type { ProductSpecDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';

/**
 * 文件职责：规格做法页面数据动作。
 * 1. 加载门店列表与模板列表。
 * 2. 维护门店切换时的数据一致性。
 */
import { message } from 'ant-design-vue';

import { getProductSpecListApi } from '#/api/product';
import { getStoreListApi } from '#/api/store';

interface CreateDataActionsOptions {
  isLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  keyword: Ref<string>;
  rows: Ref<ProductSpecDto[]>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];
      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        options.rows.value = [];
        return;
      }

      const hasSelected = options.stores.value.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!hasSelected) {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadSpecs() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      return;
    }

    options.isLoading.value = true;
    try {
      const list = await getProductSpecListApi({
        storeId: options.selectedStoreId.value,
        keyword: options.keyword.value.trim() || undefined,
      });
      options.rows.value = list;
    } catch (error) {
      console.error(error);
      options.rows.value = [];
      message.error('加载模板失败');
    } finally {
      options.isLoading.value = false;
    }
  }

  return {
    loadSpecs,
    loadStores,
  };
}
