Merge branch 'dev' of github.com:jetlinks/jetlinks-ui-vue into dev

# Conflicts:
#	components.d.ts
This commit is contained in:
xiongqian 2023-01-11 18:41:06 +08:00
commit b0983a1988
35 changed files with 2409 additions and 539 deletions

5
components.d.ts vendored
View File

@ -7,6 +7,7 @@ export {}
declare module '@vue/runtime-core' {
export interface GlobalComponents {
AAlert: typeof import('ant-design-vue/es')['Alert']
ABadge: typeof import('ant-design-vue/es')['Badge']
AButton: typeof import('ant-design-vue/es')['Button']
ACheckbox: typeof import('ant-design-vue/es')['Checkbox']
@ -25,12 +26,16 @@ declare module '@vue/runtime-core' {
AModal: typeof import('ant-design-vue/es')['Modal']
APagination: typeof import('ant-design-vue/es')['Pagination']
APopconfirm: typeof import('ant-design-vue/es')['Popconfirm']
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
ARow: typeof import('ant-design-vue/es')['Row']
ASelect: typeof import('ant-design-vue/es')['Select']
ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
ASpin: typeof import('ant-design-vue/es')['Spin']
ASwitch: typeof import('ant-design-vue/es')['Switch']
ATable: typeof import('ant-design-vue/es')['Table']
ATimePicker: typeof import('ant-design-vue/es')['TimePicker']
ATooltip: typeof import('ant-design-vue/es')['Tooltip']
ATreeSelect: typeof import('ant-design-vue/es')['TreeSelect']
AUpload: typeof import('ant-design-vue/es')['Upload']
BadgeStatus: typeof import('./src/components/BadgeStatus/index.vue')['default']
CardBox: typeof import('./src/components/CardBox/index.vue')['default']

View File

@ -1,4 +1,6 @@
import { get } from '@/utils/request'
import { get, post } from '@/utils/request'
// 三方应用账户信息
export const applicationInfo = (code: string) => get(`/application/sso/bind-code/${code}`)
export const applicationInfo = (code: string): any => get(`/application/sso/bind-code/${code}`)
// 立即绑定
export const bindAccount = (code: string): any => post(`/application/sso/me/bind/${code}`)

View File

@ -0,0 +1,33 @@
import server from '@/utils/request';
export const getProviders = () => server.get(`/gateway/device/providers`);
export const detail = (id) => server.get(`/gateway/device/${id}`);
export const getNetworkList = (networkType, data, params) =>
server.get(
`/network/config/${networkType}/_alive?include=${params.include}`,
data,
);
export const getProtocolList = (transport, params) =>
server.get(`/protocol/supports/${transport ? transport : ''}`, params);
export const getConfigView = (id, transport) =>
server.get(`/protocol/${id}/transport/${transport}`);
export const getChildConfigView = (id) =>
server.get(`/protocol/${id}/transports`);
export const save = (data) => server.post(`/gateway/device`, data);
export const update = (data) => server.patch(`/gateway/device`, data);
export const list = (data) =>
server.post(`/gateway/device/detail/_query`, data);
export const undeploy = (id) => server.post(`/gateway/device/${id}/_shutdown`);
export const deploy = (id) => server.post(`/gateway/device/${id}/_startup`);
export const del = (id) => server.remove(`/gateway/device/${id}`);

View File

@ -2,17 +2,10 @@
<div class="card">
<div
class="card-warp"
:class="{
hover: maskShow ? 'hover' : '',
active: actived ? 'active' : '',
}"
:class="{ active: active ? 'active' : ''}"
@click="handleClick"
>
<div
class="card-content"
@mouseenter="setMaskShow(true)"
@mouseleave="setMaskShow(false)"
>
<div class="card-content">
<a-row>
<a-col :span="6">
<!-- 图片 -->
@ -27,7 +20,7 @@
</a-row>
<!-- 勾选 -->
<div v-if="actived" class="checked-icon">
<div v-if="active" class="checked-icon">
<div>
<CheckOutlined />
</div>
@ -47,21 +40,12 @@
></BadgeStatus>
</div>
</div>
<!-- 遮罩层 -->
<div
v-if="showMask"
class="card-mask"
:class="maskShow ? 'show' : ''"
>
<slot name="mask"></slot>
</div>
</div>
</div>
<!-- 按钮 -->
<slot name="botton-tool">
<div v-if="showTool" class="card-tools">
<slot name="bottom-tool">
<div v-if="showTool && actions && actions.length" class="card-tools">
<div
v-for="item in actions"
:key="item.key"
@ -70,18 +54,32 @@
delete: item.key === 'delete',
}"
>
<a-tooltip v-if="item.disabled === true">
<template #title>{{ item.message }}</template>
<a-popconfirm v-if="item.popConfirm" v-bind="item.popConfirm">
<template v-if="item.key === 'delete'">
<a-button :disabled="item.disabled">
<template #icon><SearchOutlined /></template>
<span>{{ item.label }}</span>
<DeleteOutlined />
</a-button>
</a-tooltip>
<a-button v-else :disabled="item.disabled">
<template #icon><SearchOutlined /></template>
<span>{{ item.label }}</span>
</a-button>
</template>
<template v-else>
<a-button :disabled="item.disabled">
<AIcon :type="item.icon" />
<span>{{ item.text }}</span>
</a-button>
</template>
</a-popconfirm>
<template v-else>
<template v-if="item.key === 'delete'">
<a-button :disabled="item.disabled">
<DeleteOutlined />
</a-button>
</template>
<template v-else>
<a-button :disabled="item.disabled">
<AIcon :type="item.icon" />
<span>{{ item.text }}</span>
</a-button>
</template>
</template>
</div>
</div>
</slot>
@ -89,18 +87,26 @@
</template>
<script setup lang="ts">
import { SearchOutlined, CheckOutlined } from '@ant-design/icons-vue';
import { SearchOutlined, CheckOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import BadgeStatus from '@/components/BadgeStatus/index.vue';
import { StatusColorEnum } from '@/utils/consts.ts';
import type { ActionsType } from '@/components/Table/index.vue'
import { PropType } from 'vue';
type EmitProps = {
(e: 'update:modelvalue', data: string | number): void;
(e: 'actived', data: boolean): void;
// (e: 'update:modelValue', data: Record<string, any>): void;
(e: 'click', data: Record<string, any>): void;
};
type TableActionsType = Partial<ActionsType>
const emit = defineEmits<EmitProps>();
const props = defineProps({
value: {
type: Object as PropType<Record<string, any>>,
default: () => {}
},
showStatus: {
type: Boolean,
default: true,
@ -109,10 +115,7 @@ const props = defineProps({
type: Boolean,
default: true,
},
showMask: {
type: Boolean,
default: true,
},
statusText: {
type: String,
default: '正常',
@ -125,21 +128,17 @@ const props = defineProps({
type: Object,
},
actions: {
type: Array as any,
type: Array as PropType<TableActionsType[]>,
default: () => [],
},
active: {
type: Boolean,
default: false
}
});
const maskShow = ref(false);
const actived = ref(false);
const setMaskShow = (val: boolean) => {
maskShow.value = val;
};
const handleClick = () => {
actived.value = !actived.value;
emit('actived', actived.value);
emit('click', props.value);
};
</script>

View File

@ -1,11 +1,252 @@
<template>
<div class=''>
<div class='JForm-content'>
<a-form
ref='form'
v-bind='props'
:model='formData.data'
layout='vertical'
>
<a-row :type='rowType'>
<a-col v-for='item in formOptions.data' :key='item.key' :span='item.span'>
<a-form-item
:name='item.name'
:required='item.required'
:rules='item.rules'
:noStyle='item.noStyle'
>
<template #label>
<span>{{ item.title }}</span>
<a-tooltip :title='item.tooltip'>
<QuestionCircleOutlined v-if='!!item.tooltip' style='margin-left: 4px; color: rgba(0,0,0,.45) ' />
</a-tooltip>
</template>
<a-input
v-if='item.component === componentType.input'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<a-select
v-else-if='item.component === componentType.select'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
:options='item.options'
/>
<a-inputnumber
v-else-if='item.component === componentType.inputNumber'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<a-input-password
v-else-if='item.component === componentType.password'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<a-switch
v-else-if='item.component === componentType.switch'
v-bind='item.componentProps'
v-model:checked='formData.data[item.name]'
/>
<a-radio-group
v-else-if='item.component === componentType.radio'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<a-checkbox-group
v-else-if='item.component === componentType.checkbox'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
:options='item.options'
/>
<a-time-picker
v-else-if='item.component === componentType.time'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<a-date-picker
v-else-if='item.component === componentType.date'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<a-tree-select
v-else-if='item.component === componentType.tree'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
:tree-data='item.options'
/>
<a-upload
v-else-if='item.component === componentType.upload'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
<component
v-else
:is='item.component'
v-bind='item.componentProps'
v-model:value='formData.data[item.name]'
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
</div>
</template>
<script setup type='ts' name='FormBuilder'>
const data = reactive({})
<script setup lang='ts' name='FormBuilder'>
import type { Options, OptionsItem, OptionsComponent } from './index.modules'
import { PropType } from 'vue'
import { get, isArray, isString, pick, set } from 'lodash-es'
import { formProps } from 'ant-design-vue/es/form'
import componentType from './util'
import {
QuestionCircleOutlined
} from '@ant-design/icons-vue';
const form = ref()
const props = defineProps({
...formProps,
options: {
type: Object as PropType<Options>,
default: () => []
},
initValue: {
type: Object,
default: () => ({})
},
column: {
type: Number,
default: 1
}
})
//
const formData = reactive({
data: {}
})
const formOptions = reactive<{ data: OptionsComponent[]}>({
data: []
}) // Item
const rowType = ref<string | undefined>(undefined)
const calculateItemSpan = (span?: number | string) => {
const itemSpan = 24 / props.column
if (!span) return itemSpan
if (isString(span) && span.includes('px')) {
rowType.value = 'flex'
} else {
return span
}
}
/**
* 根据传入的表单options生成表单
* @param data {Options}
* @param parentKey
*/
const handleFormData = (data: Options, parentKey: Array<string> = []): any => {
const cacheModel: any = {}
Object.keys(data).forEach(async (key) => {
const optionItem = data[key]
const _key = [...parentKey, key]
if ('type' in optionItem && optionItem.type === 'Object') {
const dataModel = handleFormData(optionItem.properties, _key)
cacheModel[key] = dataModel
} else if (!('visible' in optionItem) || ('visible' in optionItem && optionItem.visible !== true)){
//
const keyValue = get(formData.data, _key)
let _options: any[] = []
if (keyValue) { // formModel
cacheModel[key] = keyValue
} else {
cacheModel[key] = (optionItem as OptionsItem).default
}
// options
if ('options' in optionItem) {
_options = optionItem.options!
}
// onSearch
if ('onSearch' in optionItem) {
const data = await optionItem.onSearch!()
if (data) {
_options = data
}
}
const optionsItemProps = pick(optionItem, ['componentProps', 'title', 'component', 'rules', 'required', 'hidden', 'tooltip', 'noStyle'])
//
formOptions.data.push({
...optionsItemProps,
name: _key,
options: _options,
key: isArray(_key) ? _key.toString() : _key,
span: calculateItemSpan((optionItem as OptionsItem).span)
})
}
})
return cacheModel
}
/**
* 重置表单
*/
const resetModel = () => {
form.value.resetFields()
}
/**
* 验证并提交表单
*/
const formValidate = () => {
return new Promise((res, rej) => {
form.value.validate().then(() => {
res(formData.data)
}).catch((err: any) => {
rej(err)
})
})
}
/**
* 改变单个值
*/
const setItemValue = (key: string | (string | number)[], value: any) => {
set(formData.data, key, value)
}
/**
* 修改整个表单值
* @param data
*/
const setData = (data: any) => {
formData.data = data
}
if (props.initValue) {
formData.data = props.initValue
}
formData.data = handleFormData(props.options)
watch(props.options, (newValue: any) => {
formOptions.data = []
formData.data = handleFormData(newValue)
})
watch(props.initValue, (newValue: any) => {
formData.data = newValue
})
defineExpose({
resetModel,
formValidate,
setItemValue,
setData
})
</script>
<style scoped>

40
src/components/Form/index.modules.d.ts vendored Normal file
View File

@ -0,0 +1,40 @@
import type { FormProps } from 'ant-design-vue/es/form'
export interface OptionsComponent {
/** FormItem title **/
title?: string
/** 组件名称 **/
component?: string
/** 组件Props **/
componentProps?: any
/** 组件Options **/
options?: any[]
name?: any
[name: string]: any
}
export interface OptionsItem extends OptionsComponent{
/** 内置查询会覆盖options **/
onSearch?: () => Promise<any>
default?: any
/** 隐藏Item值不会进入到FormModel中 **/
visible?: boolean
/** 表单隐藏域 **/
hidden?: boolean,
span?: number | string
rules?: FormProps.rules
required?: boolean
tooltip?: string
noStyle?: boolean
}
interface ObjectTypes {
type: 'Object'
properties: {
[name: string]: OptionsItem
}
}
export interface Options extends FormProps {
[name: string]: ObjectTypes | OptionsItem
}

View File

@ -1,3 +1,4 @@
import FormBuilder from './FormBuilder.vue'
export { default as componentType } from './util'
export default FormBuilder

View File

@ -0,0 +1,15 @@
const optionComponentType = {
input: 'input',
inputNumber: 'inputNumber',
password: 'password',
switch: 'switch',
radio: 'radio',
checkbox: 'checkbox',
time: 'time',
date: 'date',
treeSelect: 'treeSelect',
upload: 'upload',
tree: 'tree',
select: 'select'
}
export default optionComponentType

View File

@ -1,62 +1,98 @@
<template>
<div class="jtable-body">
<div class="jtable-body-header">
<div class="jtable-body-header-left">
<slot name="headerTitle"></slot>
</div>
<div class="jtable-body-header-right">
<div class="jtable-setting-item" :class="[ModelEnum.CARD === model ? 'active' : '']" @click="modelChange(ModelEnum.CARD)">
<AppstoreOutlined />
<a-spin :spinning="loading">
<div class="jtable-body">
<div class="jtable-body-header">
<div class="jtable-body-header-left">
<slot name="headerTitle"></slot>
</div>
<div class="jtable-setting-item" :class="[ModelEnum.TABLE === model ? 'active' : '']" @click="modelChange(ModelEnum.TABLE)">
<UnorderedListOutlined />
<div class="jtable-body-header-right" v-if="!model">
<div class="jtable-setting-item" :class="[ModelEnum.CARD === _model ? 'active' : '']" @click="modelChange(ModelEnum.CARD)">
<AppstoreOutlined />
</div>
<div class="jtable-setting-item" :class="[ModelEnum.TABLE === _model ? 'active' : '']" @click="modelChange(ModelEnum.TABLE)">
<UnorderedListOutlined />
</div>
</div>
</div>
</div>
<div class="jtable-content">
<div v-if="model === ModelEnum.CARD" class="jtable-card">
<div
v-if="dataSource.length"
class="jtable-card-items"
:style="{gridTemplateColumns: `repeat(${column}, 1fr)`}"
>
<div class="jtable-content">
<div class="jtable-alert" v-if="rowSelection.selectedRowKeys && rowSelection.selectedRowKeys.length">
<a-alert :message="'已选择' + rowSelection.selectedRowKeys.length + '项'" type="info" :afterClose="handleAlertClose">
<template #closeText>
<a>取消选择</a>
</template>
</a-alert>
</div>
<div v-if="_model === ModelEnum.CARD" class="jtable-card">
<div
class="jtable-card-item"
v-for="(item, index) in dataSource"
:key="index"
v-if="_dataSource.length"
class="jtable-card-items"
:style="{gridTemplateColumns: `repeat(${column}, 1fr)`}"
>
<slot name="cardRender" :item="item" :index="index"></slot>
<div
class="jtable-card-item"
v-for="(item, index) in _dataSource"
:key="index"
>
<slot name="card" v-bind="item" :index="index"></slot>
</div>
</div>
<div v-else>
<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
</div>
</div>
<div v-else>
<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
<a-table rowKey="id" :rowSelection="rowSelection" :columns="[..._columns]" :dataSource="_dataSource" :pagination="false" :scroll="{ x: 1366 }">
<template #bodyCell="{ column, record }">
<!-- <template v-if="column.key === 'action'">
<a-space>
<a-tooltip v-for="i in actions" :key="i.key" v-bind="i.tooltip">
<a-popconfirm v-if="i.popConfirm" v-bind="i.popConfirm">
<a><AIcon :type="i.icon" /></a>
</a-popconfirm>
<a v-else @click="i.onClick && i.onClick(record)">
<AIcon :type="i.icon" />
</a>
</a-tooltip>
</a-space>
</template> -->
<template v-if="column.scopedSlots">
<slot :name="column.key" :row="record"></slot>
</template>
</template>
</a-table>
</div>
</div>
<div v-else>
<a-table :columns="columns" :dataSource="dataSource" :pagination="false" />
<div class="jtable-pagination" v-if="_dataSource.length && !noPagination">
<a-pagination
size="small"
:total="total"
:showQuickJumper="false"
:showSizeChanger="true"
v-model:current="pageIndex"
v-model:page-size="pageSize"
:show-total="(total, range) => `第 ${range[0]} - ${range[1]} 条/总共 ${total} 条`"
@change="pageChange"
:page-size-options="[12, 24, 48, 60, 100]"
/>
</div>
</div>
<div class="jtable-pagination" v-if="dataSource.length">
<a-pagination
size="small"
:total="50"
:show-total="total => `第 ${1} - ${1} 条/总共 ${total} 条`"
/>
</div>
</div>
</a-spin>
</template>
<script setup lang="ts">
import { UnorderedListOutlined, AppstoreOutlined } from '@ant-design/icons-vue'
import type { TableProps } from 'ant-design-vue/es/table'
import type { TableProps, ColumnsType } from 'ant-design-vue/es/table'
import type { TooltipProps } from 'ant-design-vue/es/tooltip'
import type { PopconfirmProps } from 'ant-design-vue/es/popconfirm'
import { Empty } from 'ant-design-vue'
import { CSSProperties } from 'vue';
enum ModelEnum {
TABLE = 'TABLE',
CARD = 'CARD',
}
export declare type RequestData = {
type RequestData = {
code: string;
result: {
data: Record<string, any>[] | undefined;
@ -67,53 +103,134 @@ export declare type RequestData = {
status: number;
} & Record<string, any>;
interface JTableProps extends TableProps{
request: (params: Record<string, any> & {
export interface ActionsType {
key: string;
text?: string;
disabled?: boolean;
permission?: boolean;
onClick?: (data: any) => void;
style?: CSSProperties;
tooltip?: TooltipProps;
popConfirm?: PopconfirmProps;
icon?: string;
}
export interface JColumnsProps extends ColumnsType{
scopedSlots?: boolean; // true: false:
}
export interface JTableProps extends TableProps{
request?: (params: Record<string, any> & {
pageSize: number;
pageIndex: number;
}) => Promise<Partial<RequestData>>;
cardBodyClass?: string;
columns: Record<string, any>[];
params: Record<string, any> & {
columns: JColumnsProps;
params?: Record<string, any> & {
pageSize: number;
pageIndex: number;
}
};
model?: keyof typeof ModelEnum | undefined; // tablecard
actions?: ActionsType[];
noPagination?: boolean;
rowSelection?: TableProps['rowSelection'];
cardProps?: Record<string, any>;
dataSource?: Record<string, any>[];
}
// propsemit
const emit = defineEmits(["modelChange"]);
// props
const props = withDefaults(defineProps<JTableProps>(), {
cardBodyClass: '',
request: undefined
request: undefined,
})
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
const model = ref<keyof typeof ModelEnum>(ModelEnum.CARD); //
const column = ref<number>(4);
const dataSource = ref<Record<string, any>[]>([])
console.log(props)
//
// emit
const emit = defineEmits<{
(e: 'cancelSelect'): void
}>()
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
const _model = ref<keyof typeof ModelEnum>(props.model ? props.model : ModelEnum.CARD); //
const column = ref<number>(4);
const _dataSource = ref<Record<string, any>[]>([])
const pageIndex = ref<number>(0)
const pageSize = ref<number>(6)
const total = ref<number>(0)
const _columns = ref<Record<string, any>[]>([...props.columns])
const loading = ref<boolean>(true)
//
//
const modelChange = (type: keyof typeof ModelEnum) => {
model.value = type
_model.value = type
}
/**
* 请求数据
*/
const handleSearch = async (_params?: Record<string, any>) => {
loading.value = true
if(props.request) {
const resp = await props.request({
pageSize: 12,
pageIndex: 1,
..._params
})
if(resp.status === 200){
//
if(resp.result?.data?.length === 0 && resp.result.total && resp.result.pageSize && resp.result.pageIndex) {
handleSearch({
..._params,
pageSize: pageSize.value,
pageIndex: pageIndex.value - 1,
})
} else {
_dataSource.value = resp.result?.data || []
pageIndex.value = resp.result?.pageIndex || 0
pageSize.value = resp.result?.pageSize || 6
total.value = resp.result?.total || 0
}
}
} else {
_dataSource.value = props?.dataSource || []
}
loading.value = false
}
/**
* 页码变化
*/
const pageChange = (page: number, size: number) => {
handleSearch({
...props.params,
pageSize: size,
pageIndex: pageSize.value === size ? page : 1,
})
}
//
const handleSearch = async (params1?: Record<string, any>) => {
const resp = await props.request({
pageSize: 10,
pageIndex: 1,
...params1
})
if(resp.status === 200){
dataSource.value = resp.result?.data || []
}
// alert
const handleAlertClose = () => {
emit('cancelSelect')
}
// watchEffect(() => {
// if(Array.isArray(props.actions) && props.actions.length) {
// _columns.value = [...props.columns,
// {
// title: '',
// key: 'action',
// fixed: 'right',
// width: 250
// }
// ]
// } else {
// _columns.value = [...props.columns]
// }
// })
watchEffect(() => {
handleSearch(props.params)
})
// TODO
</script>
<style lang="less" scoped>
@ -145,11 +262,13 @@ watchEffect(() => {
}
}
.jtable-content {
.jtable-alert {
margin-bottom: 16px;
}
.jtable-card {
.jtable-card-items {
display: grid;
grid-gap: 26px;
// grid-template-columns: repeat(4, 1fr);
.jtable-card-item {
display: flex;
}
@ -160,9 +279,9 @@ watchEffect(() => {
margin-top: 20px;
display: flex;
justify-content: flex-end;
// position: absolute;
// right: 24px;
// bottom: 24px;
/deep/ .ant-pagination-item {
display: none !important;
}
}
}
</style>

View File

@ -1,45 +0,0 @@
.jtable-body {
width: 100%;
padding: 0 24px 24px;
background-color: white;
.jtable-body-header {
padding: 16px 0;
display: flex;
justify-content: space-between;
align-items: center;
.jtable-body-header-right {
display: flex;
gap: 8px;
.jtable-setting-item {
color: rgba(0, 0, 0, 0.75);
font-size: 16px;
cursor: pointer;
&:hover {
color: @primary-color-hover;
}
&.active {
color: @primary-color-active;
}
}
}
}
.jtable-content {
.jtable-card {
.jtable-card-items {
display: grid;
grid-gap: 26px;
// grid-template-columns: repeat(4, 1fr);
.jtable-card-item {
display: flex;
}
}
}
}
.jtable-pagination {
position: absolute;
right: 24px;
bottom: 24px;
}
}

View File

@ -1,168 +0,0 @@
import { UnorderedListOutlined, AppstoreOutlined } from '@ant-design/icons-vue'
import styles from './index.module.less'
import { Pagination, Table, Empty } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue/es/table'
enum ModelEnum {
TABLE = 'TABLE',
CARD = 'CARD',
}
export declare type RequestData = {
code: string;
result: {
data: any[] | undefined;
pageIndex: number;
pageSize: number;
total: number;
};
status: number;
} & Record<string, any>;
interface JTableProps extends TableProps{
request: (params: Record<string, any> & {
pageSize: number;
pageIndex: number;
}) => Promise<Partial<RequestData>>;
cardBodyClass: string;
}
const JTable = defineComponent<JTableProps>({
name: 'JTable',
slots: [
'headerTitle', // 顶部左边插槽
'cardRender', // 卡片内容
],
emits: [
'modelChange', // 切换卡片和表格
],
props: {
cardBodyClass: '',
request: undefined,
columns: []
} as any,
setup(props ,{ slots, emit }){
const model = ref<keyof typeof ModelEnum>(ModelEnum.CARD); // 模式切换
const column = ref<number>(3);
console.log(props.columns, props.request)
const dataSource = ref<any[]>([
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '2',
name: '胡彦祖1',
age: 42,
address: '西湖区湖底公园1号',
},
{
key: '3',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '4',
name: '胡彦祖1',
age: 42,
address: '西湖区湖底公园1号',
},
{
key: '5',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '6',
name: '胡彦祖1',
age: 42,
address: '西湖区湖底公园1号',
},
])
// 请求数据
onMounted(() => {
})
return () => <div class={styles["jtable-body"]}>
<div class={styles["jtable-body-header"]}>
<div class={styles["jtable-body-header-left"]}>
{/* 顶部左边插槽 */}
{slots.headerTitle && slots.headerTitle()}
</div>
<div class={styles["jtable-body-header-right"]}>
{/* <Space> */}
<div class={[styles["jtable-setting-item"], ModelEnum.CARD === model.value ? styles['active'] : '']} onClick={() => {
model.value = ModelEnum.CARD
}}>
<AppstoreOutlined />
</div>
<div class={[styles["jtable-setting-item"], ModelEnum.TABLE === model.value ? styles['active'] : '']} onClick={() => {
model.value = ModelEnum.TABLE
}}>
<UnorderedListOutlined />
</div>
{/* </Space> */}
</div>
</div>
{/* content */}
<div class={styles['jtable-content']}>
{
model.value === ModelEnum.CARD ?
<div class={styles['jtable-card']}>
{
dataSource.value.length ?
<div
class={styles['jtable-card-items']}
style={{gridTemplateColumns: `repeat(${column.value}, 1fr)`}}
>
{
dataSource.value.map(item => slots.cardRender ?
<div class={[styles['jtable-card-item'], props.cardBodyClass]}>{slots.cardRender(item)}</div>
: null)
}
</div> :
<div><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>
}
</div> :
<div>
<Table
dataSource={dataSource.value}
columns={props.columns}
pagination={false}
/>
</div>
}
</div>
{/* 分页 */}
{
dataSource.value.length &&
<div class={styles['jtable-pagination']}>
<Pagination
size="small"
total={50}
showTotal={(total) => {
const min = 1
const max = 1
return `${min} - ${max} 条/总共 ${total}`
}}
onChange={() => {
}}
onShowSizeChange={() => {
}}
/>
</div>
}
</div>
}
})
export default JTable

View File

@ -3,7 +3,8 @@ import AIcon from './AIcon'
import PermissionButton from './PermissionButton/index.vue'
import JTable from './Table/index.vue'
import TitleComponent from "./TitleComponent/index.vue";
import Form from './Form'
import Form from './Form';
import CardBox from './CardBox/index.vue';
export default {
install(app: App) {
@ -12,5 +13,6 @@ export default {
.component('JTable', JTable)
.component('TitleComponent', TitleComponent)
.component('Form', Form)
.component('CardBox', CardBox)
}
}

View File

@ -59,6 +59,10 @@ export default [
path: '/link/certificate/detail/add',
component: () => import('@/views/link/Certificate/Detail/index.vue')
},
{
path: '/link/accessConfig',
component: () => import('@/views/link/AccessConfig/index.vue')
},
{
path: '/link/accessConfig/detail/add',
component: () => import('@/views/link/AccessConfig/Detail/index.vue')

View File

@ -0,0 +1,4 @@
.ant-form-item-required:before {
position: absolute;
right: -12px;
}

View File

@ -4,7 +4,7 @@
<div class="content">
<div class="title">第三方账户绑定</div>
<!-- 已登录-绑定三方账号 -->
<template v-if="false">
<template v-if="!token">
<div class="info">
<a-card style="width: 280px">
<template #title>
@ -28,14 +28,21 @@
</div>
</template>
<div class="info-body">
<img :src="getImage('/bind/wechat-webapp.png')" />
<img
:src="
accountInfo?.avatar ||
getImage('/bind/wechat-webapp.png')
"
/>
<p>用户名-</p>
<p>名称微信昵称</p>
<p>名称{{ accountInfo?.name || '-' }}</p>
</div>
</a-card>
</div>
<div class="btn">
<a-button type="primary">立即绑定</a-button>
<a-button type="primary" @click="handleBind"
>立即绑定</a-button
>
</div>
</template>
<!-- 未登录-绑定三方账号 -->
@ -74,23 +81,25 @@
</a-form-item>
<a-form-item
label="验证码"
v-bind="validateInfos.captcha"
v-bind="validateInfos.verifyCode"
>
<a-input
v-model:value="formData.captcha"
v-model:value="formData.verifyCode"
placeholder="请输入验证码"
>
<template #addonAfter>
<span style="cursor: pointer">
图形验证码
</span>
<img
:src="captcha.base64"
@click="getCode"
style="cursor: pointer"
/>
</template>
</a-input>
</a-form-item>
<a-form-item>
<a-button
type="primary"
@click="handleSubmit"
@click="handleLoginBind"
style="width: 100%"
>
登录并绑定账户
@ -105,32 +114,58 @@
</template>
<script setup lang="ts">
import { getImage } from '@/utils/comm';
import { getImage, LocalStore } from '@/utils/comm';
import { TOKEN_KEY } from '@/utils/variable';
import { Form } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { applicationInfo } from '@/api/bind';
import { applicationInfo, bindAccount } from '@/api/bind';
import { code, authLogin } from '@/api/login';
const useForm = Form.useForm;
interface formData {
username: string;
password: string;
captcha: string;
verifyCode: string;
}
const token = computed(() => LocalStore.get(TOKEN_KEY));
//
const getUrlCode = () => {
const url = new URLSearchParams(window.location.href);
return url.get('code') as string;
};
//
const accountInfo = ref({
avatar: '',
name: '',
});
const getAppInfo = async () => {
const code: string = '73ab60c88979a1475963a5dde31e374b';
const code = getUrlCode();
const res = await applicationInfo(code);
console.log('getAppInfo: ', res);
accountInfo.value = res?.result?.result;
};
getAppInfo();
//
/**
* 立即绑定
*/
const handleBind = async () => {
const code = getUrlCode();
const res = await bindAccount(code);
console.log('bindAccount: ', res);
message.success('绑定成功');
goRedirect();
setTimeout(() => window.close(), 1000);
};
// -
const formData = ref<formData>({
username: '',
password: '',
captcha: '',
verifyCode: '',
});
const formRules = ref({
username: [
@ -145,7 +180,7 @@ const formRules = ref({
message: '请输入密码',
},
],
captcha: [
verifyCode: [
{
required: true,
message: '请输入验证码',
@ -158,17 +193,40 @@ const { resetFields, validate, validateInfos } = useForm(
formRules.value,
);
/**
* 获取图形验证码
*/
const captcha = ref({
base64: '',
key: '',
});
const getCode = async () => {
const res: any = await code();
captcha.value = res.result;
};
getCode();
/**
* 登录并绑定账户
*/
const handleSubmit = () => {
const handleLoginBind = () => {
validate()
.then(() => {
console.log('toRaw:', toRaw(formData.value));
console.log('formData.value:', formData.value);
.then(async () => {
const code = getUrlCode();
const params = {
...formData.value,
verifyKey: captcha.value.key,
bindCode: code,
expires: 3600000,
};
const res = await authLogin(params);
console.log('res: ', res);
message.success('登录成功');
goRedirect();
setTimeout(() => window.close(), 1000);
})
.catch((err) => {
console.log('error', err);
getCode();
});
};

View File

@ -1,9 +1,59 @@
<template>
<Form />
<Form
ref='form'
:options='options'
:initValue='initValue'
/>
<a-button @click='submit'>提交</a-button>
<a-button @click='reset'>重置</a-button>
<a-button @click='setValue'>修改name</a-button>
</template>
<script setup name='FormDemo'>
const data = reactive({})
import { componentType } from 'components/Form'
const form = ref()
const initValue = reactive({})
const submit = () => {
form.value.formValidate().then(res => {
console.log(res)
})
}
const reset = () => {
}
const setValue =() => {
initValue.name = '111111'
}
const options = reactive({
name: {
component: componentType.input,
componentProps: {
style: {
width: '200px'
}
},
title: '测试',
required: true
},
sex: {
component: componentType.select,
title: '性别',
options: [
{ label: '111', value: 1 },
{ label: '222', value: 2 },
],
required: true,
rules: [
{ required: true, message: '请选择性别'}
],
tooltip: '性别',
default: 1
}
})
</script>
<style scoped>

View File

@ -11,8 +11,8 @@
status="disable"
:statusNames="{ disable: StatusColorEnum.error }"
statusText="正常"
:showMask="false"
:actions="actions"
v-model="data"
>
<template #img>
<img :src="getImage('/device-product.png')" />
@ -63,6 +63,10 @@ const actions = ref([
label: '删除',
},
]);
const data = ref({
id: 123
})
</script>
<style lang="less" scoped>

View File

@ -3,41 +3,143 @@
<JTable
:columns="[
{
title: '名',
title: '',
dataIndex: 'name',
key: 'name',
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
title: 'ID',
dataIndex: 'id',
key: 'id',
scopedSlots: true
},
{
title: '住址',
dataIndex: 'address',
key: 'address',
}
title: '分类',
dataIndex: 'classifiedName',
key: 'classifiedName',
},
{
title: '操作',
key: 'action',
fixed: 'right',
width: 250,
scopedSlots: true
}
]"
:actions="actions"
:request="request"
:rowSelection="{
selectedRowKeys: _selectedRowKeys,
onChange: onSelectChange
}"
@cancelSelect="cancelSelect"
>
<template #headerTitle>
<a-button type="primary">新增</a-button>
</template>
<template #cardRender="slotProps">
<CardBox>
<template #card="slotProps">
<CardBox :value="slotProps" @click="handleClick" :actions="actions" v-bind="slotProps" :active="_selectedRowKeys.includes(slotProps.id)">
<template #img>
<slot name="img">
<img :src="getImage('/device-product.png')" />
</slot>
</template>
<template #content>
{{slotProps.item.name}}
<h3>{{slotProps.name}}</h3>
<a-row>
<a-col :span="12">
<div class="card-item-content-text">
设备类型
</div>
<div>直连设备</div>
</a-col>
<a-col :span="12">
<div class="card-item-content-text">
产品名称
</div>
<div>测试固定地址</div>
</a-col>
</a-row>
</template>
</CardBox>
</template>
<template #id="slotProps">
<a>{{slotProps.row.id}}</a>
</template>
<template #action="slotProps">
<a-space :size="16">
<a-tooltip v-for="i in actions" :key="i.key" v-bind="i.tooltip">
<a-popconfirm v-if="i.popConfirm" v-bind="i.popConfirm">
<a-button style="padding: 0" type="link"><AIcon :type="i.icon" /></a-button>
</a-popconfirm>
<a-button style="padding: 0" type="link" v-else @click="i.onClick && i.onClick(slotProps)">
<AIcon :type="i.icon" />
</a-button>
</a-tooltip>
</a-space>
</template>
</JTable>
</div>
</template>
<script setup lang="ts">
import server from "@/utils/request";
import CardBox from '@/components/CardBox/index.vue';
import type { ActionsType } from '@/components/Table/index.vue'
import { getImage } from '@/utils/comm';
const request = (data: any) => server.post(`/device-product/_query`, data)
const actions: ActionsType[] = [
{
key: 'edit',
// disabled: true,
text: "编辑",
tooltip: {
title: '编辑'
},
icon: 'icon-rizhifuwu'
},
{
key: 'import',
// disabled: true,
text: "导入",
tooltip: {
title: '导入'
},
icon: 'icon-xiazai'
},
{
key: 'delete',
// disabled: true,
text: "删除",
tooltip: {
title: '删除'
},
popConfirm: {
title: '确认删除?'
},
}
]
const _selectedRowKeys = ref<string[]>([])
const onSelectChange = (keys: string[]) => {
_selectedRowKeys.value = [...keys]
}
const cancelSelect = () => {
_selectedRowKeys.value = []
}
const handleClick = (dt: any) => {
// _selectedRowKeys.value = [dt.id] //
// _selectedRowKeys.value = [..._selectedRowKeys.value, dt.id] //
if(_selectedRowKeys.value.includes(dt.id)) {
const _index = _selectedRowKeys.value.findIndex(i => i === dt.id)
_selectedRowKeys.value.splice(_index, 1)
} else {
_selectedRowKeys.value = [..._selectedRowKeys.value, dt.id]
}
}
</script>

View File

@ -30,18 +30,10 @@
重置
</a-button>
</div>
<a-table
:columns="columns"
:data-source="tableData"
:row-selection="{
onChange: (selectedRowKeys, selectedRows) =>
(selectItem = selectedRows),
type: 'radio',
}"
>
</a-table>
<JTable :columns="columns">
</JTable>
<template #footer>
<a-button key="back" @click="visible = false">取消</a-button>
<a-button key="submit" type="primary" @click="handleOk"
@ -90,9 +82,7 @@ const productList = ref<[productItem] | []>([]);
const getOptions = () => {
productList.value = [];
};
const clickSearch = ()=>{
}
const clickSearch = () => {};
const clickReset = () => {
Object.entries(form.value).forEach(([prop]) => {
form.value[prop] = '';
@ -102,27 +92,27 @@ const clickReset = () => {
//
const columns = [
{
name: 'deviceId',
title: '设备Id',
dataIndex: 'deviceId',
key: 'deviceId',
},
{
name: 'deviceName',
title: '设备名称',
dataIndex: 'deviceName',
key: 'deviceName',
},
{
name: 'productName',
title: '产品名称',
dataIndex: 'productName',
key: 'productName',
},
{
name: 'createTime',
title: '注册时间',
dataIndex: 'createTime',
key: 'createTime',
},
{
name: 'status',
title: '状态',
dataIndex: 'status',
key: 'status',
},

View File

@ -1,21 +1,30 @@
const MetworkTypeMapping = new Map();
MetworkTypeMapping.set('websocket-server', 'WEB_SOCKET_SERVER');
MetworkTypeMapping.set('http-server-gateway', 'HTTP_SERVER');
MetworkTypeMapping.set('udp-device-gateway', 'UDP');
MetworkTypeMapping.set('coap-server-gateway', 'COAP_SERVER');
MetworkTypeMapping.set('mqtt-client-gateway', 'MQTT_CLIENT');
MetworkTypeMapping.set('mqtt-server-gateway', 'MQTT_SERVER');
MetworkTypeMapping.set('tcp-server-gateway', 'TCP_SERVER');
const ProcotoleMapping = new Map();
ProcotoleMapping.set('websocket-server', 'WebSocket');
ProcotoleMapping.set('http-server-gateway', 'HTTP');
ProcotoleMapping.set('udp-device-gateway', 'UDP');
ProcotoleMapping.set('coap-server-gateway', 'CoAP');
ProcotoleMapping.set('mqtt-client-gateway', 'MQTT');
ProcotoleMapping.set('mqtt-server-gateway', 'MQTT');
ProcotoleMapping.set('tcp-server-gateway', 'TCP');
ProcotoleMapping.set('child-device', '');
const ProtocolMapping = new Map();
ProtocolMapping.set('websocket-server', 'WebSocket');
ProtocolMapping.set('http-server-gateway', 'HTTP');
ProtocolMapping.set('udp-device-gateway', 'UDP');
ProtocolMapping.set('coap-server-gateway', 'CoAP');
ProtocolMapping.set('mqtt-client-gateway', 'MQTT');
ProtocolMapping.set('mqtt-server-gateway', 'MQTT');
ProtocolMapping.set('tcp-server-gateway', 'TCP');
ProtocolMapping.set('child-device', '');
ProtocolMapping.set('OneNet', 'HTTP');
ProtocolMapping.set('Ctwing', 'HTTP');
ProtocolMapping.set('modbus-tcp', 'MODBUS_TCP');
ProtocolMapping.set('opc-ua', 'OPC_UA');
ProtocolMapping.set('edge-child-device', 'EdgeGateway');
ProtocolMapping.set('official-edge-gateway', 'MQTT');
const NetworkTypeMapping = new Map();
NetworkTypeMapping.set('websocket-server', 'WEB_SOCKET_SERVER');
NetworkTypeMapping.set('http-server-gateway', 'HTTP_SERVER');
NetworkTypeMapping.set('udp-device-gateway', 'UDP');
NetworkTypeMapping.set('coap-server-gateway', 'COAP_SERVER');
NetworkTypeMapping.set('mqtt-client-gateway', 'MQTT_CLIENT');
NetworkTypeMapping.set('mqtt-server-gateway', 'MQTT_SERVER');
NetworkTypeMapping.set('tcp-server-gateway', 'TCP_SERVER');
NetworkTypeMapping.set('official-edge-gateway', 'MQTT_SERVER');
const descriptionList = {
'udp-device-gateway':
@ -96,4 +105,4 @@ const columnsHTTP = [
},
]
export { MetworkTypeMapping, ProcotoleMapping, descriptionList, columnsMQTT, columnsHTTP };
export { NetworkTypeMapping, ProtocolMapping, descriptionList, columnsMQTT, columnsHTTP };

View File

@ -1,62 +1,93 @@
<template>
<a-card :bordered="false">
<TitleComponent data="自定义设备接入"></TitleComponent>
<div>
<a-row :gutter="[24, 24]">
<a-col :span="12" v-for="item in items" :key="item.id">
<div class="provider">
<div class="box">
<div class="left">
<div class="images">
<img :src="backMap.get(item.id)" />
</div>
<div class="context">
<div class="title">{{ item.name }}</div>
<div class="desc">
<a-tooltip :title="item.description">
{{ item.description || '' }}
</a-tooltip>
</div>
</div>
</div>
<div class="right">
<a-button
type="primary"
@click="goProviders(item)"
>接入</a-button
>
</div>
</div>
</div>
</a-col>
</a-row>
</div>
</a-card>
<a-spin :spinning="loading">
<a-card :bordered="false">
<div v-if="type">
<Provider
@onClick="goProviders"
:dataSource="dataSource"
></Provider>
</div>
<div v-else>
<div v-if="!id"><a @click="goBack">返回</a></div>
<AccessNetwork :provider="provider" :data="data" />
</div>
</a-card>
</a-spin>
</template>
<script lang="ts" setup name="AccessConfigDetail">
import { getImage } from '@/utils/comm';
import TitleComponent from '@/components/TitleComponent/index.vue';
import AccessNetwork from '../components/Network.vue';
import Provider from '../components/Provider/index.vue';
import { getProviders, detail } from '@/api/link/accessConfig';
const items = [
{ id: 'mqtt-server-gateway', name: '测试1', description: '测试1' },
{ id: 'websocket-server', name: '测试2', description: '测试' },
{ id: 'coap-server-gateway', name: '测试3', description: '测试' },
];
// const router = useRouter();
const route = useRoute();
const backMap = new Map();
backMap.set('mqtt-server-gateway', getImage('/access/mqtt.png'));
backMap.set('websocket-server', getImage('/access/websocket.png'));
backMap.set('coap-server-gateway', getImage('/access/coap.png'));
backMap.set('tcp-server-gateway', getImage('/access/tcp.png'));
backMap.set('child-device', getImage('/access/child-device.png'));
backMap.set('http-server-gateway', getImage('/access/http.png'));
backMap.set('udp-device-gateway', getImage('/access/udp.png'));
backMap.set('mqtt-client-gateway', getImage('/access/mqtt-broke.png'));
const id = route.query.id;
const goProviders = (value: object) => {
console.log(111, value);
const dataSource = ref([]);
const type = ref(false);
const loading = ref(true);
const provider = ref({});
const data = ref({});
const goProviders = (param: object) => {
provider.value = param;
type.value = false;
};
const goBack = () => {
provider.value = {};
type.value = true;
};
const queryProviders = async () => {
const resp = await getProviders();
if (resp.status === 200) {
dataSource.value = resp.result.filter(
(item) =>
item.channel === 'network' || item.channel === 'child-device',
);
}
};
const getProvidersData = async () => {
if (id) {
getProviders().then((response) => {
if (response.status === 200) {
dataSource.value = response.result.filter(
(item) =>
item.channel === 'network' ||
item.channel === 'child-device',
);
detail(id).then((resp) => {
if (resp.status === 200) {
const dt = response.result.find(
(item) => item?.id === resp.result.provider,
);
provider.value = dt;
data.value = resp.result;
type.value = false;
}
});
loading.value = false;
} else {
loading.value = false;
}
});
} else {
type.value = true;
queryProviders();
loading.value = false;
}
};
onMounted(() => {
loading.value = true;
getProvidersData();
});
</script>
<style lang="less" scoped>

View File

@ -0,0 +1,86 @@
<template>
<a-card hoverable :class="['card-render', checked === data.id ? 'checked' : '']" @click="checkedChange(data.id)">
<div class="title">
<a-tooltip placement="topLeft" :title="data.name">{{ data.name }}</a-tooltip>
</div>
<slot name="other"></slot>
<div class="desc">
<a-tooltip placement="topLeft" :title="data.description">{{ data.description }}</a-tooltip>
</div>
<div class="checked-icon">
<div><a-icon type="check" /></div>
</div>
</a-card>
</template>
<script>
export default {
name: "AccessCard",
props: ['data', 'checked'],
methods: {
checkedChange(id){
this.$emit('checkedChange', id)
}
}
};
</script>
<style lang="less" scoped>
.card-render {
width: 100%;
overflow: hidden;
background: url("/public/images/access/access.png") no-repeat;
background-size: 100% 100%;
min-height: 105px;
.title {
width: calc(100% - 88px);
overflow: hidden;
font-weight: 800;
white-space: nowrap;
text-overflow: ellipsis;
}
.desc {
width: 100%;
margin-top: 10px;
color: rgba(0, 0, 0, 0.55);
font-weight: 400;
font-size: 13px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.checked-icon {
position: absolute;
right: -22px;
bottom: -22px;
z-index: 2;
display: none;
width: 44px;
height: 44px;
color: #fff;
background-color: red;
background-color: #2f54eb;
transform: rotate(-45deg);
> div {
position: relative;
height: 100%;
transform: rotate(45deg);
font-size: 12px;
padding: 4px 0 0 6px;
}
}
&.checked {
position: relative;
color: #2f54eb;
border-color: #2f54eb;
.checked-icon {
display: block;
}
}
}
</style>

View File

@ -0,0 +1,733 @@
<template>
<div style="margin-top: 10px">
<a-steps :current="stepCurrent">
<a-step v-for="item in steps" :key="item" :title="item" />
</a-steps>
<div class="steps-content">
<div class="steps-box" v-if="current === 0">
<div class="alert">
<a-icon type="info-circle" style="margin-right: 10px" />
选择与设备通信的网络组件
</div>
<div class="search">
<a-input-search
allowClear
placeholder="请输入"
style="width: 300px"
@search="networkSearch"
/>
<a-button type="primary" @click="addNetwork">新增</a-button>
</div>
<div class="card-item">
<a-row :gutter="[24, 24]" v-if="networkList.length > 0">
<a-col
:span="8"
v-for="item in networkList"
:key="item.id"
>
<access-card
@checkedChange="checkedChange"
:checked="networkCurrent"
:data="{
...item,
description: item.description
? item.description
: descriptionList[provider.id],
}"
>
<div slot="other" class="other">
<a-tooltip placement="topLeft">
<div
slot="title"
v-if="
(item.addresses || []).length >
1
"
>
<div
v-for="i in item.addresses ||
[]"
:key="i.address"
class="item"
>
<a-badge
:color="
i.health === -1
? 'red'
: 'green'
"
/>{{ i.address }}
</div>
</div>
<div
v-for="i in (
item.addresses || []
).slice(0, 1)"
:key="i.address"
class="item"
>
<a-badge
:color="
i.health === -1
? 'red'
: 'green'
"
:text="i.address"
/>
<span
v-if="
(item.addresses || [])
.length > 1
"
>...</span
>
</div>
</a-tooltip>
</div>
</access-card>
</a-col>
</a-row>
<a-empty v-else description="暂无数据" />
</div>
</div>
<div class="steps-box" v-else-if="current === 1">
<div class="alert">
<a-icon type="info-circle" style="margin-right: 10px" />
使用选择的消息协议对网络组件通信数据进行编解码认证等操作
</div>
<div class="search">
<a-input-search
allowClear
placeholder="请输入"
style="width: 300px"
@search="procotolSearch"
/>
<a-button type="primary" @click="addProcotol"
>新增</a-button
>
</div>
<div class="card-item">
<a-row :gutter="[24, 24]" v-if="procotolList.length > 0">
<a-col
:span="8"
v-for="item in procotolList"
:key="item.id"
>
<access-card
@checkedChange="procotolChange"
:checked="procotolCurrent"
:data="item"
>
</access-card>
</a-col>
</a-row>
<a-empty v-else description="暂无数据" />
</div>
</div>
<div class="steps-box" v-else>
<div class="card-last">
<a-row :gutter="[24, 24]">
<a-col :span="12">
<title-component data="基本信息" />
<div>
<a-form :form="form" layout="vertical">
<a-form-item label="名称">
<a-input
allowClear
placeholder="请输入名称"
v-decorator="[
'name',
{
initialValue: data.name,
rules: [
{
required: true,
message:
'请输入名称!',
},
],
},
]"
/>
</a-form-item>
<a-form-item label="说明">
<a-textarea
placeholder="请输入说明"
:rows="4"
v-decorator="[
'description',
{
initialValue:
data.description,
},
]"
/>
</a-form-item>
</a-form>
</div>
</a-col>
<a-col :span="12">
<div class="config-right">
<div class="config-right-item">
<div class="config-right-item-title">
接入方式
</div>
<div class="config-right-item-context">
{{ provider.name }}
</div>
<div class="config-right-item-context">
{{ provider.description }}
</div>
</div>
<div class="config-right-item">
<div class="config-right-item-title">
消息协议
</div>
<div class="config-right-item-context">
{{
procotolList.find(
(i) => i.id === procotolCurrent,
).name
}}
</div>
<div
class="config-right-item-context"
v-if="config.document"
>
{{ config.document }}
</div>
</div>
<div
class="config-right-item"
v-if="
networkList.find(
(i) => i.id === networkCurrent,
) &&
(
networkList.find(
(i) => i.id === networkCurrent,
).addresses || []
).length > 0
"
>
<div class="config-right-item-title">
网络组件
</div>
<div
v-for="i in (networkList.find(
(i) => i.id === networkCurrent,
) &&
networkList.find(
(i) => i.id === networkCurrent,
).addresses) ||
[]"
:key="i.address"
>
<a-badge
:color="
i.health === -1
? 'red'
: 'green'
"
:text="i.address"
/>
</div>
</div>
<div
class="config-right-item"
v-if="
config.routes &&
config.routes.length > 0
"
>
<div class="config-right-item-title">
{{
data.provider ===
'mqtt-server-gateway' ||
data.provider ===
'mqtt-client-gateway'
? 'topic'
: 'URL信息'
}}
</div>
<a-table
:pagination="false"
:rowKey="generateUUID()"
:data-source="config.routes || []"
bordered
:columns="columnsMQTT"
:scroll="{ y: 300 }"
>
<template
slot="stream"
slot-scope="text, record"
>
<span
v-if="
record.upstream &&
record.downstream
"
>上行下行</span
>
<span v-else-if="record.upstream"
>上行</span
>
<span v-else-if="record.downstream"
>下行</span
>
</template>
</a-table>
</div>
</div>
</a-col>
</a-row>
</div>
</div>
</div>
<div class="steps-action">
<a-button
v-if="[0, 1].includes(current)"
type="primary"
@click="next"
>
下一步
</a-button>
<a-button v-if="current === 2" type="primary" @click="save">
保存
</a-button>
<a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
上一步
</a-button>
</div>
</div>
</template>
<script lang="ts" setup name="AccessNetwork">
import {
getNetworkList,
getProtocolList,
getConfigView,
save,
update,
getChildConfigView,
} from '@/api/link/accessConfig';
import {
descriptionList,
NetworkTypeMapping,
ProtocolMapping,
} from '../Detail/data';
import AccessCard from './AccessCard/index.vue';
import TitleComponent from '@/components/TitleComponent/index.vue';
import { message, Form } from 'ant-design-vue';
function generateUUID() {
var d = new Date().getTime();
if (
typeof performance !== 'undefined' &&
typeof performance.now === 'function'
) {
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
},
);
}
const props = defineProps({
provider: {
type: Object,
default: () => {},
},
data: {
type: Object,
default: () => {},
},
});
const current = ref(0);
const stepCurrent = ref(0);
const steps = ref(['网络组件', '消息协议', '完成']);
const networkList = ref([]);
const procotolList = ref([]);
const allProcotolList = ref([]);
const networkCurrent = ref('');
const procotolCurrent = ref('');
let config = ref({});
let columnsMQTT = ref([]);
const form = reactive({
name: 'access',
description: '',
});
const queryNetworkList = async (id: string, params: object, data = {}) => {
console.log('queryNetworkList',NetworkTypeMapping.get(id), data, params);
const resp = await getNetworkList(NetworkTypeMapping.get(id), data, params);
if (resp.status === 200) {
networkList.value = resp.result;
}
};
// const queryProcotolList=async(id:string, params:object) =>{
const queryProcotolList = async (id: string, params = {}) => {
const resp = await getProtocolList(ProtocolMapping.get(id), {
...params,
'sorts[0].name': 'createTime',
'sorts[0].order': 'desc',
});
if (resp.status === 200) {
procotolList.value = resp.result;
allProcotolList.value = resp.result;
}
};
const addNetwork = () => {
// const url = this.$store.state.permission.routes['Link/Type/Detail']
const url = '/demo';
const tab = window.open(
`${window.location.origin + window.location.pathname}#${url}?type=${
NetworkTypeMapping.get(props.provider?.id) || ''
}`,
);
tab.onTabSaveSuccess = (value) => {
if (value.success) {
networkCurrent.value = value.result.id;
queryNetworkList(props.provider?.id, {
include: networkCurrent.value || '',
});
}
};
};
const addProcotol = () => {
// const url = this.$store.state.permission.routes['Link/Protocol']
const url = '/demo';
const tab = window.open(
`${window.location.origin + window.location.pathname}#${url}?save=true`,
);
tab.onTabSaveSuccess = (value) => {
if (value.success) {
procotolCurrent.value = value.result?.id;
queryProcotolList(props.provider?.id);
}
};
};
const checkedChange = (id: string) => {
networkCurrent.value = id;
};
const networkSearch = (value: string) => {
console.log('networkSearch',
props.provider.id,
{
include: networkCurrent.value || '',
},
{
terms: [
{
column: 'name$LIKE',
value: `%${value}%`,
},
],
},
);
queryNetworkList(
props.provider.id,
{
include: networkCurrent.value || '',
},
{
terms: [
{
column: 'name$LIKE',
value: `%${value}%`,
},
],
},
);
};
const procotolChange = (id: string) => {
if (!props.data.id) {
procotolCurrent.value = id;
}
};
const procotolSearch = (value: string) => {
if (value) {
const list = allProcotolList.value.filter((i) => {
return (
i.name &&
i.name.toLocaleLowerCase().includes(value.toLocaleLowerCase())
);
});
procotolList.value = list;
} else {
procotolList.value = allProcotolList.value;
}
};
const saveData = () => {
form.validateFields(async (err, values) => {
if (!err) {
let resp = undefined;
if (props.data && props.data.id) {
resp = await update({
...props.data,
name: values.name,
description: values.description,
protocol: procotolCurrent.value,
channel: 'network', //
channelId: networkCurrent.value,
});
} else {
resp = await save({
name: values.name,
description: values.description,
provider: props.provider.id,
protocol: procotolCurrent.value,
transport:
props.provider?.id === 'child-device'
? 'Gateway'
: ProtocolMapping.get(props.provider.id),
channel: 'network', //
channelId: networkCurrent.value,
});
}
if (resp.status === 200) {
message.success('操作成功!');
//
if (window.onTabSaveSuccess) {
window.onTabSaveSuccess(resp);
setTimeout(() => window.close(), 300);
} else {
// this.$store.dispatch('jumpPathByKey', { key: MenuKeys['Link/AccessConfig'] })
}
}
}
});
};
const next = async () => {
if (current.value === 0) {
if (!networkCurrent.value) {
message.error('请选择网络组件!');
} else {
queryProcotolList(props.provider.id);
current.value -= current.value;
}
} else if (current.value === 1) {
if (!procotolCurrent.value) {
message.error('请选择消息协议!');
} else {
const resp =
props.provider.channel !== 'child-device'
? await getConfigView(
procotolCurrent.value,
ProtocolMapping.get(props.provider.id),
)
: await getChildConfigView(procotolCurrent.value);
if (resp.status === 200) {
config.value = resp.result;
current.value += current.value;
columnsMQTT = [
{
title: '分组',
dataIndex: 'group',
key: 'group',
ellipsis: true,
align: 'center',
width: 100,
customRender: (value, row, index) => {
const obj = {
children: value,
attrs: {},
};
const list = (config && config.routes) || [];
const arr = list.filter((res) => {
return res.group == row.group;
});
if (
index == 0 ||
list[index - 1].group !== row.group
) {
obj.attrs.rowSpan = arr.length;
} else {
obj.attrs.rowSpan = 0;
}
return obj;
},
},
{
title: 'topic',
dataIndex: 'topic',
key: 'topic',
ellipsis: true,
},
{
title: '上下行',
dataIndex: 'stream',
key: 'stream',
ellipsis: true,
align: 'center',
width: 100,
scopedSlots: { customRender: 'stream' },
},
{
title: '说明',
dataIndex: 'description',
key: 'description',
ellipsis: true,
},
];
}
}
}
};
const prev = () => {
const currentValue = current.value;
current.value -= currentValue;
};
onMounted(() => {
if (props.data && props.data.id) {
if (props.data.provider !== 'child-device') {
procotolCurrent.value = props.data.protocol;
current.value = 0;
networkCurrent.value = props.data.channelId;
console.log(11111111,props.provider.id, {
include: networkCurrent.value,
});
queryNetworkList(props.provider.id, {
include: networkCurrent.value,
});
procotolCurrent.value = props.data.protocol;
steps.value = ['网络组件', '消息协议', '完成'];
} else {
steps.value = ['消息协议', '完成'];
current.value = 1;
queryProcotolList(props.provider.id);
}
} else {
if (props.provider?.id) {
if (props.provider.channel !== 'child-device') {
console.log(3333333, props.provider.id, {
include: '',
});
queryNetworkList(props.provider.id, {
include: '',
});
steps.value = ['网络组件', '消息协议', '完成'];
current.value = 0;
} else {
console.log(444444,props.provider.id);
steps.value = ['消息协议', '完成'];
current.value = 1;
queryProcotolList(props.provider.id);
}
}
}
});
// watch(
// () => props.modelValue,
// (v) => {
// keystoreBase64.value = v;
// },
// {
// deep: true,
// immediate: true,
// },
// );
// watch: {
// current(val) {
// if (this.provider.channel !== 'child-device') {
// this.stepCurrent = val
// } else {
// this.stepCurrent = val - 1
// }
// },
// },
</script>
<style lang="less" scoped>
.steps-content {
margin: 20px;
}
.steps-box {
min-height: 400px;
.card-item {
padding-right: 5px;
max-height: 480px;
overflow-y: auto;
overflow-x: hidden;
}
.card-last {
padding-right: 5px;
max-height: 580px;
overflow-y: auto;
overflow-x: hidden;
}
}
.steps-action {
width: 100%;
margin-top: 24px;
margin-left: 20px;
}
.alert {
height: 40px;
padding-left: 10px;
color: rgba(0, 0, 0, 0.55);
line-height: 40px;
background-color: #f6f6f6;
}
.search {
display: flex;
margin: 15px 0;
justify-content: space-between;
}
.other {
width: 100%;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.item {
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.config-right {
padding: 20px;
color: rgba(0, 0, 0, 0.8);
background: rgba(0, 0, 0, 0.04);
.config-right-item {
margin-bottom: 10px;
.config-right-item-title {
width: 100%;
margin-bottom: 10px;
font-weight: 600;
}
.config-right-item-context {
margin: 5px 0;
color: rgba(0, 0, 0, 0.8);
}
}
}
</style>

View File

@ -0,0 +1,145 @@
<template>
<TitleComponent data="自定义设备接入"></TitleComponent>
<div>
<a-row :gutter="[24, 24]">
<a-col :span="12" v-for="item in dataSource" :key="item.id">
<div class="provider">
<div class="box">
<div class="left">
<div class="images">
<img :src="backMap.get(item.id)" />
</div>
<div class="context">
<div class="title">
{{ item.name }}
</div>
<div class="desc">
<a-tooltip :title="item.description">
{{ item.description || '' }}
</a-tooltip>
</div>
</div>
</div>
<div class="right">
<a-button type="primary" @click="click(item)"
>接入</a-button
>
</div>
</div>
</div>
</a-col>
</a-row>
</div>
</template>
<script lang="ts" setup name="AccessConfigProvider">
import TitleComponent from '@/components/TitleComponent/index.vue';
import { getImage } from '@/utils/comm';
const props = defineProps({
dataSource: {
type: Array,
default: () => [],
},
});
const emit = defineEmits(['onClick']);
const backMap = new Map();
backMap.set('mqtt-server-gateway', getImage('/access/mqtt.png'));
backMap.set('websocket-server', getImage('/access/websocket.png'));
backMap.set('modbus-tcp', getImage('/access/modbus.png'));
backMap.set('coap-server-gateway', getImage('/access/coap.png'));
backMap.set('tcp-server-gateway', getImage('/access/tcp.png'));
backMap.set('Ctwing', getImage('/access/ctwing.png'));
backMap.set('child-device', getImage('/access/child-device.png'));
backMap.set('opc-ua', getImage('/access/opc-ua.png'));
backMap.set('http-server-gateway', getImage('/access/http.png'));
backMap.set('fixed-media', getImage('/access/video-device.png'));
backMap.set('udp-device-gateway', getImage('/access/udp.png'));
backMap.set('OneNet', getImage('/access/onenet.png'));
backMap.set('gb28181-2016', getImage('/access/gb28181.png'));
backMap.set('mqtt-client-gateway', getImage('/access/mqtt-broke.png'));
backMap.set('edge-child-device', getImage('/access/child-device.png'));
backMap.set('official-edge-gateway', getImage('/access/edge.png'));
const click = (value: object) => {
emit('onClick', value);
};
</script>
<style lang="less" scoped>
.provider {
position: relative;
width: 100%;
padding: 20px;
background: url('/public/images/access/background.png') no-repeat;
background-size: 100% 100%;
border: 1px solid #e6e6e6;
&::before {
position: absolute;
top: 0;
left: 40px;
display: block;
width: 15%;
min-width: 64px;
height: 2px;
background-image: url('/public/images/access/rectangle.png');
background-repeat: no-repeat;
background-size: 100% 100%;
// border: 1px #8da1f4 solid;
// border-bottom-left-radius: 10%;
// border-bottom-right-radius: 10%;
content: ' ';
}
&:hover {
box-shadow: 0 0 24px rgba(#000, 0.1);
}
}
.box {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
.left {
display: flex;
width: calc(100% - 70px);
.images {
width: 64px;
height: 64px;
img {
width: 100%;
}
}
.context {
width: calc(100% - 84px);
margin: 10px;
.title {
font-weight: 600;
}
.desc {
width: 100%;
margin-top: 10px;
overflow: hidden;
color: rgba(0, 0, 0, 0.55);
font-weight: 400;
font-size: 13px;
white-space: nowrap;
text-overflow: ellipsis;
}
}
}
.right {
width: 70px;
}
}
</style>

View File

@ -1,11 +1,18 @@
<template>
<a-button type="primary" @click="handlAdd">新增</a-button>
<a-button type="primary" @click="handlAdd">新增</a-button>
</template>
<script lang="ts" setup name="AccessConfigPage">
const router = useRouter();
const handlAdd = (e: any) => {
console.log(111,e);
// const handlAdd = () => {
// router.push({
// path: '/link/accessConfig/detail/add',
// query: {
// id: '1610475400026861568',
// },
// });
// };
const handlAdd = () => {
router.push('/link/accessConfig/detail/add');
}
</script>

View File

@ -64,16 +64,14 @@ const handleChange = (info: UploadChangeParam) => {
message.success('上传成功!');
const result = info.file.response?.result;
keystoreBase64.value = result;
console.log(1114, result);
loading.value = false;
emit('change', result);
emit('update:modelValue', result);
}
};
const textChange = (val: any) => {
val.name = props.name;
emit('change', val);
// emit('update:modelValue', val);
emit('change', keystoreBase64.value);
emit('update:modelValue', keystoreBase64.value);
};
watch(

View File

@ -10,10 +10,8 @@
:label-col="{ span: 8 }"
:wrapper-col="{ span: 16 }"
autocomplete="off"
@finish="onFinish"
:rules="formRules"
>
<a-form-item label="证书标准" name="type">
<a-form-item label="证书标准" v-bind="validateInfos.type">
<a-radio-group v-model:value="formData.type">
<a-radio-button
class="form-radio-button"
@ -24,25 +22,29 @@
</a-radio-group>
</a-form-item>
<a-form-item label="证书名称" name="name">
<a-form-item label="证书名称" v-bind="validateInfos.name">
<a-input
placeholder="请输入证书名称"
v-model:value="formData.name"
/>
</a-form-item>
<a-form-item label="证书文件" name="cert">
<a-form-item
label="证书文件"
v-bind="validateInfos['configs.cert']"
>
<CertificateFile
name="cert"
v-model:modelValue="formData.cert"
@change="changeFileValue"
v-model:modelValue="formData.configs.cert"
placeholder='证书格式以"-----BEGIN CERTIFICATE-----"开头,以"-----END CERTIFICATE-----"结尾"'
/>
</a-form-item>
<a-form-item label="证书私钥" name="key">
<a-form-item
label="证书私钥"
v-bind="validateInfos['configs.key']"
>
<CertificateFile
name="key"
v-model:modelValue="formData.key"
@change="changeFileValue"
v-model:modelValue="formData.configs.key"
placeholder='证书私钥格式以"-----BEGIN (RSA|EC) PRIVATE KEY-----"开头,以"-----END(RSA|EC) PRIVATE KEY-----"结尾。'
/>
</a-form-item>
@ -61,6 +63,8 @@
class="form-submit"
html-type="submit"
type="primary"
@click.prevent="onSubmit"
:loading="loading"
>保存</a-button
>
</a-form-item>
@ -89,7 +93,7 @@
</template>
<script lang="ts" setup name="CertificateDetail">
import { message } from 'ant-design-vue';
import { message, Form } from 'ant-design-vue';
import { getImage } from '@/utils/comm';
import CertificateFile from './CertificateFile.vue';
import type { UploadChangeParam } from 'ant-design-vue';
@ -101,57 +105,65 @@ import {
} from '@/utils/variable';
import { save } from '@/api/link/certificate';
const router = useRouter();
const useForm = Form.useForm;
const fileLoading = ref(false);
const loading = ref(false);
const formData = reactive({
type: 'common',
name: '',
cert: '',
key: '',
// configs: {
// cert: '',
// key: '',
// },
configs: {
cert: '',
key: '',
},
description: '',
});
const formRules = {
type: [{ required: true, message: '请选择证书标准', trigger: 'blur' }],
name: [
{ required: true, message: '请输入证书名称', trigger: 'blur' },
{ max: 64, message: '最多可输入64个字符' },
],
cert: [{ required: true, message: '请输入或上传文件', trigger: 'blur' }],
key: [{ required: true, message: '请输入或上传文件', trigger: 'blur' }],
description: [{ max: 200, message: '最多可输入200个字符' }],
};
const { resetFields, validate, validateInfos } = useForm(
formData,
reactive({
type: [{ required: true, message: '请选择证书标准', trigger: 'blur' }],
name: [
{ required: true, message: '请输入证书名称', trigger: 'blur' },
{ max: 64, message: '最多可输入64个字符' },
],
'configs.cert': [
{ required: true, message: '请输入或上传文件', trigger: 'blur' },
],
'configs.key': [
{ required: true, message: '请输入或上传文件', trigger: 'blur' },
],
description: [{ max: 200, message: '最多可输入200个字符' }],
}),
);
const onFinish = async (values: any) => {
values.configs = {
cert: formData.cert,
key: formData.key,
};
delete values.cert;
delete values.key;
const response = await save(values)
if (response.status === 200) {
message.success('操作成功')
}
};
const changeFileValue = (v: any) => {
formData[v.name] = v.data;
const onSubmit = () => {
validate()
.then(async (res) => {
const params = toRaw(formData);
loading.value = true;
const response = await save(params);
if (response.status === 200) {
message.success('操作成功');
router.push('/link/certificate');
}
loading.value = false;
})
.catch((err) => {
loading.value = false;
});
};
const handleChange = (info: UploadChangeParam) => {
loading.value = true;
fileLoading.value = true;
if (info.file.status === 'done') {
message.success('上传成功!');
const result = info.file.response?.result;
formData.cert = result;
loading.value = false;
formData.configs.cert = result;
fileLoading.value = false;
}
};
</script>

View File

@ -3,8 +3,11 @@
</template>
<script lang="ts" setup name="CertificatePage">
const handlAdd = (e: any) => {
console.log(111,e);
const router = useRouter();
const handlAdd = () => {
router.push('/link/certificate/detail/add');
}

View File

@ -0,0 +1,139 @@
<template>
<div class="api-does-container">
<div class="top">
<h5>{{ selectApi.summary }}</h5>
<div class="input">
<InputCard :value="selectApi.method" />
<a-input :value="selectApi?.url" disabled />
</div>
</div>
<p style="display: flex; justify-content: space-between">
<span class="label">请求数据类型</span>
<span class="value">{{
getContent(selectApi.requestBody) ||
'application/x-www-form-urlencoded'
}}</span>
<span class="label">响应数据类型</span>
<span class="value">{{ `["/"]` }}</span>
</p>
<div class="api-card">
<h5>请求参数</h5>
<div class="content">
<JTable
:columns="columns.request"
:dataSource="selectApi.parameters"
noPagination
model="TABLE"
>
<template #required="slotProps">
<span>{{ slotProps.row.required + '' }}</span>
</template>
<template #type="slotProps">
<span>{{ slotProps.row.schema.type }}</span>
</template>
</JTable>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { apiDetailsType } from '../index';
import InputCard from './InputCard.vue';
import { PropType } from 'vue';
const props = defineProps({
selectApi: {
type: Object as PropType<apiDetailsType>,
required: true,
},
});
const { selectApi } = toRefs(props);
const columns = {
request: [
{
title: '参数名',
dataIndex: 'name',
key: 'name',
},
{
title: '参数说明',
dataIndex: 'description',
key: 'description',
},
{
title: '请求类型',
dataIndex: 'in',
key: 'in',
},
{
title: '是否必须',
dataIndex: 'required',
key: 'required',
scopedSlots: true,
},
{
title: '参数类型',
dataIndex: 'type',
key: 'type',
scopedSlots: true,
},
],
};
console.log(selectApi.value);
const getContent = (data: any) => {
if (!data) return '';
return Object.keys(data.content)[0];
};
</script>
<style lang="less" scoped>
.api-does-container {
.top {
width: 100%;
h5 {
font-weight: bold;
font-size: 16px;
}
.input {
display: flex;
}
}
.api-card {
h5 {
position: relative;
padding-left: 10px;
&::before {
position: absolute;
top: 0;
left: 0;
width: 4px;
height: 100%;
background-color: #1d39c4;
border-radius: 0 3px 3px 0;
content: ' ';
}
}
.content {
padding-left: 10px;
:deep(.jtable-body) {
padding: 0;
.jtable-body-header {
display: none;
}
}
}
}
}
</style>

View File

@ -0,0 +1,42 @@
<template>
<div class="api-test-container">
<div class="top">
<h5>{{ selectApi.summary }}</h5>
<div class="input">
<InputCard :value="selectApi.method" />
<a-input :value="selectApi?.url" disabled />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { apiDetailsType } from '../index';
import InputCard from './InputCard.vue';
import { PropType } from 'vue';
const props = defineProps({
selectApi: {
type: Object as PropType<apiDetailsType>,
required: true,
},
});
const { selectApi } = toRefs(props);
</script>
<style lang="less" scoped>
.api-test-container {
.top {
width: 100%;
h5 {
font-weight: bold;
font-size: 16px;
}
.input {
display: flex;
}
}
}
</style>

View File

@ -0,0 +1,65 @@
<template>
<div class="choose-api-container">
<JTable
:columns="columns"
:dataSource="props.tableData"
:rowSelection="rowSelection"
noPagination
model="TABLE"
>
<template #url="slotProps">
<span
style="color: #1d39c4; cursor: pointer"
@click="jump(slotProps.row)"
>{{ slotProps.row.url }}</span
>
</template>
</JTable>
<a-button type="primary">保存</a-button>
</div>
</template>
<script setup lang="ts">
import { TableProps } from 'ant-design-vue';
const emits = defineEmits(['update:clickApi'])
const props = defineProps({
tableData: Array,
clickApi: Object
});
const columns = [
{
title: 'API',
dataIndex: 'url',
key: 'url',
scopedSlots: true,
},
{
title: '说明',
dataIndex: 'summary',
key: 'summary',
},
];
const rowSelection: TableProps['rowSelection'] = {
// onChange: (selectedRowKeys, selectedRows) => {
// console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
// },
};
const jump = (row:object) => {
emits('update:clickApi',row)
};
</script>
<style lang="less" scoped>
.choose-api-container {
height: 100%;
:deep(.jtable-body-header) {
display: none !important;
}
}
</style>

View File

@ -0,0 +1,35 @@
<template>
<span class="input-card-container" :class="props.value">
{{ props.value?.toLocaleUpperCase() }}
</span>
</template>
<script setup lang="ts">
const props = defineProps({
value: String,
});
</script>
<style lang="less" scoped>
.input-card-container {
padding: 4px 15px;
font-size: 14px;
color: #fff;
&.get {
background-color: #1890ff;
}
&.put {
background-color: #fa8c16;
}
&.post {
background-color: #52c41a;
}
&.delete {
background-color: #f5222d;
}
&.patch {
background-color: #a0d911;
}
}
</style>

View File

@ -15,51 +15,62 @@
import { TreeProps } from 'ant-design-vue';
import { getTreeOne_api, getTreeTwo_api } from '@/api/system/apiPage';
import { treeNodeTpye } from '../index';
type treeNodeTpye = {
name: string;
url: string;
children?: treeNodeTpye[];
};
const emits = defineEmits(['select']);
const treeData: TreeProps['treeData'] = ref([]);
const treeData = ref<TreeProps['treeData']>([]);
const getTreeData = () => {
let tree: treeNodeTpye[] = [];
getTreeOne_api().then((resp) => {
tree = resp.urls.map((item) => ({
getTreeOne_api().then((resp: any) => {
tree = resp.urls.map((item: any) => ({
...item,
key: item.url,
}));
const allPromise = tree.map((item) => getTreeTwo_api(item.name));
Promise.all(allPromise).then((values) => {
values.forEach((item, i) => {
tree[i].children = combData(item.paths);
values.forEach((item: any, i) => {
tree[i].children = combData(item?.paths);
});
console.log(tree);
treeData.value = tree
treeData.value = tree;
});
});
};
const clickSelectItem = (key, { node }) => {
emits('select', node);
const clickSelectItem: TreeProps['onSelect'] = (key, node: any) => {
emits('select', node.node.dataRef);
};
onMounted(() => {
getTreeData();
});
const combData = (dataSource: object): object[] => {
const apiList: object[] = [];
const combData = (dataSource: object) => {
const apiList: treeNodeTpye[] = [];
const keys = Object.keys(dataSource);
keys.forEach((key) => {
const method = Object.keys(dataSource[key] || {})[0];
const name = dataSource[key][method].tags[0];
let apiObj = apiList.find((item) => item.name === name);
if (!apiObj) {
apiObj = { name, link: key, methods: dataSource[key], key };
let apiObj: treeNodeTpye | undefined = apiList.find(
(item) => item.name === name,
);
if (apiObj) {
apiObj.apiList?.push({
url: key,
method: dataSource[key],
});
} else {
apiObj = {
name,
key: name,
apiList: [
{
url: key,
method: dataSource[key],
},
],
};
apiList.push(apiObj);
}
});
@ -68,4 +79,17 @@ const combData = (dataSource: object): object[] => {
};
</script>
<style lang="less" scoped></style>
<style lang="less">
.left-tree-container {
border-right: 1px solid #e9e9e9;
height: calc(100vh - 150px);
overflow-y: auto;
.ant-tree-list {
.ant-tree-list-holder-inner {
.ant-tree-switcher-noop {
display: none !important;
}
}
}
}
</style>

22
src/views/system/apiPage/index.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
export type treeNodeTpye = {
name: string;
key: string;
link?: string;
apiList?: object[];
children?: treeNodeTpye[];
};
export type methodType = {
[key: string]: object
}
export type apiObjType = {
url: string,
method: methodType
}
export type apiDetailsType = {
url: string;
method: string;
summary: string;
parameters: [];
requestBody?: any;
}

View File

@ -1,15 +1,78 @@
<template>
<a-card class="api-page-container" >
<LeftTree />
<a-card class="api-page-container">
<a-row :gutter="24">
<a-col :span="5">
<LeftTree @select="treeSelect" />
</a-col>
<a-col :span="19">
<ChooseApi
v-show="!selectedApi.url"
v-model:click-api="selectedApi"
:table-data="tableData"
/>
<div
class="api-details"
v-show="selectedApi.url && tableData.length > 0"
>
<a-button @click="selectedApi = initSelectedApi"
>返回</a-button
>
<a-tabs v-model:activeKey="activeKey" type="card">
<a-tab-pane key="does" tab="文档">
<ApiDoes :select-api="selectedApi" />
</a-tab-pane>
<a-tab-pane key="test" tab="调试">
<ApiTest :select-api="selectedApi" />
</a-tab-pane>
</a-tabs>
</div>
</a-col>
</a-row>
</a-card>
</template>
<script setup lang="ts">
<script setup lang="ts" name="apiPage">
import { treeNodeTpye, apiObjType, apiDetailsType } from './index';
import LeftTree from './components/LeftTree.vue';
import ChooseApi from './components/ChooseApi.vue';
import ApiDoes from './components/ApiDoes.vue';
import ApiTest from './components/ApiTest.vue';
const tableData = ref([]);
const treeSelect = (node: treeNodeTpye) => {
if (!node.apiList) return;
const apiList: apiObjType[] = node.apiList as apiObjType[];
const table: any = [];
//
apiList?.forEach((apiItem) => {
const { method, url } = apiItem;
for (const key in method) {
if (Object.prototype.hasOwnProperty.call(method, key)) {
table.push({
...method[key],
url,
method: key,
});
}
}
});
tableData.value = table;
};
const activeKey = ref('does');
const initSelectedApi = {
url: '',
method: '',
summary: '',
};
const selectedApi = ref<apiDetailsType>(initSelectedApi);
watch(tableData, () => (selectedApi.value = initSelectedApi));
</script>
<style scoped>
.api-page-container {
height: 100%;
}
</style>
</style>