import { computed, ref, watch } from 'vue' import { CHECKLIST_ITEMS, TRAINING_ROLES, itemsForRole, type TrainingRoleKey, } from './checklist-items' const STORAGE_CHECKED = 'oms.kb.training.checked.v1' const STORAGE_ROLE = 'oms.kb.training.role.v1' function readChecked(): Record { try { const raw = localStorage.getItem(STORAGE_CHECKED) if (!raw) return {} const parsed = JSON.parse(raw) as Record return parsed && typeof parsed === 'object' ? parsed : {} } catch { return {} } } function readRole(): TrainingRoleKey { try { const raw = localStorage.getItem(STORAGE_ROLE) // 兼容旧岗位键:渠道运营→运营,仓管→操作 const mapped = raw === 'channel' ? 'ops' : raw === 'warehouse' ? 'warehouse' : raw if (mapped && TRAINING_ROLES.some((r) => r.key === mapped)) { return mapped as TrainingRoleKey } } catch { // ignore } return 'all' } const checkedMap = ref>(readChecked()) const role = ref(readRole()) watch( checkedMap, (val) => { try { localStorage.setItem(STORAGE_CHECKED, JSON.stringify(val)) } catch { // ignore quota } }, { deep: true }, ) watch(role, (val) => { try { localStorage.setItem(STORAGE_ROLE, val) } catch { // ignore } }) export function useTrainingProgress() { const roleMeta = computed(() => TRAINING_ROLES.find((r) => r.key === role.value)!) const relevantItems = computed(() => itemsForRole(role.value)) const doneCount = computed( () => relevantItems.value.filter((i) => checkedMap.value[i.id]).length, ) const totalCount = computed(() => relevantItems.value.length) const percent = computed(() => totalCount.value ? Math.round((doneCount.value / totalCount.value) * 100) : 0, ) function isChecked(id: string) { return Boolean(checkedMap.value[id]) } function setChecked(id: string, value: boolean) { checkedMap.value = { ...checkedMap.value, [id]: value } } function toggle(id: string) { setChecked(id, !isChecked(id)) } function resetAll() { checkedMap.value = {} } function weekProgress(week: string) { const items = relevantItems.value.filter((i) => i.week === week) const done = items.filter((i) => checkedMap.value[i.id]).length return { done, total: items.length } } return { role, roleMeta, roles: TRAINING_ROLES, checkedMap, relevantItems, allItems: CHECKLIST_ITEMS, doneCount, totalCount, percent, isChecked, setChecked, toggle, resetAll, weekProgress, } }