收藏主机.

This commit is contained in:
lijiahang
2023-09-14 16:18:41 +08:00
parent 08f9b9410b
commit f8b694c16a
13 changed files with 386 additions and 74 deletions

View File

@@ -1,5 +1,4 @@
import axios from 'axios';
import qs from 'query-string';
import { DataGrid, Pagination } from '@/types/global';
/**
@@ -9,6 +8,7 @@ export interface HostCreateRequest {
name?: string;
code?: string;
address?: string;
tags?: Array<number>;
}
/**
@@ -26,6 +26,10 @@ export interface HostQueryRequest extends Pagination {
name?: string;
code?: string;
address?: string;
favorite?: boolean;
tags?: Array<number>;
extra?: boolean;
config?: boolean;
}
/**
@@ -40,6 +44,28 @@ export interface HostQueryResponse {
updateTime: number;
creator: string;
updater: string;
favorite: boolean;
tags: Record<number, string>;
configs: Record<string, HostConfigQueryResponse>;
}
/**
* 主机配置请求
*/
export interface HostConfigRequest {
hostId?: number;
type?: string;
version?: number;
config?: string;
}
/**
* 主机配置查询响应
*/
export interface HostConfigQueryResponse {
id: number;
version: number;
config: Record<string, any>;
}
/**
@@ -59,20 +85,8 @@ export function updateHost(request: HostUpdateRequest) {
/**
* 通过 id 查询主机
*/
export function getHost(id: number) {
return axios.get<HostQueryResponse>('/asset/host/get', { params: { id } });
}
/**
* 通过 id 批量查询主机
*/
export function getHostList(idList: Array<number>) {
return axios.get<HostQueryResponse[]>('/asset/host/list', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
}
});
export function getHost(params: HostQueryRequest) {
return axios.get<HostQueryResponse>('/asset/host/get', { params });
}
/**
@@ -97,13 +111,22 @@ export function deleteHost(id: number) {
}
/**
* 通过 id 批量删除主机
* 查询主机配置
*/
export function batchDeleteHost(idList: Array<number>) {
return axios.delete('/asset/host/delete-batch', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
}
});
export function getHostConfig(params: HostConfigRequest) {
return axios.get<HostConfigQueryResponse>('/asset/host/get-config', { params });
}
/**
* 查询主机配置 - 全部
*/
export function getHostConfigAll(params: HostConfigRequest) {
return axios.get<Array<HostConfigQueryResponse>>('/asset/host/get-config-all', { params });
}
/**
* 更新主机配置
*/
export function updateHostConfig(request: HostConfigRequest) {
return axios.put('/asset/host/update-config', request);
}

View File

@@ -0,0 +1,25 @@
import axios from 'axios';
export type FavoriteType = 'HOST'
/**
* 收藏操作对象
*/
export interface FavoriteOperatorRequest {
relId: number;
type: FavoriteType;
}
/**
* 添加收藏
*/
export function addFavorite(request: FavoriteOperatorRequest) {
return axios.put('/infra/favorite/add', request);
}
/**
* 取消收藏
*/
export function cancelFavorite(request: FavoriteOperatorRequest) {
return axios.put('/infra/favorite/cancel', request);
}

View File

@@ -0,0 +1,33 @@
import axios from 'axios';
export type TagType = 'HOST'
/**
* tag 创建对象
*/
export interface TagCreateRequest {
name: number;
type: TagType;
}
/**
* tag 响应对象
*/
export interface TagResponse {
id: number;
name: string;
}
/**
* 创建标签
*/
export function createTag(request: TagCreateRequest) {
return axios.post('/infra/tag/create', request);
}
/**
* 查询标签
*/
export function getTagList(type: TagType) {
return axios.get<TagResponse>('/infra/tag/list', { params: { type } });
}

View File

@@ -66,6 +66,10 @@
}
}
.usn {
user-select: none;
}
.hide {
display: none;
}

View File

@@ -0,0 +1,113 @@
<template>
<a-select v-model:model-value="value"
:placeholder="placeholder"
:options="optionData"
:limit=limit
@exceed-limit="onLimited"
multiple
:allow-create="allowCreate"
allow-clear>
</a-select>
</template>
<script lang="ts">
export default {
name: 'tag-multi-selector'
};
</script>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { useCacheStore } from '@/store';
import { Message, SelectOptionData } from '@arco-design/web-vue';
import { createTag, TagCreateRequest, TagType } from '@/api/meta/tag';
const props = defineProps({
modelValue: Array,
placeholder: String,
limit: Number,
type: String,
allowCreate: Boolean
});
const emits = defineEmits(['update:modelValue']);
const value = computed({
get() {
return props.modelValue;
},
async set(e) {
await checkCreateTag(e as any);
emits('update:modelValue', e);
}
});
// 选项数据
const cacheStore = useCacheStore();
const optionData = ref<SelectOptionData[]>([]);
const initOptionData = () => {
optionData.value = cacheStore.tags.map(s => {
return {
label: s.name,
value: s.id,
};
}) as SelectOptionData[];
};
initOptionData();
defineExpose({ initOptionData });
// 检查是否可以创建tag
const checkCreateTag = async (tags: Array<any>) => {
if (!tags.length) {
return;
}
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
// 为 number 代表为 id 已存在
if (typeof tag === 'number') {
continue;
}
// 已存在则跳过
const find = optionData.value.find((o) => o.label === tag);
if (find) {
// 删除并且跳出循环
tags.splice(i, 1);
return;
}
try {
// 创建 tag
tags[i] = await doCreateTag(tag);
} catch (e) {
// 失败删除
tags.splice(i, 1);
}
}
};
// 创建 tag
const doCreateTag = async (name: string) => {
const { data: id } = await createTag({
name,
type: props.type
} as unknown as TagCreateRequest);
// 插入缓存
cacheStore.tags.push({ id, name });
// 插入 options
optionData.value.push({
label: name,
value: id
});
return id;
};
// 超出限制
const onLimited = () => {
Message.warning(`最多选择${props.limit}个tag`);
};
</script>
<style lang="less" scoped>
</style>

View File

@@ -0,0 +1,29 @@
import { Message } from '@arco-design/web-vue';
import { FavoriteType, addFavorite, cancelFavorite } from '@/api/meta/favorite';
export default function useFavorite(type: FavoriteType) {
const toggle = async (record: any, id: number, cancelField = 'favorite') => {
const request = { relId: id, type } as any;
const loading = Message.loading(record[cancelField] ? '取消中' : '收藏中');
try {
if (record[cancelField]) {
// 取消收藏
await cancelFavorite(request);
record[cancelField] = false;
Message.success('已取消');
} else {
// 添加收藏
await addFavorite(request);
record[cancelField] = true;
Message.success('已收藏');
}
} finally {
loading.close();
}
};
return {
toggle
};
}

View File

@@ -50,6 +50,17 @@ export function md5(plain: string): string {
return Md5.hashStr(plain);
}
/**
* 获取数据颜色
*/
export function dataColor(str: string, colors: string[]): string {
let total = 0;
for (let i = 0; i < str.length; i++) {
total += str.charCodeAt(i);
}
return colors[total % colors.length];
}
/**
* 判断值是否非空
*/

View File

@@ -32,6 +32,14 @@
<a-form-item field="address" label="主机地址">
<a-input v-model="formModel.address" placeholder="请输入主机地址" />
</a-form-item>
<!-- 主机标签 -->
<a-form-item field="tags" label="主机标签">
<tag-multi-selector v-model="formModel.tags"
:allowCreate="true"
:limit="5"
type="HOST"
placeholder="请选择主机标签" />
</a-form-item>
</a-form>
</a-spin>
</a-modal>
@@ -50,8 +58,7 @@
import formRules from '../types/form.rules';
import { createHost, updateHost } from '@/api/asset/host';
import { Message } from '@arco-design/web-vue';
import {} from '../types/enum.types';
import { toOptions } from '@/utils/enum';
import TagMultiSelector from '@/components/tag/tag-multi-selector.vue';
const { visible, setVisible } = useVisible();
const { loading, setLoading } = useLoading();
@@ -65,7 +72,7 @@
name: undefined,
code: undefined,
address: undefined,
favorite: undefined,
tags: undefined,
};
};

View File

@@ -21,6 +21,15 @@
<a-form-item field="address" label="主机地址" label-col-flex="50px">
<a-input v-model="formModel.address" placeholder="请输入主机地址" allow-clear />
</a-form-item>
<!-- 主机标签 -->
<a-form-item field="tags" label="主机地址" label-col-flex="50px">
<tag-multi-selector v-model="formModel.tags"
ref="tagSelector"
:allowCreate="false"
:limit="0"
type="HOST"
placeholder="请选择主机标签" />
</a-form-item>
</a-query-header>
</a-card>
<!-- 表格 -->
@@ -33,6 +42,18 @@
<!-- 右侧按钮 -->
<div class="table-bar-handle">
<a-space>
<!-- 仅看收藏 -->
<a-checkbox v-model="formModel.favorite" @change="fetchTableData()">
<template #checkbox="{ checked }">
<a-tag :checked="checked"
class="only-favorite"
size="large"
color="arcoblue"
checkable>
仅看收藏
</a-tag>
</template>
</a-checkbox>
<!-- 新增 -->
<a-button type="primary"
v-permission="['asset:host:create']"
@@ -42,21 +63,6 @@
<icon-plus />
</template>
</a-button>
<!-- 删除 -->
<a-popconfirm position="br"
type="warning"
:content="`确认删除选中的${selectedKeys.length}条记录吗?`"
@ok="deleteSelectRows">
<a-button v-permission="['asset:host:delete']"
type="secondary"
status="danger"
:disabled="selectedKeys.length === 0">
删除
<template #icon>
<icon-delete />
</template>
</a-button>
</a-popconfirm>
</a-space>
</div>
</template>
@@ -67,8 +73,6 @@
label-align="left"
:loading="loading"
:columns="columns"
v-model:selectedKeys="selectedKeys"
:row-selection="rowSelection"
:data="tableRenderData"
:pagination="pagination"
@page-change="(page) => fetchTableData(page, pagination.pageSize)"
@@ -80,6 +84,16 @@
{{ record.address }}
</span>
</template>
<!-- 标签 -->
<template #tag="{ record }">
<a-space v-if="record.tags">
<a-tag v-for="tag in record.tags"
:key="tag.id"
:color="dataColor(tag.name, tagColor)">
{{ tag.name }}
</a-tag>
</a-space>
</template>
<!-- 操作 -->
<template #handle="{ record }">
<div class="table-handle-wrapper row-handle-wrapper">
@@ -103,10 +117,18 @@
</a-button>
</a-popconfirm>
<!-- 收藏 -->
<a-tooltip :content="record.favorite ? '取消收藏' : '收藏'">
<icon-star-fill v-if="record.favorite" class="host-favorite host-favorite-choice" />
<icon-star v-else class="host-favorite host-favorite-un-choice" />
</a-tooltip>
<span v-if="record.favorite"
title="取消收藏"
class="host-favorite host-favorite-choice"
@click="() => toggleFavorite(record, record.id)">
<icon-star-fill />
</span>
<span v-else
title="收藏"
class="host-favorite host-favorite-un-choice"
@click="() => toggleFavorite(record, record.id)">
<icon-star />
</span>
</div>
</template>
</a-table>
@@ -121,46 +143,38 @@
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { batchDeleteHost, deleteHost, getHostPage, HostQueryRequest, HostQueryResponse } from '@/api/asset/host';
import { deleteHost, getHostPage, HostQueryRequest, HostQueryResponse } from '@/api/asset/host';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import columns from '../types/table.columns';
import { defaultPagination, defaultRowSelection } from '@/types/table';
import {} from '../types/enum.types';
import { toOptions } from '@/utils/enum';
import { tagColor } from '../types/const';
import { defaultPagination } from '@/types/table';
import useCopy from '@/hooks/copy';
import useFavorite from '@/hooks/favorite';
import { dataColor } from '@/utils';
import TagMultiSelector from '@/components/tag/tag-multi-selector.vue';
import { getTagList } from '@/api/meta/tag';
import { useCacheStore } from '@/store';
const tagSelector = ref();
const tableRenderData = ref<HostQueryResponse[]>();
const { loading, setLoading } = useLoading();
const emits = defineEmits(['openAdd', 'openUpdate']);
const pagination = reactive(defaultPagination());
const selectedKeys = ref<number[]>([]);
const rowSelection = reactive(defaultRowSelection());
const { copy } = useCopy();
const { toggle: toggleFavorite } = useFavorite('HOST');
const formModel = reactive<HostQueryRequest>({
id: undefined,
name: undefined,
code: undefined,
address: undefined,
favorite: undefined,
tags: undefined,
extra: true
});
// 删除选中行
const deleteSelectRows = async () => {
try {
setLoading(true);
// 调用删除接口
await batchDeleteHost(selectedKeys.value);
Message.success(`成功删除${selectedKeys.value.length}条数据`);
selectedKeys.value = [];
// 重新加载数据
await fetchTableData();
} finally {
setLoading(false);
}
};
// 删除当前行
const deleteRow = async ({ id }: { id: number }) => {
try {
@@ -209,6 +223,21 @@
};
fetchTableData();
// 加载 tags
const loadTags = async () => {
try {
const { data } = await getTagList('HOST');
// 设置到缓存
const cacheStore = useCacheStore();
cacheStore.set('tags', data);
// 重新初始化
tagSelector.value.initOptionData();
} catch {
Message.error('tag加载失败');
}
};
loadTags();
</script>
<style lang="less" scoped>
@@ -229,14 +258,30 @@
margin: 0 4px;
}
.host-favorite-choice {
color: rgb(var(--yellow-6));
:hover {
transition: .2s;
color: rgba(232, 203, 12, .9);
}
}
.host-favorite-un-choice {
color: rgb(var(--gray-6));
}
:hover {
transition: .2s;
color: rgb(var(--yellow-6));
}
}
}
.only-favorite {
user-select: none;
color: rgb(var(--arcoblue-5));
background: rgb(var(--gray-2));
}
</style>

View File

@@ -2,12 +2,12 @@
<div class="layout-container">
<!-- 表格 -->
<host-table ref="table"
@openAdd="() => modal.openAdd()"
@openUpdate="(e) => modal.openUpdate(e)" />
@openAdd="() => modal.openAdd()"
@openUpdate="(e) => modal.openUpdate(e)" />
<!-- 添加修改模态框 -->
<host-form-modal ref="modal"
@added="() => table.addedCallback()"
@updated="() => table.updatedCallback()" />
@added="() => table.addedCallback()"
@updated="() => table.updatedCallback()" />
</div>
</template>
@@ -20,11 +20,18 @@
<script lang="ts" setup>
import HostTable from './components/host-table.vue';
import HostFormModal from './components/host-form-modal.vue';
import { ref } from 'vue';
import { onUnmounted, ref } from 'vue';
import { useCacheStore } from '@/store';
const table = ref();
const modal = ref();
// 卸载时清除 tags cache
onUnmounted(() => {
const cacheStore = useCacheStore();
cacheStore.set('tags', []);
});
</script>
<style lang="less" scoped>

View File

@@ -0,0 +1,4 @@
/**
* tag 颜色
*/
export const tagColor = ['#FF5E5E', '#0FC6C2', '#CE36FF', '#14C93E', '#168CFF'];

View File

@@ -24,8 +24,14 @@ export const address = [{
message: '主机地址长度不能大于128位'
}] as FieldRule[];
export const tags = [{
maxLength: 5,
message: '最多选择5个标签'
}] as FieldRule[];
export default {
name,
code,
address,
tags,
} as Record<string, FieldRule | FieldRule[]>;

View File

@@ -23,6 +23,11 @@ const columns = [
dataIndex: 'address',
slotName: 'address',
align: 'center',
}, {
title: '标签',
dataIndex: 'tag',
slotName: 'tag',
align: 'left',
}, {
title: '操作',
slotName: 'handle',