/**
 * 门店列表页面主编排：
 * - 维护页面状态
 * - 组合数据与动作模块
 * - 对外暴露组件可消费的数据与方法
 */
import type {
  DrawerMode,
  PagePaginationState,
  StatCardItem,
  StoreFilterState,
  StoreFormState,
  StoreTablePagination,
} from '../types';

import type {
  ServiceType,
  StoreAuditStatus,
  StoreBusinessStatus,
  StoreListItemDto,
  StoreStatsDto,
} from '#/api/store';

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

import {
  auditStatusMap,
  auditStatusOptions,
  businessStatusMap,
  businessStatusOptions,
  columns,
  DEFAULT_FILTERS,
  DEFAULT_FORM_STATE,
  DEFAULT_PAGINATION,
  DEFAULT_STATS,
  geoStatusMap,
  serviceTypeMap,
  serviceTypeOptions,
  THEME_COLORS,
} from './store-list-page/constants';
import { createDataActions } from './store-list-page/data-actions';
import { createDrawerActions } from './store-list-page/drawer-actions';
import { getAvatarColor } from './store-list-page/helpers';
import { createListActions } from './store-list-page/list-actions';

export function useStoreListPage() {
  // 1. 列表与筛选状态。
  const isLoading = ref(false);
  const storeList = ref<StoreListItemDto[]>([]);
  const stats = ref<StoreStatsDto>({ ...DEFAULT_STATS });
  const pagination = reactive<PagePaginationState>({ ...DEFAULT_PAGINATION });
  const filters = reactive<StoreFilterState>({ ...DEFAULT_FILTERS });

  // 2. 抽屉与表单状态。
  const isDrawerVisible = ref(false);
  const drawerMode = ref<DrawerMode>('create');
  const formState = reactive<StoreFormState>({
    ...DEFAULT_FORM_STATE,
    serviceTypes: [...DEFAULT_FORM_STATE.serviceTypes],
  });
  const isSubmitting = ref(false);

  // 3. 视图衍生数据。
  const drawerTitle = computed(() =>
    drawerMode.value === 'edit' ? '编辑门店' : '添加门店',
  );

  const statCards = computed<StatCardItem[]>(() => [
    { color: THEME_COLORS.text, title: '门店总数', value: stats.value.total },
    {
      color: THEME_COLORS.success,
      title: '营业中',
      value: stats.value.operating,
    },
    {
      color: THEME_COLORS.warning,
      title: '休息中',
      value: stats.value.resting,
    },
    {
      color: THEME_COLORS.danger,
      title: '待审核',
      value: stats.value.pendingAudit,
    },
  ]);

  const tablePagination = computed<StoreTablePagination>(() => ({
    current: pagination.current,
    pageSize: pagination.pageSize,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
    total: pagination.total,
  }));

  // 4. 组装数据加载动作。
  const { loadList, loadStats } = createDataActions({
    filters,
    isLoading,
    pagination,
    stats,
    storeList,
  });

  // 5. 组装列表交互动作。
  const { handleReset, handleSearch, handleTableChange } = createListActions({
    filters,
    loadList,
    pagination,
  });

  // 6. 组装抽屉与删除动作。
  const {
    handleDelete,
    handleRetryGeocode,
    handleSubmit,
    handleToggleBusinessStatus,
    openDrawer,
  } = createDrawerActions({
    drawerMode,
    formState,
    isDrawerVisible,
    isSubmitting,
    loadList,
    loadStats,
  });

  // 7. 筛选字段更新方法。
  function setKeyword(value: string) {
    filters.keyword = value;
  }

  function setBusinessStatus(value?: StoreBusinessStatus) {
    filters.businessStatus = value;
  }

  function setAuditStatus(value?: StoreAuditStatus) {
    filters.auditStatus = value;
  }

  function setServiceType(value?: ServiceType) {
    filters.serviceType = value;
  }

  // 8. 抽屉表单字段更新方法。
  function setDrawerVisible(value: boolean) {
    isDrawerVisible.value = value;
  }

  function setFormName(value: string) {
    formState.name = value;
  }

  function setFormContactPhone(value: string) {
    formState.contactPhone = value;
  }

  function setFormManagerName(value: string) {
    formState.managerName = value;
  }

  function setFormAddress(value: string) {
    formState.address = value;
  }

  function setFormServiceTypes(value: ServiceType[]) {
    formState.serviceTypes = value;
  }

  // 9. 抽屉便捷入口。
  function openCreateDrawer() {
    openDrawer('create');
  }

  function openEditDrawer(record: StoreListItemDto) {
    openDrawer('edit', record);
  }

  // 10. 页面初始化。
  onMounted(() => {
    loadList();
    loadStats();
  });

  return {
    auditStatusMap,
    auditStatusOptions,
    businessStatusMap,
    businessStatusOptions,
    columns,
    drawerTitle,
    filters,
    formState,
    getAvatarColor,
    handleDeleteStore: handleDelete,
    handleRetryStoreGeocode: handleRetryGeocode,
    handleToggleStoreBusinessStatus: handleToggleBusinessStatus,
    handleReset,
    handleSearch,
    handleSubmitStore: handleSubmit,
    handleTableChange,
    isDrawerVisible,
    isLoading,
    isSubmitting,
    openCreateDrawer,
    openEditDrawer,
    pagination,
    geoStatusMap,
    serviceTypeMap,
    serviceTypeOptions,
    setAuditStatus,
    setBusinessStatus,
    setDrawerVisible,
    setFormAddress,
    setFormContactPhone,
    setFormManagerName,
    setFormName,
    setFormServiceTypes,
    setKeyword,
    setServiceType,
    statCards,
    storeList,
    tablePagination,
  };
}
