import {useCallback,useEffect,useRef,useState} from 'react'; import {AppState,Platform} from 'react-native'; import * as SecureStore from 'expo-secure-store'; import {createDraftStore} from '../core/drafts'; import {Dialog} from '../dialogs'; const store=createDraftStore({ get:async key=>Platform.OS==='web'?localStorage.getItem(key):SecureStore.getItemAsync(key), set:async(key,value)=>{if(Platform.OS==='web')localStorage.setItem(key,value);else await SecureStore.setItemAsync(key,value);}, remove:async key=>{if(Platform.OS==='web')localStorage.removeItem(key);else await SecureStore.deleteItemAsync(key);} }); type Options={scope?:string;kind:string;id:string|number;value:T;onRestore:(value:T)=>void;enabled?:boolean;suspendAutosave?:boolean;hasContent?:(value:T)=>boolean;isPending?:(value:T)=>boolean}; export function useOperationDraft({scope,kind,id,value,onRestore,enabled=true,suspendAutosave=false,hasContent,isPending}:Options){ const active=!!scope&&enabled,[ready,setReady]=useState(!active),[restored,setRestored]=useState(false),[error,setError]=useState(''); const latest=useRef(value),restore=useRef(onRestore),content=useRef(hasContent),pending=useRef(isPending),cleared=useRef(false),live=useRef(true),readyRef=useRef(!active); const explicit=useRef<{value:T;fingerprint:string}|null>(null); const fingerprint=JSON.stringify(value); // An autosave scheduled before submit must never overwrite the durable // "pending" snapshot while React is still committing its new state. if(explicit.current?.fingerprint===fingerprint)explicit.current=null; latest.current=value;restore.current=onRestore;content.current=hasContent;pending.current=isPending; const saveNow=useCallback(async(override?:T)=>{ if(!active||!scope||cleared.current)return; if(override!==undefined)explicit.current={value:override,fingerprint:JSON.stringify(override)}; const next=override===undefined?(explicit.current?.value??latest.current):override; if(!readyRef.current)throw new Error('请先处理恢复草稿提示'); if(content.current&&!content.current(next))return; try{await store.save(scope,kind,id,next);if(live.current)setError('');} catch(e){if(live.current)setError('草稿未保存:'+(e instanceof Error?e.message:'请检查手机存储空间'));throw e;} },[active,scope,kind,id]); const clear=useCallback(async()=>{if(!scope||!active)return;cleared.current=true;await store.clear(scope,kind,id);if(live.current){setRestored(false);setError('');}},[scope,active,kind,id]); useEffect(()=>{ live.current=true;cleared.current=false;readyRef.current=!active;setReady(!active);setRestored(false);let alive=true; if(active&&scope)void store.load(scope,kind,id).then(saved=>{ if(!alive)return; const finish=()=>{readyRef.current=true;setReady(true);}; if(!saved){finish();return;} const uncertain=pending.current?.(saved.value)===true; Dialog.alert(uncertain?'有待核对的提交':'继续上次填写?',uncertain?'上次提交结果尚待核对。恢复后请先核对记录;重试会保留原请求标识,不会创建另一笔。':'已保留上次填写的内容,尚未自动提交业务。',[ ...(!uncertain?[{text:'丢弃草稿',style:'destructive' as const,onPress:()=>{void store.clear(scope,kind,id).then(()=>{if(alive)finish();}).catch(e=>{if(alive)setError(e.message);});}}]:[]), {text:uncertain?'恢复并核对':'继续填写',onPress:()=>{if(!alive)return;restore.current(saved.value);setRestored(true);finish();}} ]); }).catch(e=>{if(alive)setError(e instanceof Error?e.message:'无法读取草稿,请核对业务记录后重试');}); return()=>{alive=false;live.current=false;}; },[active,scope,kind,id]); useEffect(()=>{if(!ready||!active||suspendAutosave||cleared.current)return;const timer=setTimeout(()=>{void saveNow().catch(()=>{});},350);return()=>clearTimeout(timer);},[fingerprint,ready,active,suspendAutosave,saveNow]); useEffect(()=>{if(!active)return;const sub=AppState.addEventListener('change',state=>{if(state!=='active'&&readyRef.current)void saveNow().catch(()=>{});});return()=>{sub.remove();if(readyRef.current&&!cleared.current)void saveNow().catch(()=>{});};},[active,saveNow]); return {ready,restored,error,clear,saveNow}; }