import { useCallback, useEffect, useState, type FormEvent } from 'react'
import { api, post, put, del } from '../../api'
import type { CustomField, FieldType } from '../../types'
import { useDialog } from '../../components/Dialog'
const TYPES: { key: FieldType; label: string }[] = [
{ key: 'text', label: '单行文本' }, { key: 'number', label: '数字' },
{ key: 'date', label: '日期' }, { key: 'select', label: '下拉选择' }, { key: 'textarea', label: '多行文本' },
]
export function FieldsTab() {
const dlg = useDialog()
const [list, setList] = useState<CustomField[]>([])
const [modal, setModal] = useState<CustomField | null | undefined>(undefined)
const load = useCallback(async () => {
const r = await api<{ list: CustomField[] }>('/api/admin/fields')
setList(r.list)
}, [])
useEffect(() => { load() }, [load])
async function remove(f: CustomField) {
if (!await dlg.confirm({ title: '删除字段', danger: true, message: `确认删除字段「${f.label}」?`, confirmText: '确认删除' })) return
try { await del(`/api/admin/fields/${f.id}`); dlg.toast({ message: '已删除', type: 'success' }); load() }
catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
}
async function toggle(f: CustomField) {
try { await put(`/api/admin/fields/${f.id}`, { ...f, enabled: !f.enabled }); load() }
catch (e: any) { dlg.toast({ message: e.message, type: 'error' }) }
}
return (
<div>
<div className="panel-head">
<div><h3>自定义字段</h3><p className="hint">字段配置后,新增/编辑客户表单会自动显示;也可用于 Excel 导入导出。</p></div>
<button className="btn btn-primary btn-sm" onClick={() => setModal(null)}>+ 新增字段</button>
</div>
<div className="table-wrap">
<table className="table">
<thead><tr><th>字段名称</th><th>标识</th><th>类型</th><th>选项</th><th>必填</th><th>启用</th><th style={{ width: 140 }}>操作</th></tr></thead>
<tbody>
{list.length === 0 && <tr><td colSpan={7} className="td-center empty">暂无自定义字段</td></tr>}
{list.map(f => (
<tr key={f.id}>
<td><b>{f.label}</b></td>
<td><code>{f.field_key}</code></td>
<td>{TYPES.find(t => t.key === f.field_type)?.label || f.field_type}</td>
<td>{f.options.join('、') || '-'}</td>
<td>{f.required ? '是' : '否'}</td>
<td><button className={`toggle ${f.enabled ? 'on' : ''}`} onClick={() => toggle(f)}>
<span />{f.enabled ? '启用' : '停用'}</button></td>
<td><div className="row-actions">
<button className="link" onClick={() => setModal(f)}>编辑</button>
<button className="link link-danger" onClick={() => remove(f)}>删除</button>
</div></td>
</tr>
))}
</tbody>
</table>
</div>
{modal !== undefined && <FieldModal field={modal}
onClose={() => setModal(undefined)} onSaved={() => { load(); setModal(undefined) }} />}
</div>
)
}
function FieldModal({ field, onClose, onSaved }: {
field: CustomField | null; onClose: () => void; onSaved: () => void
}) {
const [key, setKey] = useState(field?.field_key || '')
const [label, setLabel] = useState(field?.label || '')
const [type, setType] = useState<FieldType>(field?.field_type || 'text')
const [options, setOptions] = useState((field?.options || []).join(','))
const [required, setRequired] = useState(field?.required || false)
const [sort, setSort] = useState(field?.sort_order || 0)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
if (!key || !label) { setError('字段标识和名称必填'); return }
setBusy(true); setError('')
try {
const payload = {
field_key: key, label, field_type: type,
options: type === 'select' ? options.split(',').map(s => s.trim()).filter(Boolean) : [],
required, sort_order: Number(sort),
}
if (field) await put(`/api/admin/fields/${field.id}`, payload)
else await post('/api/admin/fields', payload)
onSaved()
} catch (err: any) { setError(err.message) }
finally { setBusy(false) }
}
return (
<div className="modal-backdrop" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<div className="modal" style={{ maxWidth: 480 }}>
<div className="modal-head"><h3>{field ? '编辑字段' : '新增字段'}</h3><button className="modal-x" onClick={onClose}>×</button></div>
<form onSubmit={submit} className="modal-body">
<div className="form-grid">
<label>字段名称 <em>*</em><input value={label} onChange={e => setLabel(e.target.value)} /></label>
<label>字段标识 <em>*</em><input value={key} onChange={e => setKey(e.target.value)} disabled={!!field} placeholder="如 contract_no" /></label>
</div>
<label>字段类型<select value={type} onChange={e => setType(e.target.value as FieldType)}>
{TYPES.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
</select></label>
{type === 'select' && <label>选项(英文逗号分隔)<input value={options} onChange={e => setOptions(e.target.value)} placeholder="选项A,选项B,选项C" /></label>}
<div className="form-grid">
<label className="check-line"><input type="checkbox" checked={required} onChange={e => setRequired(e.target.checked)} /> 必填字段</label>
<label>排序<input type="number" value={sort} onChange={e => setSort(Number(e.target.value))} /></label>
</div>
{error && <div className="form-error">{error}</div>}
<div className="modal-actions">
<button type="button" className="btn btn-ghost" onClick={onClose}>取消</button>
<button className="btn btn-primary" disabled={busy}>保存</button>
</div>
</form>
</div>
</div>
)
}