import type { Ref } from 'vue';

import type { ProductPickerItemDto, ProductScheduleDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';
import type { ScheduleProductLookup } from '#/views/product/schedule/types';

/**
 * 文件职责：时段供应数据加载动作。
 */
import { message } from 'ant-design-vue';

import {
  getProductScheduleListApi,
  searchProductPickerApi,
} from '#/api/product';
import { getStoreListApi } from '#/api/store';

interface CreateDataActionsOptions {
  isLoading: Ref<boolean>;
  isPickerLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  pickerKeyword: Ref<string>;
  pickerProducts: Ref<ProductPickerItemDto[]>;
  productLookup: Ref<ScheduleProductLookup>;
  rows: Ref<ProductScheduleDto[]>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  function mergeProductLookup(list: ProductPickerItemDto[]) {
    if (list.length === 0) return;

    const next: ScheduleProductLookup = {
      ...options.productLookup.value,
    };
    for (const item of list) {
      next[item.id] = item;
    }

    options.productLookup.value = next;
  }

  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 = [];
        options.pickerProducts.value = [];
        options.productLookup.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 loadSchedules() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      return;
    }

    options.isLoading.value = true;
    try {
      const list = await getProductScheduleListApi({
        storeId: options.selectedStoreId.value,
      });
      options.rows.value = list.toSorted((a, b) =>
        a.name.localeCompare(b.name),
      );
    } catch (error) {
      console.error(error);
      options.rows.value = [];
      message.error('加载时段规则失败');
    } finally {
      options.isLoading.value = false;
    }
  }

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

    options.isPickerLoading.value = true;
    try {
      const list = await searchProductPickerApi({
        storeId: options.selectedStoreId.value,
        keyword: options.pickerKeyword.value.trim() || undefined,
        limit: 500,
      });
      options.pickerProducts.value = list;
      mergeProductLookup(list);
    } catch (error) {
      console.error(error);
      options.pickerProducts.value = [];
      message.error('加载商品失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  async function preloadProductLookup() {
    if (!options.selectedStoreId.value) {
      options.pickerProducts.value = [];
      options.productLookup.value = {};
      return;
    }

    try {
      const list = await searchProductPickerApi({
        storeId: options.selectedStoreId.value,
        limit: 500,
      });
      options.pickerProducts.value = list;
      mergeProductLookup(list);
    } catch (error) {
      console.error(error);
    }
  }

  return {
    loadPickerProducts,
    loadSchedules,
    loadStores,
    preloadProductLookup,
  };
}
