master #6

Merged
bichangxiong merged 9 commits from master into prod 2025-09-08 18:53:13 +08:00
17 changed files with 1199 additions and 66 deletions

View File

@@ -0,0 +1,61 @@
import type { ActivityVO, ActivityForm, ActivityQuery } from './model';
import type { ID, IDS } from '#/api/common';
import type { PageResult } from '#/api/common';
import { commonExport } from '#/api/helper';
import { requestClient } from '#/api/request';
/**
* 查询客户服务-活动列表
* @param params
* @returns 客户服务-活动列表
*/
export function activityList(params?: ActivityQuery) {
return requestClient.get<PageResult<ActivityVO>>('/property/activity/list', { params });
}
/**
* 导出客户服务-活动列表
* @param params
* @returns 客户服务-活动列表
*/
export function activityExport(params?: ActivityQuery) {
return commonExport('/property/activity/export', params ?? {});
}
/**
* 查询客户服务-活动详情
* @param id id
* @returns 客户服务-活动详情
*/
export function activityInfo(id: ID) {
return requestClient.get<ActivityVO>(`/property/activity/${id}`);
}
/**
* 新增客户服务-活动
* @param data
* @returns void
*/
export function activityAdd(data: ActivityForm) {
return requestClient.postWithMsg<void>('/property/activity', data);
}
/**
* 更新客户服务-活动
* @param data
* @returns void
*/
export function activityUpdate(data: ActivityForm) {
return requestClient.putWithMsg<void>('/property/activity', data);
}
/**
* 删除客户服务-活动
* @param id id
* @returns void
*/
export function activityRemove(id: ID | IDS) {
return requestClient.deleteWithMsg<void>(`/property/activity/${id}`);
}

View File

@@ -0,0 +1,154 @@
import type { PageQuery, BaseEntity } from '#/api/common';
export interface ActivityVO {
/**
* 主键
*/
id: string | number;
/**
* 标题
*/
title: string;
/**
* 状态(1待进行2进行中3已完成)
*/
status: string;
/**
* 活动图片
*/
activityImgUrl: string;
/**
* 开始时间
*/
startTime: string;
/**
* 结束时间
*/
endTime: string;
/**
* 活动内容
*/
activityContent: string;
/**
* 备注
*/
remark: string;
/**
* 发布人
*/
issuers: number;
/**
* 搜索值
*/
searchValue: string;
}
export interface ActivityForm extends BaseEntity {
/**
* 主键
*/
id?: string | number;
/**
* 标题
*/
title?: string;
/**
* 状态(1待进行2进行中3已完成)
*/
status?: string;
/**
* 活动图片
*/
activityImgUrl?: string;
/**
* 开始时间
*/
startTime?: string;
/**
* 结束时间
*/
endTime?: string;
/**
* 活动内容
*/
activityContent?: string;
/**
* 备注
*/
remark?: string;
/**
* 发布人
*/
issuers?: number;
/**
* 搜索值
*/
searchValue?: string;
}
export interface ActivityQuery extends PageQuery {
/**
* 标题
*/
title?: string;
/**
* 状态(1待进行2进行中3已完成)
*/
status?: string;
/**
* 活动图片
*/
activityImgUrl?: string;
/**
* 开始时间
*/
startTime?: string;
/**
* 结束时间
*/
endTime?: string;
/**
* 活动内容
*/
activityContent?: string;
/**
* 发布人
*/
issuers?: number;
/**
* 搜索值
*/
searchValue?: string;
/**
* 日期范围参数
*/
params?: any;
}

View File

@@ -1,4 +1,4 @@
import type { PageQuery, BaseEntity } from '#/api/common';
import type {PageQuery, BaseEntity} from '#/api/common';
export interface Resident_unitVO {
/**
@@ -67,8 +67,8 @@ export interface Resident_unitVO {
*/
authGroupName?: string;
// 授权期限
authBegDate?:string;//开始
authEndDate?:string;//结束
authBegDate?: string;//开始
authEndDate?: string;//结束
}
@@ -177,8 +177,8 @@ export interface Resident_unitQuery extends PageQuery {
number?: number;
/**
* 日期范围参数
*/
* 日期范围参数
*/
params?: any;
}
@@ -240,4 +240,9 @@ export interface Unit extends BaseEntity {
*/
remark?: string;
/**
* 入驻面积
*/
area?: string;
}

View File

@@ -63,8 +63,6 @@ export const useNotifyStore = defineStore(
watch(data, (message) => {
if (!message) return
console.log(`接收到消息: ${message}`)
try {
// 尝试解析JSON
const obj = JSON.parse(message)

View File

@@ -19,11 +19,12 @@ import {
getStatisticsCurrDay,
getStatistics,
} from '#/api/analytics/index';
import { getVisitorList } from '#/api/property/resident/passRecordManagement';
const overviewItems = ref<any[]>([
{
icon: SvgCardIcon,
title: '今日访客量',
totalTitle: '总访客量',
title: '今日通行量',
totalTitle: '总通行量',
totalValue: 0,
value: 0,
},
@@ -73,6 +74,37 @@ const handleDateChange = (date: any) => {
}
};
// 通行量
async function getPersonCount() {
const date = new Date();
const nowDate = date
.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
.replace(/\//g, '-');
const historyData = {
pageNum: 1,
pageSize: 10,
begTime: '2025-09-01',
endTime: nowDate,
};
const todayData = {
pageNum: 1,
pageSize: 10,
begTime: nowDate,
endTime: nowDate,
};
const historyTotal = await getVisitorList(historyData);
const todayTotal = await getVisitorList(todayData);
overviewItems.value[0].totalValue = historyTotal.total;
overviewItems.value[0].value = todayTotal.total;
}
// 工单数量
async function getIndex() {
const res = await getIndexCount();
@@ -91,8 +123,7 @@ async function getCarCount() {
endDate.setHours(23, 59, 59, 999);
// 转换为正确的 ISO 格式,考虑时区偏移
const toLocalISOString = (date: Date) => {
const timezoneOffset = date.getTimezoneOffset() * 60000; // 转换为毫秒
const localTime = new Date(date.getTime() - timezoneOffset);
const localTime = new Date(date.getTime());
return localTime.toISOString().slice(0, -1) + 'Z';
};
const response = await fetch(
@@ -146,6 +177,7 @@ async function getStatisticsCount() {
onMounted(() => {
getIndex();
getCarCount();
getPersonCount();
getStatisticsCurrDayCount();
getStatisticsCount();
});

View File

@@ -3,7 +3,7 @@ import {computed, ref} from 'vue';
import {useVbenModal} from '@vben/common-ui';
import {$t} from '@vben/locales';
import {cloneDeep} from '@vben/utils';
import {cloneDeep, handleNode} from '@vben/utils';
import {useVbenForm} from '#/adapter/form';
import {
@@ -107,6 +107,12 @@ async function handleClosed() {
async function queryWorkOrdersType() {
const options = await workOrdersTypeTree()
const splitStr = '/';
handleNode(options, 'orderTypeName', splitStr, function (node: any) {
if (node.children.length) {
node.disabled = true;
}
});
formApi.updateSchema([
{
componentProps: (formModel) => ({

View File

@@ -0,0 +1,70 @@
<script setup lang="ts">
import type {ActivityVO} from '#/api/property/customerService/activity/model';
import {shallowRef} from 'vue';
import {useVbenModal} from '@vben/common-ui';
import {Descriptions, DescriptionsItem} from 'ant-design-vue';
import {activityInfo} from '#/api/property/customerService/activity';
import {renderDict} from "#/utils/render";
import {ossInfo} from "#/api/system/oss";
const [BasicModal, modalApi] = useVbenModal({
onOpenChange: handleOpenChange,
onClosed() {
activityDetail.value = null;
},
});
const activityDetail = shallowRef<null | ActivityVO>(null);
async function handleOpenChange(open: boolean) {
if (!open) {
return null;
}
modalApi.modalLoading(true);
const {id} = modalApi.getData() as { id: number | string };
const response = await activityInfo(id);
activityDetail.value = response;
if(activityDetail.value.activityImgUrl){
try {
const res = await ossInfo([activityDetail.value.activityImgUrl]);
activityDetail.value.activityImgUrl = res?.[0]?.url;
} catch (e) {
activityDetail.value.activityImgUrl = '';
}
}
modalApi.modalLoading(false);
}
</script>
<template>
<BasicModal :footer="false" :fullscreen-button="false" title="详情" class="w-[70%]">
<Descriptions v-if="activityDetail" size="small" :column="2" bordered :labelStyle="{width:'120px'}">
<DescriptionsItem label="活动ID">
{{ activityDetail.id }}
</DescriptionsItem>
<DescriptionsItem label="标题">
{{ activityDetail.title }}
</DescriptionsItem>
<DescriptionsItem label="开始时间">
{{ activityDetail.startTime }}
</DescriptionsItem>
<DescriptionsItem label="结束时间">
{{ activityDetail.endTime }}
</DescriptionsItem>
<DescriptionsItem label="发布状态" v-if="activityDetail.status!=null">
<component
:is="renderDict(activityDetail.status,'pro_release_status')"
/>
</DescriptionsItem>
<DescriptionsItem label="发布人">
{{ activityDetail.issuersText }}
</DescriptionsItem>
<DescriptionsItem label="活动图片" :span="2" v-if="activityDetail.activityImgUrl">
<img style="width: 100px" :src="activityDetail.activityImgUrl" alt="图片加载失败"/>
</DescriptionsItem>
<DescriptionsItem label="活动内容" :span="2">
<div v-html="activityDetail.activityContent"></div>
</DescriptionsItem>
</Descriptions>
</BasicModal>
</template>

View File

@@ -0,0 +1,101 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { activityAdd, activityInfo, activityUpdate } from '#/api/property/customerService/activity';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { modalSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
// 默认占满两列
formItemClass: 'col-span-2',
// 默认label宽度 px
labelWidth: 80,
// 通用配置项 会影响到所有表单项
componentProps: {
class: 'w-full',
}
},
schema: modalSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicModal, modalApi] = useVbenModal({
// 在这里更改宽度
class: 'w-[60%]',
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
modalApi.modalLoading(true);
const { id } = modalApi.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await activityInfo(id);
await formApi.setValues(record);
}
await markInitialized();
modalApi.modalLoading(false);
},
});
async function handleConfirm() {
try {
modalApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
// getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? activityUpdate(data) : activityAdd(data));
resetInitialized();
emit('reload');
modalApi.close();
} catch (error) {
console.error(error);
} finally {
modalApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicModal :title="title">
<BasicForm />
</BasicModal>
</template>

View File

@@ -0,0 +1,112 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'title',
label: '标题',
},
];
// 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
// export const columns: () => VxeGridProps['columns'] = () => [
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '活动ID',
field: 'id',
},
{
title: '标题',
field: 'title',
},
{
title: '开始时间',
field: 'startTime',
},
{
title: '结束时间',
field: 'endTime',
},
{
title: '发布状态',
field: 'status',
slots: {
default: ({ row }) => {
return renderDict(row.status, 'pro_release_status');
},
},
},
{
title: '发布人',
field: 'issuersText',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
width: 180,
},
];
export const modalSchema: FormSchemaGetter = () => [
{
label: '主键',
fieldName: 'id',
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
},
{
label: '标题',
fieldName: 'title',
component: 'Input',
rules: 'required',
},
{
label: '活动图片',
fieldName: 'activityImgUrl',
component: 'ImageUpload',
componentProps: {
maxCount: 1,
},
// rules: 'required',
},
{
label: '开始时间',
fieldName: 'startTime',
component: 'DatePicker',
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
},
rules: 'required',
},
{
label: '结束时间',
fieldName: 'endTime',
component: 'DatePicker',
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
},
rules: 'required',
},
{
label: '活动内容',
fieldName: 'activityContent',
component: 'RichTextarea',
componentProps: {
// disabled: false, // 是否只读
// height: 400 // 高度 默认400
},
rules: 'required',
},
];

View File

@@ -0,0 +1,195 @@
<script setup lang="ts">
import { Page, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import {
useVbenVxeGrid,
vxeCheckboxChecked,
type VxeGridProps
} from '#/adapter/vxe-table';
import {
activityExport,
activityList,
activityRemove,
} from '#/api/property/customerService/activity';
import type { ActivityForm } from '#/api/property/customerService/activity/model';
import { commonDownloadExcel } from '#/utils/file/download';
import activityModal from './activity-modal.vue';
import activityDetail from './activity-detail.vue';
import { columns, querySchema } from './data';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
// 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
// 不需要直接删除
// fieldMappingTime: [
// [
// 'createTime',
// ['params[beginTime]', 'params[endTime]'],
// ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
// ],
// ],
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
// 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
// columns: columns(),
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await activityList({
pageNum: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
// 表格全局唯一表示 保存列配置需要用到
id: 'property-activity-index'
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [ActivityModal, modalApi] = useVbenModal({
connectedComponent: activityModal,
});
const [ActivityDetail, activityDetailApi] = useVbenModal({
connectedComponent: activityDetail,
});
async function handleInfo(row: Required<ActivityForm>) {
activityDetailApi.setData({ id: row.id });
activityDetailApi.open();
}
function handleAdd() {
modalApi.setData({});
modalApi.open();
}
async function handleEdit(row: Required<ActivityForm>) {
modalApi.setData({ id: row.id });
modalApi.open();
}
async function handleDelete(row: Required<ActivityForm>) {
await activityRemove(row.id);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: Required<ActivityForm>) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await activityRemove(ids);
await tableApi.query();
},
});
}
function handleDownloadExcel() {
commonDownloadExcel(activityExport, '客户服务-活动数据', tableApi.formApi.form.values, {
fieldMappingTime: formOptions.fieldMappingTime,
});
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="活动管理列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['property:activity:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['property:activity:remove']"
@click="handleMultiDelete">
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['property:activity:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
@click.stop="handleInfo(row)"
>
{{ $t('pages.common.info') }}
</ghost-button>
<ghost-button
v-access:code="['property:activity:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['property:activity:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<ActivityModal @reload="tableApi.query()" />
<ActivityDetail/>
</Page>
</template>

View File

@@ -19,18 +19,15 @@ onMounted(() => {
() => notifyStore.sseList,
(val) => {
const latestMessage = val[val.length - 1];
try {
// 尝试解析消息内容
const parsedMessage = JSON.parse(latestMessage);
console.log('收到sse消息:', parsedMessage);
if (parsedMessage.type === 'meter') {
// 根据消息内容执行相应操作
handleSSEMessage(parsedMessage);
}
} catch (e) {
console.log('收到非JSON消息:', latestMessage);
// 处理非JSON格式消息
}
},
{ deep: true },

View File

@@ -44,7 +44,7 @@ async function handleOpenChange(open: boolean) {
<template>
<BasicModal :footer="false" :fullscreen-button="false" title="入驻单位信息" class="w-[70%]">
<Descriptions v-if="unitDetail" size="small" :column="2" bordered :labelStyle="{width:'110px'}">
<Descriptions v-if="unitDetail" size="small" :column="2" bordered :labelStyle="{width:'120px'}">
<DescriptionsItem label="单位编号">
{{ unitDetail.id }}
</DescriptionsItem>
@@ -62,6 +62,9 @@ async function handleOpenChange(open: boolean) {
<DescriptionsItem label="入驻位置" :span="2">
{{ unitDetail.locationDetail }}
</DescriptionsItem>
<DescriptionsItem label="入驻面积(㎡)" :span="2">
{{ unitDetail.area }}
</DescriptionsItem>
<DescriptionsItem label="入驻时间">
{{ unitDetail.time }}
</DescriptionsItem>

View File

@@ -14,7 +14,7 @@
<!-- 设备分组区域 -->
<div class="bg-background flex-1">
<div class="video-play-area flex h-[calc(100%-30px)] flex-wrap">
<div class="video-play-area flex h-[calc(100%-80px)] flex-wrap">
<div
v-for="i in playerNum"
:style="playerStyle"
@@ -36,26 +36,41 @@
</Loading>
</div>
</div>
<div class="player-area flex h-[30px] gap-[5px]">
<div
v-for="key in 4"
@click="onPlayerNumChanged(key)"
:class="playerSelectItemIndex == key ? selected : ''"
class="btn-item h-[20px] w-[20px]"
>
<Svg1FrameIcon v-if="key == 1" style="width: 100%; height: 100%" />
<Svg4FrameIcon
v-else-if="key == 2"
style="width: 100%; height: 100%"
/>
<Svg9FrameIcon
v-else-if="key == 3"
style="width: 100%; height: 100%"
/>
<Svg16FrameIcon
v-else-if="key == 4"
style="width: 100%; height: 100%"
/>
<div class="player-area h-[80px]">
<div class="process-wrap w-full">
<Process :init-date="processDate"></Process>
</div>
<!-- 视频回放操作栏 -->
<div class="play-option flex h-[40px] w-full gap-10">
<div class="left flex-1"></div>
<div class="mid flex flex-1 items-center content-center gap-5">
<div class="playing-time h-full w-[120px] flex items-center">
<DatePicker v-model:value="playDate" :allow-clear="false" />
</div>
<div class="playing" @click="onPlayerBtnClick">
<span v-if="playering">
<a-button type="primary" shape="circle" size="middle">
<template #icon>
<CaretRightOutlined />
</template>
</a-button>
</span>
<span v-else>
<a-button
style="background: darkgray"
type="primary"
shape="circle"
size="middle"
>
<template #icon>
<PauseCircleOutlined />
</template>
</a-button>
</span>
</div>
</div>
<div class="right flex-1"></div>
</div>
</div>
</div>
@@ -67,17 +82,15 @@
import { onMounted, onUnmounted, ref, toRaw } from 'vue';
import { Loading, Page } from '@vben/common-ui';
import ChannelTree from './channel-tree.vue';
import Process from './process.vue';
import mpegts from 'mpegts.js';
import { message } from 'ant-design-vue';
import { DatePicker, message } from 'ant-design-vue';
import { addStreamProxy } from '#/api/sis/stream';
import {
Svg16FrameIcon,
Svg1FrameIcon,
Svg4FrameIcon,
Svg9FrameIcon,
} from '@vben/icons';
import { checkHEVCSupport } from '#/utils/video';
import type { AddStreamProxyResult } from '#/api/sis/stream/model';
import { CaretRightOutlined, PauseCircleOutlined } from '@ant-design/icons-vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
const selected = 'selected';
@@ -107,12 +120,18 @@ const currentSelectPlayerIndex = ref(0);
const playerList: any[] = [];
// loading
const playerLoading = ref<boolean[]>([]);
// key
const currentSelectKey = ref('');
// key
const selectKeys = ref<string[]>([]);
const playering = ref<boolean>(true);
const playDate = ref<Dayjs>();
function onPlayerBtnClick() {
playering.value = !playering.value;
}
function playerSelect(index: number) {
currentSelectPlayerIndex.value = index;
const player = playerList[index];
@@ -435,11 +454,20 @@ function loading(index: number, cmd: Number = 0) {
playerLoading.value = loadinArr;
}
const processDate = ref('');
let isSupportH265 = false;
onMounted(() => {
// h265
isSupportH265 = checkHEVCSupport();
setInterval(catchUp, 120000);
// setInterval(catchUp, 120000);
//
const now = dayjs();
playDate.value = now;
processDate.value = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
setInterval(() => {
processDate.value = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
}, 1000);
});
onUnmounted(() => {
@@ -447,20 +475,6 @@ onUnmounted(() => {
closePlayer(i);
}
});
function catchUp() {
playerList.forEach((playerData) => {
if (playerData) {
const { player, el } = playerData;
const end = player.buffered.end(player.buffered.length - 1);
const diff = end - el.currentTime;
if (diff > 2) {
// 2
el.currentTime = end - 0.5; //
}
}
});
}
</script>
<style scoped>
@@ -484,12 +498,10 @@ function catchUp() {
}
.player-area {
display: flex;
align-items: center;
cursor: pointer;
.btn-item.selected {
color: #00a8ff;
.play-option {
background-color: #606060;
}
}
</style>

View File

@@ -0,0 +1,386 @@
<template>
<div class="playbackbar" ref="playbackbarRef">
<canvas ref="playbackbarCanvasRef"></canvas>
</div>
</template>
<script setup lang="js">
import { ref, reactive, watch, onMounted, onBeforeUnmount, computed } from 'vue';
import dayjs from 'dayjs';
// 1. 定义 PropsVue3 中使用 defineProps 声明)
const props = defineProps({
// 初始化时间 => 2021-08-20 00:00:00
initDate: {
type: String,
required: true // 建议添加必填校验,确保组件正常运行
},
/**
* 记录的区域列表
* @attribute startTime 开始时间 YYYY-MM-DD HH:mm:ss
* @attribute endTime 结束时间 YYYY-MM-DD HH:mm:ss
*/
timeData: {
type: Array,
default: () => []
}
});
// 2. 定义响应式数据Vue3 中使用 ref/reactive 替代 data
const playbackbarRef = ref(null); // 容器 DOM 引用
const playbackbarCanvasRef = ref(null); // canvas DOM 引用
// 基础响应式数据(使用 reactive 组合相关状态)
const state = reactive({
nowDate: props.initDate, // 当前时间
mouseNowDate: props.initDate, // 鼠标移入画布时的时间记录
ctx: null, // 画布 2D 上下文
_width: 0, // 画布宽
_height: 0, // 画布高
isMouseDown: false, // 是否在画布上按下鼠标
mousedownX: 0, // 鼠标按下的X坐标
mousedownY: 0, // 鼠标按下的Y坐标
size: 160, // 坐标尺寸(每小时对应的像素宽度)
axisTick: 1 // 默认刻度11小时/刻度)
});
// 3. 计算属性Vue3 中 computed 直接使用)
const pxToSecond = computed(() => {
// 1个移动像素代表的秒数 = (刻度小时数 * 60分钟 * 60秒) / 刻度像素宽度
return (state.axisTick * 60 * 60) / state.size;
});
// 4. 核心方法(提取为独立函数,在 setup 中调用)
/**
* 初始化画布(设置尺寸、上下文,绘制基础内容)
*/
const initCanvas = () => {
const box = playbackbarRef.value;
const canvas = playbackbarCanvasRef.value;
// 设置画布尺寸(与容器一致)
state._width = box.offsetWidth;
state._height = box.offsetHeight;
canvas.width = state._width;
canvas.height = state._height;
// 获取 2D 上下文
state.ctx = canvas.getContext('2d');
// 绘制基础内容
onBaseFill(state.ctx, state._width, state._height);
onDrawNowDate(state.ctx, state._width);
onMouseHandle(canvas, state.ctx, state._width, state._height);
};
/**
* 绘制画布基础内容(轴线、刻度、记录区域等)
* @param {CanvasRenderingContext2D} ctx - 画布上下文
* @param {number} _width - 画布宽度
* @param {number} _height - 画布高度
*/
const onBaseFill = (ctx, _width, _height) => {
// 1. 时间线上轴线(深色粗线)
ctx.beginPath();
ctx.strokeStyle = '#303030';
ctx.lineWidth = 3;
ctx.moveTo(0, 40.5);
ctx.lineTo(_width, 40.5);
ctx.stroke();
// 2. 绘制刻度线、记录区域
onDrawTick(ctx, _width, _height);
onDrawRecordArea(ctx, _width, _height);
// 3. 时间轴辅助线(浅绿色细线)
ctx.beginPath();
ctx.strokeStyle = '#B1BE76';
ctx.lineWidth = 1;
ctx.moveTo(0, 42.5);
ctx.lineTo(_width, 42.5);
ctx.stroke();
// 4. 黄色辅助线
ctx.beginPath();
ctx.strokeStyle = '#FFFF00';
ctx.lineWidth = 1;
ctx.moveTo(0, 50.5);
ctx.lineTo(_width, 50.5);
ctx.stroke();
// 5. 中间时间线(黄色粗线,画布中点)
ctx.beginPath();
ctx.strokeStyle = '#ffcc00';
ctx.lineWidth = 2;
ctx.moveTo(_width / 2 - 1 + 0.5, 0);
ctx.lineTo(_width / 2 - 1 + 0.5, _height);
ctx.stroke();
};
/**
* 绘制轴线刻度线及时间文本
* @param {CanvasRenderingContext2D} ctx - 画布上下文
* @param {number} _width - 画布宽度
* @param {number} _height - 画布高度
*/
const onDrawTick = (ctx, _width, _height) => {
const nowTime = new Date(state.nowDate).getTime();
// 离当前时间最近的整点时间(如 14:00:00
dayjs(nowTime).format('YYYY-MM-DD HH');
const leftIntTime = new Date(dayjs(state.nowDate).format('YYYY-MM-DD HH') + ':00:00').getTime()
const nowHour = dayjs(state.nowDate).format('HH');
// 当前时间距离左侧整点的秒数
const leftIntSecond = (nowTime - leftIntTime) / 1000;
// 中间点距离左侧整点的像素距离
const leftIntLength = leftIntSecond / pxToSecond.value;
// 整点在画布上的基准位置(以画布中点为参考)
const center = _width / 2 - 1 - leftIntLength;
// 左侧刻度个数(基准点向左能绘制的刻度数)
const leftTickNumber = Math.floor(center / state.size);
// 右侧刻度个数(基准点向右能绘制的刻度数)
const rightTickNumber = Math.floor((_width - center) / state.size);
// 绘制左侧刻度
for (let i = 0; i <= leftTickNumber; i++) {
const _X = center - i * state.size;
let hour = Number(nowHour) - i;
hour = hour < 0 ? hour + 24 : hour; // 处理跨天小时(如 0时-1时=23时
const timeText = hour < 10 ? `0${hour}:00` : `${hour}:00`;
// 绘制刻度线
ctx.beginPath();
ctx.strokeStyle = '#4B4B4B';
ctx.lineWidth = 2;
ctx.moveTo(_X + 0.5, 40);
ctx.lineTo(_X + 0.5, _height);
ctx.stroke();
// 绘制时间文本
ctx.font = '10px Arial';
ctx.fillStyle = '#969696';
ctx.fillText(timeText, _X + 0.5 - 12, 34);
}
// 绘制右侧刻度
for (let i = 1; i <= rightTickNumber; i++) {
const _X = center + i * state.size;
let hour = Number(nowHour) + i;
hour = hour >= 24 ? hour - 24 : hour; // 处理跨天小时(如 23时+2时=1时
const timeText = hour < 10 ? `0${hour}:00` : `${hour}:00`;
// 绘制刻度线
ctx.beginPath();
ctx.strokeStyle = '#4B4B4B';
ctx.lineWidth = 2;
ctx.moveTo(_X + 0.5, 40);
ctx.lineTo(_X + 0.5, _height);
ctx.stroke();
// 绘制时间文本
ctx.font = '10px Arial';
ctx.fillStyle = '#969696';
ctx.fillText(timeText, _X + 0.5 - 12, 34);
}
};
/**
* 绘制当前时间文本(画布上方中间)
* @param {CanvasRenderingContext2D} ctx - 画布上下文
* @param {number} _width - 画布宽度
*/
const onDrawNowDate = (ctx, _width) => {
ctx.font = '14px Arial';
ctx.fillStyle = '#ffffff';
ctx.fillText(state.nowDate, _width / 2 - 75, 24);
};
/**
* 绘制视频记录区域(蓝色矩形)
* @param {CanvasRenderingContext2D} ctx - 画布上下文
* @param {number} _width - 画布宽度
* @param {number} _height - 画布高度
*/
const onDrawRecordArea = (ctx, _width, _height) => {
const nowTime = new Date(state.nowDate).getTime();
// 画布左侧顶点对应的时间(秒)
const leftVertexTime = nowTime / 1000 - (_width / 2) * pxToSecond.value;
// 画布右侧顶点对应的时间(秒)
const rightVertexTime = nowTime / 1000 + (_width / 2) * pxToSecond.value;
// 筛选可视范围内的记录(与画布有交集的记录)
const visibleTimeList = props.timeData.filter((record) => {
const startTimeSecond = new Date(record.startTime).getTime() / 1000;
const endTimeSecond = new Date(record.endTime).getTime() / 1000;
// 两种交集情况1. 记录覆盖画布左侧 2. 记录起点在画布内
return (
(startTimeSecond < leftVertexTime && endTimeSecond > leftVertexTime) ||
(startTimeSecond >= leftVertexTime && startTimeSecond < rightVertexTime)
);
});
// 绘制每个可视记录的蓝色矩形
visibleTimeList.forEach((record) => {
const startTimeSecond = new Date(record.startTime).getTime() / 1000;
const endTimeSecond = new Date(record.endTime).getTime() / 1000;
// 情况1记录起点在画布左侧矩形从画布左端开始
if (startTimeSecond < leftVertexTime) {
const rectWidth = endTimeSecond < rightVertexTime
? (endTimeSecond - leftVertexTime) / pxToSecond.value
: _width; // 若记录覆盖画布右侧,宽度设为画布宽
ctx.beginPath();
ctx.fillStyle = '#637DEC';
ctx.fillRect(0, 43, rectWidth, 8);
}
// 情况2记录起点在画布内
if (startTimeSecond >= leftVertexTime) {
const rectX = (startTimeSecond - leftVertexTime) / pxToSecond.value; // 矩形X坐标
const rectWidth = (endTimeSecond - startTimeSecond) / pxToSecond.value; // 矩形宽度
ctx.beginPath();
ctx.fillStyle = '#637DEC';
ctx.fillRect(rectX, 43, rectWidth, 8);
}
});
};
/**
* 绑定画布鼠标事件(移入、移出、移动、按下)
* @param {HTMLCanvasElement} canvas - canvas DOM 元素
* @param {CanvasRenderingContext2D} ctx - 画布上下文
* @param {number} _width - 画布宽度
* @param {number} _height - 画布高度
*/
const onMouseHandle = (canvas, ctx, _width, _height) => {
// 鼠标移入:记录当前时间(避免移动时受实时时间影响)
canvas.onmouseover = (e) => {
if (!state.isMouseDown) {
state.mouseNowDate = state.nowDate;
}
};
// 鼠标移出:清空画布并重新绘制基础内容
canvas.onmouseout = (e) => {
ctx.clearRect(0, 0, _width, _height);
onBaseFill(ctx, _width, _height);
onDrawNowDate(ctx, _width);
};
// 鼠标移动(未按下时):显示当前鼠标对应的时间
canvas.onmousemove = (e) => {
if (!state.isMouseDown) {
ctx.clearRect(0, 0, _width, _height);
onBaseFill(ctx, _width, _height);
const offsetX = e.offsetX; // 鼠标在画布内的X坐标
const moveLength = offsetX - _width / 2; // 鼠标与画布中点的距离
// 计算鼠标位置对应的时间
const targetTime = new Date(state.mouseNowDate).getTime() + pxToSecond.value * moveLength * 1000;
const targetTimeText = dayjs(targetTime).format('YYYY-MM-DD HH:mm:ss');
// 绘制鼠标对应的时间文本(鼠标上方)
ctx.font = '12px Arial';
ctx.fillStyle = '#ffffff';
ctx.fillText(targetTimeText, offsetX - 62, 12);
// 绘制当前时间文本(画布中间)
onDrawNowDate(ctx, _width);
}
};
// 鼠标按下:记录按下时的坐标和状态
canvas.onmousedown = (e) => {
state.mousedownX = e.clientX;
state.mousedownY = e.clientY;
state.isMouseDown = true;
};
};
/**
* 绑定全局事件(鼠标抬起、全局移动)
*/
const onDocumentEvent = () => {
// 全局鼠标抬起:重置按下状态
document.onmouseup = (e) => {
if (state.isMouseDown) {
state.mouseNowDate = state.nowDate; // 同步最终时间
state.isMouseDown = false;
}
};
// 全局鼠标移动(按下时):拖动画布改变当前时间
document.onmousemove = (e) => {
if (state.isMouseDown && state.ctx) {
state.ctx.clearRect(0, 0, state._width, state._height);
onBaseFill(state.ctx, state._width, state._height);
const clientX = e.clientX;
const moveLength = state.mousedownX - clientX; // 鼠标拖动的距离
// 计算拖动后的时间
const targetTime = new Date(state.mouseNowDate).getTime() + pxToSecond.value * moveLength * 1000;
state.nowDate = dayjs(targetTime).format('YYYY-MM-DD HH:mm:ss');
// 重新绘制当前时间文本
onDrawNowDate(state.ctx, state._width);
}
};
};
// 5. 生命周期钩子Vue3 中直接使用 onMounted/onBeforeUnmount 等)
// 组件挂载后初始化画布、绑定事件、监听窗口resize
onMounted(() => {
initCanvas();
onDocumentEvent();
// 窗口resize防抖处理
let isDebouncing = false;
window.onresize = () => {
if (!isDebouncing) {
isDebouncing = true;
setTimeout(() => {
initCanvas();
isDebouncing = false;
}, 300);
}
};
});
// 组件卸载前:清除事件监听
onBeforeUnmount(() => {
window.onresize = null;
document.onmousemove = null;
document.onmouseup = null;
if (playbackbarCanvasRef.value) {
playbackbarCanvasRef.value.onmouseover = null;
playbackbarCanvasRef.value.onmouseout = null;
playbackbarCanvasRef.value.onmousemove = null;
playbackbarCanvasRef.value.onmousedown = null;
}
});
// 6. 监听 Props 变化initDate 变化时重新初始化
watch(
() => props.initDate,
(newVal) => {
state.nowDate = newVal;
state.mouseNowDate = newVal;
initCanvas();
},
{ immediate: false } // 初始化时已在 onMounted 处理,无需立即执行
);
</script>
<style lang="scss" scoped>
.playbackbar {
width: 100%;
height: 40px;
background-color: #343434;
canvas {
cursor: pointer;
background: #000;
}
}
</style>

View File

@@ -3,6 +3,7 @@
"extends": "@vben/tsconfig/web-app.json",
"compilerOptions": {
"baseUrl": ".",
"allowJs": true,
"paths": {
"#/*": [
"./src/*"