477 lines
18 KiB
Vue
477 lines
18 KiB
Vue
<script setup lang="ts">
|
||
import { computed, h, onMounted, ref } from "vue";
|
||
import { NButton, NIcon, NInput, NInputNumber, NModal, NSelect, NSwitch, NTimePicker, NTooltip, useDialog } from "naive-ui";
|
||
import type { SelectRenderLabel, SelectRenderTag } from "naive-ui";
|
||
import { CreateOutline, InformationCircleOutline, TrashOutline } from "@vicons/ionicons5";
|
||
import Shell from "../../shell/Shell.vue";
|
||
import { api } from "../../shared/http";
|
||
import { useToast } from "../../shared/toast";
|
||
|
||
interface QueryTable {
|
||
code: number;
|
||
category: string;
|
||
tablename: string;
|
||
name: string;
|
||
}
|
||
interface Schedule {
|
||
mode: "weekly" | "monthly";
|
||
weekday?: number;
|
||
monthDay?: number;
|
||
time: string;
|
||
}
|
||
interface Source {
|
||
id: number;
|
||
name: string;
|
||
kind: string;
|
||
enabled: boolean;
|
||
lastError: string;
|
||
config: { tables?: QueryTable[]; timeMode?: string; timeCount?: number; city?: string; schedule?: Schedule };
|
||
}
|
||
interface Group {
|
||
code: number;
|
||
name: string;
|
||
tables: { tablename: string; name: string }[];
|
||
}
|
||
const sources = ref<Source[]>([]);
|
||
const show = ref(false);
|
||
const details = ref(false);
|
||
const fieldsOpen = ref(false);
|
||
const fieldsLoading = ref(false);
|
||
const fieldsTitle = ref("");
|
||
const fields = ref<{ name: string; type: string }[]>([]);
|
||
const fieldKeyword = ref("");
|
||
const visibleFields = computed(() => {
|
||
const text = fieldKeyword.value.trim().toLowerCase();
|
||
if (!text) return fields.value;
|
||
return fields.value.filter((field) => field.name.toLowerCase().includes(text));
|
||
});
|
||
const editing = ref<Source | null>(null);
|
||
const name = ref("");
|
||
const enabled = ref(true);
|
||
const groups = ref<Group[]>([]);
|
||
const chosen = ref<QueryTable[]>([]);
|
||
const timeMode = ref("prev_month");
|
||
const timeCount = ref(1);
|
||
const city = ref("");
|
||
const scheduleMode = ref<"weekly" | "monthly">("weekly");
|
||
const weekday = ref(1);
|
||
const monthDay = ref(1);
|
||
const clock = ref("08:00");
|
||
const catalogLoading = ref(false);
|
||
const dialog = useDialog();
|
||
const toast = useToast();
|
||
const timeOptions = [
|
||
{ label: "上一个月", value: "prev_month" },
|
||
{ label: "上一周", value: "prev_week" },
|
||
{ label: "前一天", value: "prev_day" },
|
||
{ label: "前几周", value: "prev_weeks" },
|
||
{ label: "前几月", value: "prev_months" },
|
||
{ label: "前多少天", value: "prev_days" },
|
||
];
|
||
const weekdays = ["一", "二", "三", "四", "五", "六", "日"].map((label, index) => ({ label: `周${label}`, value: index + 1 }));
|
||
const monthDays = Array.from({ length: 31 }, (_, index) => ({ label: `${index + 1} 日`, value: index + 1 }));
|
||
const needsCount = computed(() => ["prev_weeks", "prev_months", "prev_days"].includes(timeMode.value));
|
||
const countLabel = computed(() => (timeMode.value === "prev_weeks" ? "周数" : timeMode.value === "prev_months" ? "月数" : "天数"));
|
||
const tableOptions = computed(() => groups.value.map((group) => ({
|
||
type: "group" as const,
|
||
label: group.name,
|
||
key: String(group.code),
|
||
children: group.tables.map((table) => ({ label: table.name, value: table.tablename })),
|
||
})));
|
||
const picked = computed(() => chosen.value.map((item) => item.tablename));
|
||
const pickedText = computed(() => chosen.value.map((item) => item.name).join("、"));
|
||
const renderTag: SelectRenderTag = () => h("span", { class: "picker-inline" }, pickedText.value);
|
||
const renderTableLabel: SelectRenderLabel = (option) => {
|
||
if (option.type === "group") return String(option.label ?? "");
|
||
const title = String(option.label ?? "");
|
||
const tablename = String(option.value ?? "");
|
||
return h("div", { style: "display:flex;align-items:center;gap:8px;width:100%;min-width:0" }, [
|
||
h("span", { style: "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" }, title),
|
||
h(NTooltip, null, {
|
||
trigger: () => h(NButton, {
|
||
size: "tiny",
|
||
quaternary: true,
|
||
circle: true,
|
||
ariaLabel: "字段",
|
||
onMousedown: (event: MouseEvent) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
},
|
||
onClick: (event: MouseEvent) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
void openFields(tablename, title);
|
||
},
|
||
}, { icon: () => h(NIcon, { component: InformationCircleOutline }) }),
|
||
default: () => "字段",
|
||
}),
|
||
]);
|
||
};
|
||
|
||
async function openFields(tablename: string, title: string) {
|
||
fieldsTitle.value = title || "字段";
|
||
fieldKeyword.value = "";
|
||
fields.value = [];
|
||
fieldsOpen.value = true;
|
||
fieldsLoading.value = true;
|
||
try {
|
||
const result = await api<{ columns: { name: string; type: string }[] }>(`/api/admin/nqi/columns?tablename=${encodeURIComponent(tablename)}`);
|
||
fields.value = result.columns;
|
||
} catch (error) {
|
||
fieldsOpen.value = false;
|
||
toast.error(error instanceof Error ? error.message : "字段没有获取到");
|
||
} finally {
|
||
fieldsLoading.value = false;
|
||
}
|
||
}
|
||
|
||
function scheduleText(source: Source) {
|
||
const schedule = source.config.schedule;
|
||
if (!schedule) return "未设置";
|
||
const clockText = schedule.time || "";
|
||
if (schedule.mode === "monthly") return `每月 ${schedule.monthDay} 日 ${clockText}`;
|
||
const label = weekdays.find((item) => item.value === schedule.weekday)?.label || "";
|
||
return `每${label} ${clockText}`;
|
||
}
|
||
|
||
function timeText(source: Source) {
|
||
const mode = source.config.timeMode || "";
|
||
const found = timeOptions.find((item) => item.value === mode);
|
||
const count = Number(source.config.timeCount || 1);
|
||
if (!found) return "未设置";
|
||
if (mode === "prev_weeks") return `前 ${count} 周`;
|
||
if (mode === "prev_months") return `前 ${count} 月`;
|
||
if (mode === "prev_days") return `前 ${count} 天`;
|
||
return found.label;
|
||
}
|
||
|
||
function tableItems(source: Source) {
|
||
return Array.isArray(source.config.tables) ? source.config.tables : [];
|
||
}
|
||
|
||
function tablesText(source: Source) {
|
||
const tables = tableItems(source);
|
||
if (!tables.length) return "未选择";
|
||
const first = tables[0].name || tables[0].tablename;
|
||
if (tables.length === 1) return first;
|
||
return `${first} 等 ${tables.length} 张`;
|
||
}
|
||
|
||
function tablesTitle(source: Source) {
|
||
return tableItems(source).map((item) => item.name || item.tablename).join("、");
|
||
}
|
||
|
||
function cityText(source: Source) {
|
||
return String(source.config.city || "").trim() || "不限";
|
||
}
|
||
|
||
function reset(source?: Source) {
|
||
editing.value = source || null;
|
||
name.value = source?.name || "";
|
||
enabled.value = source?.enabled ?? true;
|
||
const stored = Array.isArray(source?.config.tables) ? source.config.tables : [];
|
||
chosen.value = stored.filter((item) => item?.tablename).map((item) => ({
|
||
code: Number(item.code) || 0,
|
||
category: String(item.category || ""),
|
||
tablename: String(item.tablename),
|
||
name: String(item.name || item.tablename),
|
||
}));
|
||
timeMode.value = source?.config.timeMode || "prev_month";
|
||
timeCount.value = Number(source?.config.timeCount || 1);
|
||
city.value = source?.config.city || "";
|
||
const schedule = source?.config.schedule;
|
||
scheduleMode.value = schedule?.mode === "monthly" ? "monthly" : "weekly";
|
||
weekday.value = Number(schedule?.weekday || 1);
|
||
monthDay.value = Number(schedule?.monthDay || 1);
|
||
clock.value = schedule?.time || "08:00";
|
||
show.value = true;
|
||
if (!groups.value.length) void loadCatalog();
|
||
}
|
||
|
||
async function load() {
|
||
const result = await api<{ sources: Source[] }>("/api/admin/sources");
|
||
sources.value = result.sources;
|
||
}
|
||
|
||
async function loadCatalog() {
|
||
catalogLoading.value = true;
|
||
try {
|
||
const result = await api<{ groups: Group[] }>("/api/admin/nqi/catalog?tree=true");
|
||
groups.value = result.groups;
|
||
} catch (error) {
|
||
toast.error(error instanceof Error ? error.message : "数据表没有获取到");
|
||
} finally {
|
||
catalogLoading.value = false;
|
||
}
|
||
}
|
||
|
||
function lookup(tablename: string) {
|
||
for (const group of groups.value) {
|
||
const table = group.tables.find((item) => item.tablename === tablename);
|
||
if (table) return { code: group.code, category: group.name, tablename, name: table.name };
|
||
}
|
||
return chosen.value.find((item) => item.tablename === tablename) || null;
|
||
}
|
||
|
||
function setPicked(names: string[]) {
|
||
const wasEmpty = chosen.value.length === 0;
|
||
const next = names.map(lookup).filter((item): item is QueryTable => Boolean(item));
|
||
if (wasEmpty && next.length && !name.value.trim()) name.value = next[0].name;
|
||
chosen.value = next;
|
||
}
|
||
|
||
function removeTable(tablename: string) {
|
||
chosen.value = chosen.value.filter((item) => item.tablename !== tablename);
|
||
}
|
||
|
||
async function save() {
|
||
if (!name.value.trim()) {
|
||
toast.error("请填写名称");
|
||
return false;
|
||
}
|
||
if (!chosen.value.length) {
|
||
toast.error("请选择要采集的表");
|
||
return false;
|
||
}
|
||
if (!clock.value) {
|
||
toast.error("请填写采集时间");
|
||
return false;
|
||
}
|
||
const schedule = scheduleMode.value === "weekly"
|
||
? { mode: "weekly", weekday: weekday.value, time: clock.value }
|
||
: { mode: "monthly", monthDay: monthDay.value, time: clock.value };
|
||
const body = {
|
||
name: name.value,
|
||
kind: "nqi",
|
||
enabled: enabled.value,
|
||
config: { tables: chosen.value, timeMode: timeMode.value, timeCount: timeCount.value, city: city.value, schedule },
|
||
};
|
||
try {
|
||
if (editing.value) {
|
||
await api(`/api/admin/sources/${editing.value.id}`, { method: "PUT", body: JSON.stringify(body) });
|
||
} else {
|
||
await api("/api/admin/sources", { method: "POST", body: JSON.stringify(body) });
|
||
}
|
||
show.value = false;
|
||
toast.success("已保存");
|
||
await load();
|
||
} catch (error) {
|
||
toast.error(error instanceof Error ? error.message : "保存失败");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
async function remove(id: number) {
|
||
try {
|
||
await api(`/api/admin/sources/${id}`, { method: "DELETE" });
|
||
toast.success("已删除");
|
||
await load();
|
||
} catch (error) {
|
||
toast.error(error instanceof Error ? error.message : "删除失败");
|
||
}
|
||
}
|
||
|
||
function confirmRemove(source: Source) {
|
||
dialog.warning({
|
||
title: "删除采集",
|
||
content: `删除 ${source.name}?`,
|
||
positiveText: "删除",
|
||
negativeText: "取消",
|
||
positiveButtonProps: { type: "error" },
|
||
onPositiveClick: () => remove(source.id),
|
||
});
|
||
}
|
||
|
||
onMounted(load);
|
||
</script>
|
||
|
||
<template>
|
||
<Shell>
|
||
<section class="page admin-page">
|
||
<header class="page-head">
|
||
<h2>采集</h2>
|
||
<n-button type="primary" @click="reset()">添加采集</n-button>
|
||
</header>
|
||
<div class="admin-scroll">
|
||
<div class="surface table-card">
|
||
<table class="admin-table">
|
||
<thead>
|
||
<tr>
|
||
<th>名称</th>
|
||
<th>数据表</th>
|
||
<th>数据时间</th>
|
||
<th>城市</th>
|
||
<th>周期</th>
|
||
<th>状态</th>
|
||
<th class="col-actions">操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr v-if="!sources.length">
|
||
<td class="cell-empty" colspan="7">没有采集</td>
|
||
</tr>
|
||
<tr v-for="source in sources" :key="source.id">
|
||
<td>{{ source.name }}</td>
|
||
<td class="cell-clip" :title="tablesTitle(source)">{{ tablesText(source) }}</td>
|
||
<td>{{ timeText(source) }}</td>
|
||
<td>{{ cityText(source) }}</td>
|
||
<td>{{ scheduleText(source) }}</td>
|
||
<td>
|
||
<span v-if="source.lastError" class="status-bad">{{ source.lastError }}</span>
|
||
<span v-else :class="source.enabled ? 'status-ok' : 'status-wait'">{{ source.enabled ? "启用" : "停用" }}</span>
|
||
</td>
|
||
<td class="col-actions">
|
||
<div class="row-actions">
|
||
<n-tooltip>
|
||
<template #trigger>
|
||
<n-button size="small" quaternary circle aria-label="编辑" @click="reset(source)">
|
||
<template #icon><n-icon :component="CreateOutline" /></template>
|
||
</n-button>
|
||
</template>
|
||
编辑
|
||
</n-tooltip>
|
||
<n-tooltip>
|
||
<template #trigger>
|
||
<n-button size="small" quaternary circle aria-label="删除" @click="confirmRemove(source)">
|
||
<template #icon><n-icon :component="TrashOutline" /></template>
|
||
</n-button>
|
||
</template>
|
||
删除
|
||
</n-tooltip>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<n-modal v-model:show="show" class="app-dialog app-dialog-collect" preset="card" :show-icon="false" title="采集">
|
||
<div class="collect-form">
|
||
<div class="form-row"><label>名称</label><n-input v-model:value="name" /></div>
|
||
<div class="form-row">
|
||
<label>数据表</label>
|
||
<div class="table-picker">
|
||
<n-select
|
||
class="table-select"
|
||
multiple
|
||
filterable
|
||
placeholder="请选择表"
|
||
:value="picked"
|
||
:options="tableOptions"
|
||
:loading="catalogLoading"
|
||
:render-label="renderTableLabel"
|
||
:render-tag="renderTag"
|
||
@update:value="setPicked"
|
||
/>
|
||
<n-button class="picked-link" text type="primary" :disabled="!chosen.length" @click="details = true">已选 {{ chosen.length }}</n-button>
|
||
</div>
|
||
</div>
|
||
<div class="form-row"><label>数据时间</label><n-select v-model:value="timeMode" :options="timeOptions" /></div>
|
||
<div v-if="needsCount" class="form-row"><label>{{ countLabel }}</label><n-input-number v-model:value="timeCount" :min="1" :max="366" :show-button="false" /></div>
|
||
<div class="form-row"><label>城市</label><n-input v-model:value="city" placeholder="不填则不按城市过滤" /></div>
|
||
<div class="form-row">
|
||
<label>采集周期</label>
|
||
<n-select v-model:value="scheduleMode" :options="[{ label: '每周', value: 'weekly' }, { label: '每月', value: 'monthly' }]" />
|
||
</div>
|
||
<div class="form-row">
|
||
<label>{{ scheduleMode === 'weekly' ? '星期' : '日期' }}</label>
|
||
<div class="schedule-time">
|
||
<n-select v-if="scheduleMode === 'weekly'" v-model:value="weekday" :options="weekdays" />
|
||
<n-select v-else v-model:value="monthDay" :options="monthDays" />
|
||
<n-time-picker v-model:formatted-value="clock" format="HH:mm" value-format="HH:mm" />
|
||
</div>
|
||
</div>
|
||
<div class="form-row form-row-switch"><label>启用</label><n-switch v-model:value="enabled" /></div>
|
||
</div>
|
||
<template #footer>
|
||
<div class="dialog-actions">
|
||
<n-button @click="show = false">取消</n-button>
|
||
<n-button type="primary" @click="save">保存</n-button>
|
||
</div>
|
||
</template>
|
||
</n-modal>
|
||
<n-modal v-model:show="fieldsOpen" class="app-dialog app-dialog-fields" preset="card" :title="fieldsTitle || '字段'">
|
||
<p v-if="fieldsLoading" class="admin-status">正在读取字段</p>
|
||
<div v-else-if="fields.length" class="field-panel">
|
||
<n-input v-model:value="fieldKeyword" clearable placeholder="搜索字段" />
|
||
<p class="admin-status">{{ fieldKeyword.trim() ? `匹配 ${visibleFields.length} 个` : `共 ${fields.length} 个字段` }}</p>
|
||
<div v-if="visibleFields.length" class="field-list">
|
||
<div v-for="(field, index) in visibleFields" :key="`${field.name}-${index}`" class="field-row">
|
||
<span>{{ field.name }}</span>
|
||
<span v-if="field.type" class="field-type">{{ field.type }}</span>
|
||
</div>
|
||
</div>
|
||
<p v-else class="admin-status">没有匹配的字段</p>
|
||
</div>
|
||
<p v-else class="admin-status">没有字段</p>
|
||
</n-modal>
|
||
<n-modal v-model:show="details" class="app-dialog" preset="card" title="已选表格">
|
||
<div v-if="chosen.length" class="picked-list">
|
||
<div v-for="item in chosen" :key="item.tablename" class="picked-row">
|
||
<div>
|
||
<strong>{{ item.name }}</strong>
|
||
<span>{{ item.category }}</span>
|
||
</div>
|
||
<n-tooltip>
|
||
<template #trigger>
|
||
<n-button size="small" quaternary circle aria-label="移除" @click="removeTable(item.tablename)">
|
||
<template #icon><n-icon :component="TrashOutline" /></template>
|
||
</n-button>
|
||
</template>
|
||
移除
|
||
</n-tooltip>
|
||
</div>
|
||
</div>
|
||
<p v-else class="admin-status">还没有选择表格</p>
|
||
</n-modal>
|
||
</Shell>
|
||
</template>
|
||
|
||
<style scoped>
|
||
.collect-form { display: grid; gap: 12px; min-width: 0; }
|
||
.table-picker { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||
.table-select { flex: 1; min-width: 0; }
|
||
.picked-link { flex: none; }
|
||
.form-row-switch :deep(.n-switch) { width: auto; justify-self: start; }
|
||
.table-select :deep(.n-base-selection),
|
||
.table-select :deep(.n-base-selection-tags) { min-width: 0; overflow: hidden; }
|
||
.table-select :deep(.n-base-selection-tags) { flex-wrap: nowrap; }
|
||
.table-select :deep(.n-base-selection-tag-wrapper) { min-width: 0; max-width: 100%; overflow: hidden; }
|
||
.table-select :deep(.n-base-selection-tag-wrapper:first-child) { flex: 1 1 0; }
|
||
.table-select :deep(.n-base-selection-tag-wrapper:not(:first-child)) { display: none; }
|
||
.table-select :deep(.picker-inline) {
|
||
display: block;
|
||
width: 100%;
|
||
min-width: 0;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
.schedule-time { display: grid; grid-template-columns: minmax(0, 1fr) 128px; gap: 8px; }
|
||
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
|
||
.picked-list { display: grid; gap: 8px; }
|
||
.picked-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||
.picked-row strong { display: block; }
|
||
.picked-row span { color: var(--muted); font-size: 12px; }
|
||
.field-panel { display: grid; gap: 8px; }
|
||
.field-list {
|
||
display: grid;
|
||
gap: 0;
|
||
max-height: min(48vh, 420px);
|
||
overflow: auto;
|
||
border: 1px solid var(--line);
|
||
border-radius: 8px;
|
||
}
|
||
.field-row {
|
||
display: flex;
|
||
align-items: baseline;
|
||
justify-content: space-between;
|
||
gap: 12px;
|
||
padding: 8px 12px;
|
||
border-bottom: 1px solid var(--line);
|
||
}
|
||
.field-row:last-child { border-bottom: 0; }
|
||
.field-type { color: var(--muted); font-size: 12px; white-space: nowrap; }
|
||
</style>
|