import type { Ref } from 'vue';

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

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

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

interface CreateDataActionsOptions {
  isLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  rows: Ref<ProductLabelDto[]>;
  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 loadLabels() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      return;
    }

    options.isLoading.value = true;
    try {
      const list = await getProductLabelListApi({
        storeId: options.selectedStoreId.value,
      });
      options.rows.value = list.toSorted((a, b) => a.sort - b.sort);
    } catch (error) {
      console.error(error);
      options.rows.value = [];
      message.error('加载标签失败');
    } finally {
      options.isLoading.value = false;
    }
  }

  return {
    loadLabels,
    loadStores,
  };
}
