| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234 |
- 'use client';
- import { useState } from 'react';
- import { X, Upload, FileText, CheckCircle2, AlertCircle, Sparkles } from 'lucide-react';
- import { toast } from 'react-hot-toast';
- import api from '@/lib/api';
- import { DynamicConfiguration } from '@/types';
- interface ConfigurationImportModalProps {
- isOpen: boolean;
- onClose: () => void;
- onSuccess: () => void;
- existingKeys: string[];
- }
- export default function ConfigurationImportModal({
- isOpen,
- onClose,
- onSuccess,
- existingKeys,
- }: ConfigurationImportModalProps) {
- const [jsonInput, setJsonInput] = useState('');
- const [overwrite, setOverwrite] = useState(true);
- const [submitting, setSubmitting] = useState(false);
- if (!isOpen) return null;
- let parsedList: DynamicConfiguration[] = [];
- let parseError: string | null = null;
- if (jsonInput.trim()) {
- try {
- const data = JSON.parse(jsonInput);
- if (Array.isArray(data)) {
- parsedList = data
- .filter((item) => item && typeof item === 'object' && item.config_key)
- .map((item) => ({
- config_key: String(item.config_key).trim(),
- config_value:
- typeof item.config_value === 'string'
- ? item.config_value
- : JSON.stringify(item.config_value ?? ''),
- description: String(item.description || ''),
- type: String(item.type || 'json'),
- }));
- } else if (typeof data === 'object' && data !== null) {
- if (data.config_key) {
- parsedList = [
- {
- config_key: String(data.config_key).trim(),
- config_value:
- typeof data.config_value === 'string'
- ? data.config_value
- : JSON.stringify(data.config_value ?? ''),
- description: String(data.description || ''),
- type: String(data.type || 'json'),
- },
- ];
- } else {
- parsedList = Object.entries(data).map(([k, v]) => ({
- config_key: k.trim(),
- config_value: typeof v === 'string' ? v : JSON.stringify(v),
- description: '',
- type: typeof v === 'object' ? 'json' : typeof v,
- }));
- }
- }
- } catch (e: any) {
- parseError = e.message;
- }
- }
- const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = (event) => {
- const content = event.target?.result as string;
- setJsonInput(content);
- };
- reader.readAsText(file);
- };
- const handleImport = async () => {
- if (parsedList.length === 0) {
- toast.error('无可导入的有效配置数据');
- return;
- }
- setSubmitting(true);
- let successCount = 0;
- let skipCount = 0;
- try {
- for (const item of parsedList) {
- const isExists = existingKeys.includes(item.config_key);
- if (isExists && !overwrite) {
- skipCount++;
- continue;
- }
- try {
- if (isExists && overwrite) {
- await api.put(`/api/dynamic-configurations/key/${encodeURIComponent(item.config_key)}`, {
- config_value: item.config_value,
- description: item.description || undefined,
- type: item.type || undefined,
- });
- successCount++;
- } else if (!isExists) {
- await api.post('/api/dynamic-configurations', {
- config_key: item.config_key,
- config_value: item.config_value,
- description: item.description || undefined,
- type: item.type || undefined,
- });
- successCount++;
- }
- } catch {
- skipCount++;
- }
- }
- toast.success(`导入完成: 成功 ${successCount} 项, 跳过 ${skipCount} 项`);
- onClose();
- onSuccess();
- } catch {
- toast.error('导入过程中发生错误');
- } finally {
- setSubmitting(false);
- }
- };
- return (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-grayscale p-4 font-mono">
- <div className="bg-neutral-50 border-2 border-black shadow-[8px_8px_0px_#000] w-full max-w-xl overflow-hidden animate-in zoom-in-95 duration-200">
- {/* Header */}
- <div className="px-5 py-3.5 border-b-2 border-black flex justify-between items-center bg-neutral-200 text-black select-none">
- <div className="flex items-center gap-2">
- <span className="w-2.5 h-2.5 bg-amber-300 border border-black inline-block" />
- <h3 className="font-black text-black text-xs md:text-sm uppercase tracking-wider">
- [ IMPORT CONFIGURATIONS // 导入配置数据 ]
- </h3>
- </div>
- <button
- onClick={onClose}
- className="w-6 h-6 bg-white hover:bg-amber-300 border border-black flex items-center justify-center font-bold text-xs transition"
- >
- ✕
- </button>
- </div>
- {/* Body */}
- <div className="p-5 space-y-4 max-h-[70vh] overflow-y-auto bg-white text-xs">
- {/* File Upload Zone */}
- <div className="border-2 border-dashed border-black hover:bg-amber-50 p-4 text-center transition bg-neutral-50 relative cursor-pointer">
- <input
- type="file"
- accept=".json"
- onChange={handleFileUpload}
- className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
- />
- <div className="flex flex-col items-center justify-center space-y-1">
- <Upload className="w-5 h-5 text-black mb-0.5" />
- <p className="text-xs font-bold text-black uppercase">[ 点击选择 JSON 配置文件或拖拽入此区域 ]</p>
- <p className="text-[10px] text-neutral-500">支持 configurations_backup.json</p>
- </div>
- </div>
- {/* Textarea Paste */}
- <div className="space-y-1">
- <label className="font-bold uppercase text-black flex justify-between">
- <span>[ 或直接粘贴 JSON 内容 ]</span>
- {parseError ? (
- <span className="text-rose-700 font-bold flex items-center gap-1">
- <AlertCircle size={12} /> {parseError}
- </span>
- ) : parsedList.length > 0 ? (
- <span className="text-black font-bold">
- ★ 已成功解析 {parsedList.length} 项配置
- </span>
- ) : null}
- </label>
- <textarea
- rows={6}
- value={jsonInput}
- onChange={(e) => setJsonInput(e.target.value)}
- placeholder={`[\n {\n "config_key": "EXCHANGE_RATES",\n "config_value": "{\\"USD\\": 7.2}",\n "description": "汇率配置",\n "type": "json"\n }\n]`}
- className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white outline-none font-mono text-xs text-black shadow-[2px_2px_0px_#000]"
- />
- </div>
- {/* Overwrite toggle */}
- <div className="flex items-center justify-between p-3 bg-neutral-50 border-2 border-black shadow-[2px_2px_0px_#000]">
- <div>
- <span className="font-bold text-black block uppercase">[ 同名 KEY 自动覆盖更新 ]</span>
- <span className="text-neutral-500 text-[10px]">开启后若遇到已存在 Key 将执行内容覆盖</span>
- </div>
- <label className="flex items-center gap-2 cursor-pointer font-bold text-xs">
- <input
- type="checkbox"
- checked={overwrite}
- onChange={(e) => setOverwrite(e.target.checked)}
- className="w-4 h-4 accent-black"
- />
- <span>{overwrite ? '覆盖' : '跳过'}</span>
- </label>
- </div>
- </div>
- {/* Footer */}
- <div className="px-5 py-3 bg-neutral-200 flex justify-end gap-2 border-t-2 border-black">
- <button
- type="button"
- onClick={onClose}
- className="px-4 py-1.5 bg-white hover:bg-neutral-100 border-2 border-black text-xs font-bold uppercase shadow-[2px_2px_0px_#000]"
- disabled={submitting}
- >
- [ 取消 ]
- </button>
- <button
- type="button"
- onClick={handleImport}
- disabled={submitting || parsedList.length === 0}
- className="px-5 py-1.5 bg-amber-300 hover:bg-amber-400 text-black border-2 border-black text-xs font-black uppercase shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5 disabled:opacity-50"
- >
- {submitting ? '导入处理中...' : `[ 确认导入 (${parsedList.length} 项) ]`}
- </button>
- </div>
- </div>
- </div>
- );
- }
|