Files
one-pipe-system/src/views/asset-management/task-management/device-task/index.vue
luo b2a76adc9a
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
fix: some
2026-10-13 11:25:03 +08:00

642 lines
20 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<ArtTableFullScreen>
<div v-if="isPlatformAccount" class="device-task-page" id="table-full-screen">
<ArtSearchBar
v-model:filter="searchForm"
:items="searchFormItems"
:show-expand="false"
@reset="handleReset"
@search="handleSearch"
/>
<div v-if="pollingError || pollingForbidden" class="task-polling-error">
<ElAlert
type="warning"
:closable="false"
show-icon
:title="pollingForbidden ? '当前账号无权查看该任务' : pollingError || '任务状态获取失败'"
/>
<ElButton size="small" @click="polling.retry">重试</ElButton>
</div>
<ElCard shadow="never" class="art-table-card">
<ArtTableHeader
:columnList="columnOptions"
v-model:columns="columnChecks"
@refresh="handleRefresh"
>
<template #left>
<ElButton type="primary" :icon="Upload" @click="importDialogVisible = true">
批量导入设备
</ElButton>
</template>
</ArtTableHeader>
<ArtTable
ref="tableRef"
row-key="id"
:loading="loading"
:data="taskList"
:currentPage="pagination.page"
:pageSize="pagination.pageSize"
:total="pagination.total"
:marginTop="10"
:actions="getActions"
:actionsWidth="180"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
>
<template #default>
<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
</template>
</ArtTable>
</ElCard>
</div>
<ElDrawer v-model="importDialogVisible" title="批量导入设备" direction="rtl" size="50%">
<ElAlert type="info" :closable="false" style="margin-bottom: 20px">
<template #title>
<div style="line-height: 1.8">
<p><strong>导入说明:</strong></p>
<p>1. 设备导入使用 Excel 模板,文件大小不能超过 300MB。</p>
<p>2. 列格式请设置为文本格式,避免长数字被转为科学计数法。</p>
<p>3. <strong>列顺序固定,不可调整。</strong>系统按位置读取,不识别列名。</p>
<p style="color: var(--el-color-primary)">
4. 必填列:设备标识(第 1 列,支持 VirtualNo、IMEI 或 SN)和独立的 IMEI
列。即使设备标识填写 IMEI,IMEI 列也不能留空或仅填空格。
</p>
<p>
5. 可选列:SN、设备名称、设备型号、设备类型、制造商、最大 SIM 槽数、卡 1~卡 4 ICCID。
</p>
</div>
</template>
</ElAlert>
<div style="margin-bottom: 20px">
<ElButton type="primary" :icon="Download" @click="downloadTemplate">
下载导入模板
</ElButton>
</div>
<ElRow :gutter="20">
<ElCol :span="12">
<ElFormItem label="批次号" prop="batch_no">
<ElInput
v-model="importForm.batch_no"
placeholder="请输入批次号或点击生成"
:maxlength="100"
clearable
>
<template #append>
<ElButton @click="handleGenerateBatchNo">生成编码</ElButton>
</template>
</ElInput>
</ElFormItem>
</ElCol>
<ElCol :span="12">
<ElFormItem label="实名认证策略">
<ElSelect
v-model="importForm.realname_policy"
placeholder="默认无需实名"
clearable
style="width: 100%"
>
<ElOption label="无需实名" value="none" />
<ElOption label="先实名后充值/购买" value="before_order" />
<ElOption label="先充值/购买后实名" value="after_order" />
</ElSelect>
</ElFormItem>
</ElCol>
</ElRow>
<ElUpload
ref="uploadRef"
drag
:auto-upload="false"
:on-change="handleFileChange"
:limit="1"
accept=".xlsx"
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">将文件拖到此处,或<em>点击选择</em></div>
<template #tip>
<div class="el-upload__tip">设备导入仅支持 .xlsx 文件</div>
</template>
</ElUpload>
<template #footer>
<ElButton @click="handleCancelImport">取消</ElButton>
<ElButton
type="primary"
:loading="uploading"
:disabled="!fileList.length"
@click="submitUpload"
>
开始导入
</ElButton>
</template>
</ElDrawer>
</ArtTableFullScreen>
</template>
<script setup lang="ts">
import { h, onMounted, reactive, ref, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { DeviceService } from '@/api/modules'
import { ElMessage, ElTag } from 'element-plus'
import { Download, Upload, UploadFilled } from '@element-plus/icons-vue'
import type { UploadInstance } from 'element-plus'
import type { SearchFormItem } from '@/types'
import { useCheckedColumns } from '@/composables/useCheckedColumns'
import { useAuth } from '@/composables/useAuth'
import { useAsyncTaskPolling } from '@/composables/useAsyncTaskPolling'
import { useUserStore } from '@/store/modules/user'
import { formatDateTime } from '@/utils/business/format'
import { StorageService } from '@/api/modules/storage'
import type {
DeviceImportTask,
DeviceImportTaskDetail,
DeviceImportTaskQueryParams,
DeviceImportTaskStatus,
RealnamePolicy
} from '@/types/api/device'
import { RoutesAlias } from '@/router/routesAlias'
import { generatePackageCode } from '@/utils/codeGenerator'
defineOptions({ name: 'DeviceTask' })
const router = useRouter()
const route = useRoute()
const { hasAuth } = useAuth()
const userStore = useUserStore()
const isPlatformAccount = computed(() => [1, 2].includes(Number(userStore.info.user_type)))
const loading = ref(false)
const tableRef = ref()
const uploadRef = ref<UploadInstance>()
const fileList = ref<File[]>([])
const uploading = ref(false)
const importDialogVisible = ref(false)
const importForm = reactive({
batch_no: '',
realname_policy: '' as '' | RealnamePolicy
})
const initialSearchState = {
status: undefined as DeviceImportTaskStatus | undefined,
batch_no: '',
dateRange: undefined as string[] | undefined
}
const searchForm = reactive({ ...initialSearchState })
const pagination = reactive({ page: 1, pageSize: 20, total: 0 })
const searchFormItems: SearchFormItem[] = [
{
label: '任务状态',
prop: 'status',
type: 'select',
config: { clearable: true, placeholder: '全部' },
options: () => [
{ label: '待处理', value: 1 },
{ label: '处理中', value: 2 },
{ label: '已完成', value: 3 },
{ label: '失败', value: 4 }
]
},
{
label: '批次号',
prop: 'batch_no',
type: 'input',
config: { clearable: true, placeholder: '请输入批次号' }
},
{
label: '创建时间',
prop: 'dateRange',
type: 'datetimerange',
config: {
type: 'datetimerange',
startPlaceholder: '开始时间',
endPlaceholder: '结束时间',
valueFormat: 'YYYY-MM-DDTHH:mm:ssZ'
}
}
]
const columnOptions = [
{ label: '任务编号', prop: 'task_no' },
{ label: '任务状态', prop: 'status' },
{ label: '总数', prop: 'total_count' },
{ label: '成功数', prop: 'success_count' },
{ label: '失败数', prop: 'fail_count' },
{ label: '跳过数', prop: 'skip_count' },
{ label: '开始时间', prop: 'started_at' },
{ label: '完成时间', prop: 'completed_at' },
{ label: '错误信息', prop: 'error_message' },
{ label: '批次号', prop: 'batch_no' },
{ label: '文件名', prop: 'file_name' },
{ label: '创建时间', prop: 'created_at' }
]
const taskList = ref<DeviceImportTask[]>([])
const polling = useAsyncTaskPolling<DeviceImportTaskDetail>({
storageKey: 'device-import-active-task',
autoRestore: false,
fetchTask: async (taskId) => {
const res = await DeviceService.getImportTaskDetail(taskId)
if (res.code !== 0 || !res.data) throw new Error(res.msg || '获取设备任务失败')
return res.data
},
isForbidden: (error) => {
const response = (error as { response?: { status?: number; data?: { code?: number } } })
?.response
return response?.status === 403 || response?.data?.code === 403
}
})
const pollingError = polling.error
const pollingForbidden = polling.forbidden
const getStatusType = (status: DeviceImportTaskStatus) => {
switch (status) {
case 1:
return 'info'
case 2:
return 'warning'
case 3:
return 'success'
case 4:
return 'danger'
default:
return 'info'
}
}
const viewDetail = (row: DeviceImportTask) => {
if (!isPlatformAccount.value) return
router.push({
path: RoutesAlias.TaskDetail,
query: { id: row.id, task_type: 'device' }
})
}
const handleNameClick = (row: DeviceImportTask) => {
if (isPlatformAccount.value && hasAuth('device_task:view_detail')) {
viewDetail(row)
} else {
ElMessage.warning('您没有查看详情的权限')
}
}
const { columnChecks, columns } = useCheckedColumns(() => [
{
prop: 'task_no',
label: '任务编号',
width: 220,
showOverflowTooltip: true,
formatter: (row: DeviceImportTask) =>
h(
'span',
{
style: 'color: var(--el-color-primary); cursor: pointer; text-decoration: underline;',
onClick: (e: MouseEvent) => {
e.stopPropagation()
handleNameClick(row)
}
},
row.task_no
)
},
{
prop: 'status',
label: '任务状态',
width: 100,
formatter: (row: DeviceImportTask) =>
h(ElTag, { type: getStatusType(row.status) }, () => row.status_name || row.status_text)
},
{ prop: 'total_count', label: '总数', width: 80 },
{
prop: 'success_count',
label: '成功数',
width: 80,
formatter: (row: DeviceImportTask) =>
h('span', { style: { color: 'var(--el-color-success)' } }, row.success_count)
},
{
prop: 'fail_count',
label: '失败数',
width: 80,
formatter: (row: DeviceImportTask) =>
h('span', { style: { color: 'var(--el-color-danger)' } }, row.fail_count)
},
{ prop: 'skip_count', label: '跳过数', width: 80 },
{ prop: 'batch_no', label: '批次号', width: 180, showOverflowTooltip: true },
{
prop: 'started_at',
label: '开始时间',
width: 180,
formatter: (row: DeviceImportTask) => (row.started_at ? formatDateTime(row.started_at) : '-')
},
{
prop: 'completed_at',
label: '完成时间',
width: 180,
formatter: (row: DeviceImportTask) =>
row.completed_at ? formatDateTime(row.completed_at) : '-'
},
{
prop: 'error_message',
label: '错误信息',
minWidth: 200,
showOverflowTooltip: true,
formatter: (row: DeviceImportTask) => row.error_message || '-'
},
{ prop: 'file_name', label: '文件名', minWidth: 180, showOverflowTooltip: true },
{
prop: 'creator_name',
label: '操作人',
width: 140,
showOverflowTooltip: true,
formatter: (row: DeviceImportTask) => row.creator_name || '-'
},
{
prop: 'created_at',
label: '创建时间',
width: 180,
formatter: (row: DeviceImportTask) => formatDateTime(row.created_at)
}
])
watch(polling.task, () => {
if (isPlatformAccount.value) void getTableData()
})
onMounted(() => {
if (!isPlatformAccount.value) return
void getTableData()
const routeTaskId = Number(route.query.task_id)
if (routeTaskId) {
void polling.start(routeTaskId)
} else if (polling.taskId.value) {
void polling.retry()
}
})
const getTableData = async () => {
if (!isPlatformAccount.value) {
taskList.value = []
pagination.total = 0
return
}
loading.value = true
try {
const params: DeviceImportTaskQueryParams = {
page: pagination.page,
page_size: pagination.pageSize,
status: searchForm.status,
operation_type: 'import',
batch_no: searchForm.batch_no || undefined
}
if (searchForm.dateRange && Array.isArray(searchForm.dateRange)) {
params.start_time = searchForm.dateRange[0]
params.end_time = searchForm.dateRange[1]
}
const res = await DeviceService.getImportTasks(params)
if (res.code === 0) {
taskList.value = res.data.items || []
pagination.total = res.data.total || 0
}
} catch (error) {
console.error(error)
} finally {
loading.value = false
}
}
const handleReset = () => {
Object.assign(searchForm, { ...initialSearchState })
pagination.page = 1
void getTableData()
}
const handleSearch = () => {
pagination.page = 1
void getTableData()
}
const handleRefresh = () => void getTableData()
const handleSizeChange = (newPageSize: number) => {
pagination.pageSize = newPageSize
void getTableData()
}
const handleCurrentChange = (newCurrentPage: number) => {
pagination.page = newCurrentPage
void getTableData()
}
const downloadTemplate = () => {
try {
const link = document.createElement('a')
link.href = new URL('@/template/设备导入模板.xlsx', import.meta.url).href
link.download = '设备导入模板.xlsx'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
ElMessage.success('设备导入模板下载成功')
} catch (error) {
console.error('下载模板失败:', error)
ElMessage.error('下载模板失败')
}
}
const handleFileChange = (uploadFile: any) => {
const file = uploadFile.raw as File | undefined
if (!file) return
if (file.size > 300 * 1024 * 1024) {
ElMessage.error('文件大小不能超过 300MB')
uploadRef.value?.clearFiles()
fileList.value = []
return
}
if (!file.name.toLowerCase().endsWith('.xlsx')) {
ElMessage.error('设备导入只能上传 .xlsx 文件')
uploadRef.value?.clearFiles()
fileList.value = []
return
}
fileList.value = [file]
}
const clearFiles = () => {
uploadRef.value?.clearFiles()
fileList.value = []
}
const handleGenerateBatchNo = () => {
importForm.batch_no = generatePackageCode().replace('PKG', 'DEV')
ElMessage.success('批次号生成成功')
}
const handleCancelImport = () => {
clearFiles()
importForm.batch_no = ''
importForm.realname_policy = ''
importDialogVisible.value = false
}
const submitUpload = async () => {
if (!isPlatformAccount.value || !fileList.value.length) {
ElMessage.warning('请先选择文件')
return
}
const file = fileList.value[0]
uploading.value = true
try {
ElMessage.info('正在准备上传...')
const uploadUrlRes = await StorageService.getUploadUrl({
file_name: file.name,
content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
purpose: 'iot_import'
})
if (uploadUrlRes.code !== 0) {
ElMessage.error(uploadUrlRes.msg || '获取上传地址失败')
return
}
const { upload_url, file_key } = uploadUrlRes.data
ElMessage.info('正在上传文件...')
await StorageService.uploadFile(
upload_url,
file,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
ElMessage.info('正在创建设备导入任务...')
const importRes = await DeviceService.importDevices({
file_key,
batch_no: importForm.batch_no || undefined,
realname_policy: (importForm.realname_policy || undefined) as RealnamePolicy | undefined
})
if (importRes.code !== 0) {
ElMessage.error(importRes.msg || '创建导入任务失败')
return
}
const taskNo = importRes.data.task_no
const taskId = importRes.data.task_id
handleCancelImport()
await router.replace({ path: route.path, query: { task_id: String(taskId) } })
await polling.start(taskId)
await getTableData()
ElMessage.success({
message: `导入任务已创建!任务编号:${taskNo}`,
duration: 3000,
showClose: true
})
} catch (error: any) {
console.error('设备导入失败:', error)
} finally {
uploading.value = false
}
}
const downloadFailDataByRow = async (row: DeviceImportTask) => {
if (!isPlatformAccount.value) return
try {
const res = await DeviceService.getImportTaskDetail(row.id)
if (res.code !== 0 || !res.data) return
const failReasons =
res.data.failed_items?.map((item) => ({
line: item.line || '-',
deviceNo: item.device_identifier || item.virtual_no || '-',
message: item.reason || '未知错误'
})) || []
if (failReasons.length === 0) {
ElMessage.warning('没有失败数据可下载')
return
}
const csvRows = [
['行号', '设备编号', '失败原因'].join(','),
...failReasons.map((item) =>
[item.line, `\t${item.deviceNo}`, `"${item.message.replaceAll('"', '""')}"`].join(',')
)
]
const blob = new Blob(['\uFEFF' + csvRows.join('\n')], {
type: 'text/csv;charset=utf-8;'
})
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `导入失败数据_${row.batch_no}.csv`
link.click()
URL.revokeObjectURL(url)
ElMessage.success('失败数据下载成功')
} catch (error) {
console.error('下载失败数据失败:', error)
ElMessage.error('下载失败数据失败')
}
}
const downloadTaskFile = async (row: DeviceImportTask) => {
if (!isPlatformAccount.value) return
const fileKey = row.file_key || row.file_name?.trim()
if (!fileKey) {
ElMessage.warning('当前任务没有可下载的原始文件')
return
}
try {
await StorageService.downloadFileByKey(fileKey)
ElMessage.success('原始文件下载已开始')
} catch (error) {
console.error('下载原始文件失败:', error)
ElMessage.error('下载原始文件失败')
}
}
const getActions = (row: DeviceImportTask) => {
if (!isPlatformAccount.value) return []
const actions: any[] = []
if (row.file_key && hasAuth('device_task:download_file')) {
actions.push({ label: '下载文件', handler: () => downloadTaskFile(row), type: 'primary' })
}
if (row.fail_count > 0 && hasAuth('device_task:download_fail_data')) {
actions.push({
label: '失败数据',
handler: () => downloadFailDataByRow(row),
type: 'danger'
})
}
return actions
}
</script>
<style lang="scss" scoped>
.device-task-page {
.task-polling-error {
display: flex;
gap: 12px;
align-items: center;
margin-bottom: 12px;
}
:deep(.el-icon--upload) {
margin-bottom: 16px;
font-size: 67px;
color: var(--el-text-color-placeholder);
}
:deep(.el-upload__text) {
font-size: 14px;
color: var(--el-text-color-regular);
em {
font-style: normal;
color: var(--el-color-primary);
}
}
}
</style>