import { type Ref, ref, watch } from 'vue' import type { LocationResult } from '@/lib/location' import { getPointSignInfoApi } from '@/services/modules/task/taskVisit' import type { PointSignInfoItem } from '@/services/modules/task/taskVisit/type' import type { VisitTarget, VisitTargetType } from '../types' import { getDistanceInMeters } from '../utils/distance' const TARGET_TYPE_MAP: Record = { '1': 'hospital', '2': 'company', '3': 'pharmacy', } export const useVisitTargets = (currentLocation: Ref) => { const targets = ref([]) const loading = ref(false) const errorMessage = ref('') const loadTargets = async () => { const location = currentLocation.value if (!location) { targets.value = [] return } loading.value = true errorMessage.value = '' try { const res = await getPointSignInfoApi({ latitude: location.latitude, longitude: location.longitude, }) targets.value = (Array.isArray(res.data) ? res.data : []) .map((item) => normalizeTarget(item, location)) .filter((item): item is VisitTarget => item !== null) .sort((left, right) => left.distanceMeters - right.distanceMeters) } catch (error) { errorMessage.value = error instanceof Error ? error.message : '获取附近拜访对象失败' } finally { loading.value = false } } watch( () => [currentLocation.value?.latitude, currentLocation.value?.longitude] as const, () => void loadTargets(), { immediate: true } ) return { targets, loading, errorMessage, loadTargets } } const normalizeTarget = ( item: PointSignInfoItem, currentLocation: LocationResult ): VisitTarget | null => { const type = TARGET_TYPE_MAP[String(item.signEntType)] const latitude = Number(item.latitude) const longitude = Number(item.longitude) if (!type || !Number.isFinite(latitude) || !Number.isFinite(longitude)) return null const distanceMeters = getDistanceInMeters( currentLocation.longitude, currentLocation.latitude, longitude, latitude ) return { id: `${type}-${item.signEntId}`, signEntId: String(item.signEntId), signEntType: String(item.signEntType), type, name: item.signEntName || '未命名拜访地点', address: item.address || '暂无详细地址', latitude, longitude, entLatitude: item.latitude, entLongitude: item.longitude, distanceMeters, } }