import { ref } from 'vue' import { autoSetModeCallback, createTemploraryID } from './sys' import { fetchGuidePaths, postAddGuidePath, postUpdateGuidePath, postDeleteGuidePath, uploadFile, } from '@/api' import { deleteStoreItem, addStoreItem, updateStoreItem, saveStoreItems, recoverStoreItems } from '@/utils' import type { GuidePath as SGuidePath } from '@/api' import type { Guide } from './guide' export type GuidePath = LocalMode export type GuidePaths = GuidePath[] export const guidePaths = ref([]) export const getGuidePaths = (guide: Guide) => guidePaths.value.filter(path => path.guideId === guide.id) export const createGuidePath = (path: Partial = {}): GuidePath => ({ id: createTemploraryID(), guideId: '', cover: '', time: 1, sort: 999, speed: 1, position: {x: 0, y: 0, z: 0}, target: {x: 0, y: 0, z: 0}, ...path }) let bcPaths: GuidePaths = [] export const getBackupGuidePaths = () => bcPaths export const backupGuidePaths = () => { bcPaths = guidePaths.value.map(path => ({ ...path })) } export const transformGuidePath = async (path: GuidePath): Promise => { const cover: string = await uploadFile(path.cover) return { ...path, cover } } export const recoverGuidePaths = recoverStoreItems(guidePaths, getBackupGuidePaths) export const addGuidePath = addStoreItem(guidePaths, postAddGuidePath, transformGuidePath) export const updateGuidePath = updateStoreItem(guidePaths, postUpdateGuidePath, transformGuidePath) export const deleteGuidePath = deleteStoreItem(guidePaths, path => postDeleteGuidePath(path.id)) export const initialGuidePathsByGuide = async (guide: Guide) => { const paths = await fetchGuidePaths(guide.id) guidePaths.value = guidePaths.value .filter(path => path.guideId !== guide.id) .concat(paths) backupGuidePaths() } const _saveGuidePaths = saveStoreItems( guidePaths, getBackupGuidePaths, { add: addGuidePath, update: updateGuidePath, delete: deleteGuidePath, } ) export const saveGuidePaths = async () => { await _saveGuidePaths() backupGuidePaths() const sortMaps = new Map() guidePaths.value.forEach((path) => { const sort = (sortMaps.get(path.guideId) || 0) + 1 path.sort = sort sortMaps.set(path.guideId, sort) }) console.log(guidePaths.value) await _saveGuidePaths() } export const autoSaveGuidePaths = autoSetModeCallback(guidePaths, { backup: backupGuidePaths, recovery: recoverGuidePaths, save: saveGuidePaths, })