import { useEffect, useRef, useState } from 'react'
import { api, post, fileToBase64, download } from '../api'
import type { CustomField, Pool } from '../types'
import { useDialog } from '../components/Dialog'
function formatSize(bytes: number) {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
interface Row {
index: number; name: string; company?: string; phone?: string; email?: string
status?: string; source?: string; industry?: string; level?: string; region?: string; notes?: string
custom_data?: Record<string, string>
duplicate: { id?: number; name?: string; company?: string; field?: string } | null
}
export function ImportDialog({ fields, onClose, onDone }: {
fields: CustomField[]; onClose: () => void; onDone: () => void
}) {
const dlg = useDialog()
const fileRef = useRef<HTMLInputElement>(null)
const [rows, setRows] = useState<Row[] | null>(null)
const [strategy, setStrategy] = useState('skip')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [dragging, setDragging] = useState(false)
const [fileInfo, setFileInfo] = useState<{ name: string; size: number } | null>(null)
// 导入落点:false=导入到自己名下,true=导入到公海池
const [toPool, setToPool] = useState(false)
const [targetPool, setTargetPool] = useState('')
const [pools, setPools] = useState<Pool[]>([])
useEffect(() => {
api<{ list: Pool[] }>('/api/pools/mine').then(r => {
setPools(r.list)
if (!targetPool && r.list.length) setTargetPool(r.list[0].id)
}).catch(() => {})
}, [])
async function parse(file: File) {
if (!/\.(xlsx|xls|xlsm)$/i.test(file.name)) {
setError('请选择 .xlsx / .xls / .xlsm 格式的 Excel 文件'); return
}
if (file.size > 20 * 1024 * 1024) {
setError('文件超过 20MB,请拆分后再导入'); return
}
setError(''); setRows(null); setBusy(true); setFileInfo({ name: file.name, size: file.size })
try {
const b64 = await fileToBase64(file)
const r = await api<{ rows: Row[]; total: number; duplicates: number }>(
'/api/customers/import/check', { method: 'POST', body: { file_base64: b64 } })
setRows(r.rows)
} catch (err: any) { setError(err.message || '解析失败'); setFileInfo(null) }
finally { setBusy(false) }
}
async function onFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (file) await parse(file)
e.target.value = '' // 允许重复选同一个文件
}
async function commit() {
if (!rows) return
if (toPool && !targetPool) { setError('请选择目标公海池'); return }
setBusy(true); setError('')
try {
const r = await post<{ created: number; updated: number; skipped: number }>(
'/api/customers/import/commit', { rows, strategy, to_pool: toPool, target_pool: toPool ? targetPool : undefined })
onDone()
onClose()
dlg.toast({ message: `导入完成:新增 ${r.created},更新 ${r.updated},跳过 ${r.skipped}`, type: 'success' })
} catch (err: any) { setError(err.message) }
finally { setBusy(false) }
}
const dupCount = rows?.filter(r => r.duplicate).length || 0
return (
<div className="modal-backdrop" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<div className="modal import-modal" style={{ maxWidth: 820 }}>
<div className="modal-head">
<h3>批量导入客户</h3>
<button className="modal-x" onClick={onClose}>×</button>
</div>
{/* 步骤指示 */}
<div className="stepper">
<div className={`step ${rows ? 'done' : 'active'}`}>
<span className="step-num">{rows ? '✓' : '1'}</span><span>上传文件</span>
</div>
<div className="step-line" />
<div className={`step ${rows ? 'active' : ''}`}>
<span className="step-num">2</span><span>确认导入</span>
</div>
</div>
<div className="modal-body">
{/* 拖拽上传区 */}
<div
className={`dropzone ${dragging ? 'dragging' : ''} ${fileInfo ? 'has-file' : ''}`}
onDragOver={e => { e.preventDefault(); setDragging(true) }}
onDragLeave={() => setDragging(false)}
onDrop={e => { e.preventDefault(); setDragging(false); const f = e.dataTransfer.files?.[0]; if (f) parse(f) }}
onClick={() => fileRef.current?.click()}
>
<input ref={fileRef} type="file" accept=".xlsx,.xls,.xlsm" hidden onChange={onFile} />
{fileInfo ? (
<div className="file-card">
<div className="file-icon">▤</div>
<div className="file-meta">
<b>{fileInfo.name}</b>
<span>{formatSize(fileInfo.size)}{rows && ` · ${rows.length} 条数据`}</span>
</div>
<button className="btn btn-ghost btn-sm" onClick={e => { e.stopPropagation(); setFileInfo(null); setRows(null) }}>更换</button>
</div>
) : (
<>
<div className="drop-icon">⇪</div>
<div className="drop-title">{busy ? '正在解析…' : '拖拽 Excel 文件到这里,或点击选择'}</div>
<div className="drop-sub">支持 .xlsx / .xls / .xlsm,最大 20MB</div>
</>
)}
{busy && <div className="progress-bar"><span /></div>}
</div>
<div className="import-toolrow">
<button className="btn btn-ghost btn-sm" onClick={() => download('/api/customers/import/template', '客户导入模板.xlsx')}>↓ 下载导入模板</button>
<span className="hint">首行为表头,自动按 手机号/邮箱/姓名 查重{fields.length > 0 && `;可识别自定义列:${fields.map(f => f.label).join('、')}`}</span>
</div>
<div className="import-target">
<label className="target-line">
<input type="checkbox" checked={toPool} onChange={e => setToPool(e.target.checked)} />
<b>直接导入到公海池</b>
<span className="hint">不勾选则导入到你自己的客户名下</span>
</label>
{toPool && (
<label className="target-line">目标资源池
<select value={targetPool} onChange={e => setTargetPool(e.target.value)}>
{pools.map(p => <option key={p.id} value={p.id}>{p.name}({p.customer_count} 条)</option>)}
</select>
</label>
)}
</div>
{busy && <div className="td-center" style={{ padding: 20 }}>处理中…</div>}
{error && <div className="form-error">{error}</div>}
{rows && (
<>
<div className="import-summary">
<div className="mini-stats">
<div className="mini-stat"><span>总数据</span><b>{rows.length}</b></div>
<div className="mini-stat ok"><span>可导入</span><b>{rows.length - dupCount}</b></div>
<div className="mini-stat warn"><span>重复</span><b>{dupCount}</b></div>
</div>
<label className="strategy">重复处理:
<select value={strategy} onChange={e => setStrategy(e.target.value)}>
<option value="skip">跳过</option>
<option value="update">更新已有客户</option>
</select>
</label>
</div>
<div className="table-wrap" style={{ maxHeight: 320 }}>
<table className="table table-compact">
<thead><tr><th>姓名</th><th>公司</th><th>电话</th><th>状态</th><th>查重结果</th></tr></thead>
<tbody>{rows.map((r, i) => (
<tr key={i} className={r.duplicate ? 'row-dup' : ''}>
<td>{r.name}</td><td>{r.company || '-'}</td><td>{r.phone || '-'}</td>
<td>{r.status || 'lead'}</td>
<td>{r.duplicate ? <span className="dup-tag">重复:{r.duplicate.field || r.duplicate.name}</span> : <span className="ok-tag">新增</span>}</td>
</tr>
))}</tbody>
</table>
</div>
</>
)}
<div className="modal-actions">
<button className="btn btn-ghost" onClick={onClose}>取消</button>
<button className="btn btn-primary" disabled={!rows || busy} onClick={commit}>{busy ? '处理中…' : '确认导入'}</button>
</div>
</div>
</div>
</div>
)
}