import { useCallback, useEffect, useState } from 'react'
import { api, post, put, download } from '../../api'
import { useDialog } from '../../components/Dialog'
interface BackupConfig {
enabled: boolean
url: string
username: string
password: string
has_password: boolean
remote_dir: string
frequency: string
keep_count: number
last_backup_at: string | null
last_error: string | null
}
interface HistoryItem {
id: number
filename: string
size_bytes: number
trigger: string
status: string
stats: any
error: string | null
created_at: string
}
interface RemoteItem { name: string; size: number }
interface Preview {
exported_at: string
stats: any
pool_count: number
owner_groups: { owner_id: string; owner_name: string; count: number }[]
members: { id: string; display_name: string }[]
}
const FREQ_LABELS: Record<string, string> = {
off: '关闭', hourly: '每小时', '6hours': '每 6 小时', daily: '每天', weekly: '每周',
}
export function BackupTab() {
const dlg = useDialog()
const [cfg, setCfg] = useState<BackupConfig | null>(null)
const [history, setHistory] = useState<HistoryItem[]>([])
const [remote, setRemote] = useState<RemoteItem[]>([])
const [preview, setPreview] = useState<Preview | null>(null)
const [source, setSource] = useState<{ filename: string; snapshot?: any } | null>(null)
const [localName, setLocalName] = useState('')
const [dragging, setDragging] = useState(false)
const [busy, setBusy] = useState(false)
const [tab, setTab] = useState<'config' | 'history' | 'restore'>('config')
const load = useCallback(async () => {
try {
const [c, h] = await Promise.all([
api<{ config: BackupConfig }>('/api/admin/backup/config'),
api<{ list: HistoryItem[] }>('/api/admin/backup/history'),
])
setCfg(c.config); setHistory(h.list)
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
}, [dlg])
useEffect(() => { load() }, [load])
const loadRemote = async () => {
if (!cfg?.enabled) return
setBusy(true)
try {
const r = await api<{ list: RemoteItem[] }>('/api/admin/backup/remote')
setRemote(r.list)
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
finally { setBusy(false) }
}
async function saveConfig() {
if (!cfg) return
setBusy(true)
try {
await put('/api/admin/backup/config', {
enabled: cfg.enabled, url: cfg.url, username: cfg.username,
password: cfg.password, remote_dir: cfg.remote_dir,
frequency: cfg.frequency, keep_count: cfg.keep_count,
})
dlg.toast({ message: '备份配置已保存', type: 'success' })
load()
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
finally { setBusy(false) }
}
async function testConnection() {
if (!cfg) return
setBusy(true)
try {
await post('/api/admin/backup/test', {
url: cfg.url, username: cfg.username, password: cfg.password, remote_dir: cfg.remote_dir,
})
dlg.toast({ message: 'WebDAV 连接成功', type: 'success' })
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
finally { setBusy(false) }
}
async function runNow() {
setBusy(true)
try {
const r = await post<{ message: string }>('/api/admin/backup/run')
dlg.toast({ message: r.message, type: 'success' })
load()
if (tab === 'restore') loadRemote()
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
finally { setBusy(false) }
}
async function showPreview(filename: string) {
setBusy(true)
try {
const p = await post<Preview>('/api/admin/backup/preview', { filename })
setPreview(p); setSource({ filename })
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
finally { setBusy(false) }
}
async function doRestore(scope: string, ownerIds: string[], mode: string) {
if (!source) return
if (!await dlg.confirm({
title: '确认恢复数据', danger: mode === 'overwrite',
message: `确认从备份恢复数据?\n范围:${scope === 'full' ? '全部数据' : scope === 'pool' ? '仅公海客户' : '指定成员客户'}\n模式:${mode === 'overwrite' ? '覆盖(会清空对应现有数据)' : '合并(保留现有,按ID更新)'}\n\n建议先做一次当前数据备份。`,
confirmText: '确认恢复',
})) return
setBusy(true)
try {
const r = await post<{ message: string }>('/api/admin/backup/restore', {
filename: source.filename, snapshot: source.snapshot, scope, owner_ids: ownerIds, mode,
})
dlg.toast({ message: r.message, type: 'success' })
load()
setTimeout(() => window.location.reload(), 1500)
} catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
finally { setBusy(false) }
}
async function uploadLocal(file: File) {
if (!/\.json$/i.test(file.name)) { dlg.toast({ message: '请选择 .json 备份文件', type: 'error' }); return }
if (file.size > 50 * 1024 * 1024) { dlg.toast({ message: '备份文件超过 50MB', type: 'error' }); return }
setBusy(true)
try {
const text = await file.text()
const snap = JSON.parse(text)
if (!snap?.data || !Array.isArray(snap.data.customers)) throw new Error('不是有效的备份快照')
const p = await post<Preview>('/api/admin/backup/preview', { filename: '__local_upload__', snapshot: snap })
setPreview({ ...p, exported_at: snap.exported_at }); setSource({ filename: '__local_upload__', snapshot: snap })
setLocalName(file.name)
dlg.toast({ message: '本地备份已加载,请选择恢复范围', type: 'success' })
} catch (e: any) { dlg.toast({ message: `读取失败:${e.message}`, type: 'error' }) }
finally { setBusy(false) }
}
if (!cfg) return <div className="td-center" style={{ padding: 40 }}>加载中…</div>
return (
<div>
<div className="panel-head">
<div>
<h3>云端备份与恢复</h3>
<p className="hint">把数据快照备份到 WebDAV 网盘;网站崩溃后可在新机器安装本系统,登录 WebDAV 恢复数据。</p>
</div>
<button className="btn btn-primary btn-sm" onClick={runNow} disabled={busy}>立即备份</button>
</div>
<div className="tabs" style={{ margin: '0 20px' }}>
<button className={`tab ${tab === 'config' ? 'active' : ''}`} onClick={() => setTab('config')}>备份设置</button>
<button className={`tab ${tab === 'history' ? 'active' : ''}`} onClick={() => setTab('history')}>备份历史</button>
<button className={`tab ${tab === 'restore' ? 'active' : ''}`} onClick={() => { setTab('restore'); loadRemote() }}>恢复数据</button>
</div>
{/* ---------- 备份设置 ---------- */}
{tab === 'config' && (
<div className="settings-body">
<div className="setting-item">
<div><b>启用云端备份</b><p>开启后按设定频率自动备份到 WebDAV</p></div>
<label className="toggle-switch">
<input type="checkbox" checked={cfg.enabled} onChange={e => setCfg({ ...cfg, enabled: e.target.checked })} />
<span />
</label>
</div>
<label>WebDAV 地址
<input value={cfg.url} onChange={e => setCfg({ ...cfg, url: e.target.value })}
placeholder="https://dav.example.com/backup" />
</label>
<div className="form-grid">
<label>用户名<input value={cfg.username} onChange={e => setCfg({ ...cfg, username: e.target.value })} /></label>
<label>密码 / 授权码
<input type="password" value={cfg.password}
placeholder={cfg.has_password ? '已保存,留空则不修改' : '输入密码'}
onChange={e => setCfg({ ...cfg, password: e.target.value })} />
</label>
</div>
<label>远端目录(可选)<input value={cfg.remote_dir} onChange={e => setCfg({ ...cfg, remote_dir: e.target.value })} placeholder="/crm-backup" /></label>
<div className="form-grid">
<label>自动备份频率
<select value={cfg.frequency} onChange={e => setCfg({ ...cfg, frequency: e.target.value })}>
{Object.entries(FREQ_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
</label>
<label>云端保留份数
<input type="number" min="1" max="100" value={cfg.keep_count}
onChange={e => setCfg({ ...cfg, keep_count: Number(e.target.value) })} />
</label>
</div>
{cfg.last_backup_at && <p className="hint">上次备份:{new Date(cfg.last_backup_at).toLocaleString('zh-CN')}</p>}
{cfg.last_error && <div className="form-error">上次失败:{cfg.last_error}</div>}
<div className="modal-actions" style={{ justifyContent: 'flex-start' }}>
<button className="btn btn-ghost" onClick={testConnection} disabled={busy || !cfg.url}>测试连接</button>
<button className="btn btn-primary" onClick={saveConfig} disabled={busy}>保存配置</button>
<button className="btn btn-ghost" onClick={() => download('/api/admin/backup/snapshot', 'crm-snapshot.json')} disabled={busy}>下载本地快照</button>
</div>
<p className="hint" style={{ marginTop: 14 }}>
密码使用 AES 加密存储。支持坚果云、OneDrive、Nextcloud 等标准 WebDAV 服务;坚果云请用「应用密码」而非登录密码。
</p>
</div>
)}
{/* ---------- 备份历史 ---------- */}
{tab === 'history' && (
<div className="table-wrap">
<table className="table">
<thead><tr><th>时间</th><th>文件名</th><th>大小</th><th>方式</th><th>客户数</th><th>状态</th></tr></thead>
<tbody>
{history.length === 0 && <tr><td colSpan={6} className="td-center empty">暂无备份记录</td></tr>}
{history.map(h => (
<tr key={h.id}>
<td className="nowrap">{new Date(h.created_at).toLocaleString('zh-CN')}</td>
<td><code>{h.filename}</code></td>
<td>{h.size_bytes ? (h.size_bytes / 1024).toFixed(1) + ' KB' : '-'}</td>
<td>{h.trigger === 'auto' ? '定时' : '手动'}</td>
<td>{h.stats?.customers ?? '-'}</td>
<td>{h.status === 'success'
? <span className="ok-tag">成功</span>
: <span className="dup-tag" title={h.error || ''}>失败</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* ---------- 恢复数据 ---------- */}
{tab === 'restore' && (
<div className="settings-body">
<div className="restore-source">
<div>
<b>选择备份来源</b>
<p className="hint">从云端列表选择,或将本地 JSON 快照拖到下方(换机器时用)</p>
</div>
</div>
<div
className={`dropzone dropzone-sm ${dragging ? 'dragging' : ''}`}
onDragOver={e => { e.preventDefault(); setDragging(true) }}
onDragLeave={() => setDragging(false)}
onDrop={e => { e.preventDefault(); setDragging(false); const f = e.dataTransfer.files?.[0]; if (f) uploadLocal(f) }}
onClick={() => document.getElementById('local-backup-input')?.click()}
>
<input id="local-backup-input" type="file" accept=".json" hidden
onChange={e => { e.target.files?.[0] && uploadLocal(e.target.files[0]); e.target.value = '' }} />
{localName ? (
<div className="file-card file-card-sm">
<div className="file-icon">▤</div>
<div className="file-meta"><b>{localName}</b><span>本地备份 · 已加载</span></div>
<button className="btn btn-ghost btn-sm" onClick={e => { e.stopPropagation(); setLocalName(''); setPreview(null); setSource(null) }}>更换</button>
</div>
) : (
<>
<div className="drop-icon">⇪</div>
<div className="drop-title">拖拽本地备份文件,或点击选择</div>
<div className="drop-sub">支持 .json 快照,最大 50MB</div>
</>
)}
{busy && <div className="progress-bar"><span /></div>}
</div>
{busy && <div className="td-center" style={{ padding: 20 }}>处理中…</div>}
{!preview && !busy && (
<div className="cloud-list">
{remote.length === 0
? <div className="empty-mini">云端暂无备份文件,先点「立即备份」</div>
: remote.map(item => (
<div className="cloud-item" key={item.name}>
<span className="cloud-file">☁ {item.name}</span>
<span className="muted">{(item.size / 1024).toFixed(1)} KB</span>
<button className="btn btn-ghost btn-sm" onClick={() => showPreview(item.name)}>选择</button>
</div>
))}
</div>
)}
{preview && (
<div className="preview-card">
<div className="preview-head">
<div>
<b>备份预览</b>
<span className="muted"> 导出于 {new Date(preview.exported_at).toLocaleString('zh-CN')}</span>
</div>
<button className="btn btn-ghost btn-sm" onClick={() => { setPreview(null); setSource(null) }}>重新选择</button>
</div>
<div className="preview-stats">
<div>客户 <b>{preview.stats?.customers ?? 0}</b></div>
<div>公海 <b>{preview.pool_count}</b></div>
<div>负责人 <b>{preview.owner_groups.length}</b> 组</div>
<div>跟进 <b>{preview.stats?.follow_ups ?? 0}</b></div>
</div>
<div className="preview-groups">
<div className="group-line"><span className="pool-tag">公海</span> {preview.pool_count} 个客户</div>
{preview.owner_groups.map(g => (
<div className="group-line" key={g.owner_id}>
<span className="owner-tag">{g.owner_name}</span> {g.count} 个客户
</div>
))}
</div>
<RestorePanel preview={preview} busy={busy}
onRestore={(scope, ownerIds, mode) => doRestore(scope, ownerIds, mode)} />
</div>
)}
</div>
)}
</div>
)
}
/** 恢复范围选择面板 */
function RestorePanel({ preview, busy, onRestore }: {
preview: Preview; busy: boolean
onRestore: (scope: string, ownerIds: string[], mode: string) => void
}) {
const [scope, setScope] = useState('full')
const [selectedOwners, setSelectedOwners] = useState<string[]>([])
const [mode, setMode] = useState('merge')
function toggleOwner(id: string) {
setSelectedOwners(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
}
return (
<div className="restore-panel">
<div className="section-subtitle">恢复范围</div>
<div className="scope-options">
<label className={`scope-opt ${scope === 'full' ? 'active' : ''}`}>
<input type="radio" checked={scope === 'full'} onChange={() => setScope('full')} />
全部数据(含成员、角色、字段、客户、跟进、日志)
</label>
<label className={`scope-opt ${scope === 'pool' ? 'active' : ''}`}>
<input type="radio" checked={scope === 'pool'} onChange={() => setScope('pool')} />
仅公海客户({preview.pool_count} 个)
</label>
<label className={`scope-opt ${scope === 'owner' ? 'active' : ''}`}>
<input type="radio" checked={scope === 'owner'} onChange={() => setScope('owner')} />
指定负责人的客户(可多选)
</label>
</div>
{scope === 'owner' && (
<div className="owner-picker">
{preview.owner_groups.map(g => (
<label key={g.owner_id} className="check-item">
<input type="checkbox" checked={selectedOwners.includes(g.owner_id)}
onChange={() => toggleOwner(g.owner_id)} />
{g.owner_name}({g.count} 个)
</label>
))}
</div>
)}
<div className="section-subtitle" style={{ marginTop: 16 }}>恢复模式</div>
<div className="scope-options">
<label className={`scope-opt ${mode === 'merge' ? 'active' : ''}`}>
<input type="radio" checked={mode === 'merge'} onChange={() => setMode('merge')} />
合并(推荐):保留现有数据,按 ID 更新
</label>
<label className={`scope-opt ${mode === 'overwrite' ? 'active' : ''}`}>
<input type="radio" checked={mode === 'overwrite'} onChange={() => setMode('overwrite')} />
覆盖:先清空对应数据再导入(谨慎)
</label>
</div>
<div className="modal-actions" style={{ justifyContent: 'flex-start' }}>
<button className="btn btn-primary" disabled={busy || (scope === 'owner' && selectedOwners.length === 0)}
onClick={() => onRestore(scope, selectedOwners, mode)}>
开始恢复
</button>
</div>
</div>
)
}