/**
 * 门店列表页纯函数工具：
 * - 颜色计算
 * - 过滤与表单重置
 * - 保存参数转换
 */
import type { StoreFilterState, StoreFormState } from '../../types';

import type { SaveStoreDto, StoreListItemDto } from '#/api/store';

import {
  AVATAR_COLORS,
  DEFAULT_FILTERS,
  DEFAULT_FORM_STATE,
} from './constants';

/** 获取门店头像装饰色。 */
export function getAvatarColor(index: number) {
  return AVATAR_COLORS[index % AVATAR_COLORS.length] ?? AVATAR_COLORS[0];
}

/** 重置筛选条件为默认值。 */
export function resetFilters(filters: StoreFilterState) {
  Object.assign(filters, DEFAULT_FILTERS);
}

/** 重置抽屉表单为默认值。 */
export function resetStoreForm(formState: StoreFormState) {
  Object.assign(formState, {
    ...DEFAULT_FORM_STATE,
    serviceTypes: [...DEFAULT_FORM_STATE.serviceTypes],
  });
}

/** 按门店记录回填抽屉表单。 */
export function applyRecordToForm(
  formState: StoreFormState,
  store: StoreListItemDto,
) {
  Object.assign(formState, {
    address: store.address,
    contactPhone: store.contactPhone,
    coverImage: store.coverImage || '',
    id: store.id,
    managerName: store.managerName,
    name: store.name,
    serviceTypes: [...store.serviceTypes],
  });
}

/** 将表单状态转换为保存接口参数。 */
export function toSavePayload(formState: StoreFormState): SaveStoreDto {
  return {
    address: formState.address.trim(),
    contactPhone: formState.contactPhone.trim(),
    coverImage: formState.coverImage.trim(),
    id: formState.id || undefined,
    managerName: formState.managerName.trim(),
    name: formState.name.trim(),
    serviceTypes: [...formState.serviceTypes],
  };
}
