吉安感知网项目-前端
chenyao
2 days ago a53ece5036c1fa61a63fe5f9e0cd3519210ab928
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
<!-- 巡查报告管理 -->
<template>
    <basic-container>
        <el-form ref="queryParamsRef" :model="searchParams" class="gd-search-form">
            <el-form-item label="模糊搜索" prop="nickName">
                <el-input
                    class="gd-input gray"
                    v-model="searchParams.nickName"
                    placeholder="请输入"
                    clearable
                    @clear="handleSearch"
                />
            </el-form-item>
 
            <el-form-item label="文档类型" prop="resultType">
                <el-cascader
                    class="gd-cascader gray"
                    popper-class="gd-cascader-popper"
                    v-model="searchParams.resultType"
                    :options="workOrderTypeXT"
                    :props="taskTypeCascaderProps"
                    placeholder="请选择"
                    clearable
                    @change="handleSearch"
                />
            </el-form-item>
 
            <el-form-item class="gd-search-actions">
                <el-button :icon="RefreshRight" @click="resetForm"></el-button>
                <el-button class="search-btn" :icon="Search" @click="handleSearch"></el-button>
            </el-form-item>
        </el-form>
 
        <div class="gd-table-container" v-loading="loading">
            <div class="gd-table-toolbar">
                <el-button :icon="Download" color="#4C34FF" type="primary" @click="handleDownload">文档下载</el-button>
                <el-button :icon="Upload" color="#ECECF4" type="primary" @click="handleUpload">文档上传</el-button>
            </div>
 
            <div class="gd-table-content gd-table-content-bg">
                <el-table class="gd-table" :data="list" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="46" />
                    <el-table-column type="index" width="64" label="序号" />
                    <el-table-column prop="nickName" class-name="operation-btns" show-overflow-tooltip label="文档名称">
                        <template v-slot="{ row }">
                            <el-link  type="primary"  @click="openForm(row)">{{ row.nickName }}</el-link>
                        </template>
                    </el-table-column>
                    <el-table-column prop="attachSize" show-overflow-tooltip label="文档大小">
                        <template v-slot="{ row }">
                        {{ formatFileSize(row.attachSize) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="deptName" show-overflow-tooltip label="文档归属" />
                    <!-- <el-table-column prop="resultType" show-overflow-tooltip label="文档类型" /> -->
                    <el-table-column prop="resultType" show-overflow-tooltip label="文档类型">
                        <template v-slot="{ row }">
                            {{ getTaskTypeLabel(row.resultType, workOrderTypeXT) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" class-name="operation-btns" fixed="right">
                        <template v-slot="{ row }">
                            <el-link  type="primary"  @click="seeOnlineWord(row)">查看</el-link>
                            <el-link type="primary" :disabled="isZipRow(row)" @click="openOfficeEdit(row)">在线编辑</el-link>
                            <el-link  type="primary"  @click="handleDelete(row)">删除</el-link>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
 
            <div class="gd-pagination-parent">
                <el-pagination
                    popper-class="gd-select-popper"
                    v-model:current-page="searchParams.current"
                    v-model:page-size="searchParams.size"
                    layout="total, prev, pager, next, sizes"
                    :total="total"
                    @change="getList"
                />
            </div>
        </div>
        <el-dialog
            class="gd-dialog"
            v-model="isShowEditView"
            :title="titleTxt"
            :width="pxToRem(500)"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            @close="handleClose"
        >
            <el-form class="gd-dialog-form" ref="ruleFormRef" :model="editParams" :rules="rules">
                <el-form-item label="文档名称" prop="nickName">
                    <el-input v-model="editParams.nickName" class="gd-input" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="文档类型" prop="resultType" v-if="titleTxt === '上传巡查报告'">
                    <el-cascader
                        class="gd-cascader"
                        popper-class="gd-cascader-popper"
                        v-model="editParams.resultType"
                        :options="workOrderTypeXT"
                        :props="{ ...taskTypeCascaderProps, multiple: true }"
                        placeholder="请选择"
                        clearable
                        collapse-tags
                    />
                </el-form-item>
                <el-form-item label="上传文件" prop="link" v-if="titleTxt === '上传巡查报告'">
                    <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="onUploadFileBefore">
                        <el-button class="gd-upload-btn" type="primary">点击上传</el-button>
                    </el-upload>
                    <div class="upload-tip">
                        {{ uploadName }}
                    </div>
                </el-form-item>
            </el-form>
            <!-- </div> -->
            <template #footer>
                <el-button color="#F2F3F5" @click="isShowEditView = false">取消</el-button>
                <el-button
                    class=""
                    color="#4C34FF"
                    :loading="submitting"
                    :disabled="submitting"
                    @click="submit(ruleFormRef)"
                >
                    保存
                </el-button>
            </template>
        </el-dialog>
        <PreviewFiles v-model="previewVisible" :src="searchUrl" type="docx" />
        <!-- <el-image v-if="previewVisibleImg" :src="searchUrl" fit="contain" style="height: 100%;width: 100%" /> -->
        <el-image-viewer
            v-if="previewVisibleImg"
            :url-list="[searchUrl]"
            @close="previewVisibleImg = false"
        ></el-image-viewer>
    </basic-container>
</template>
<script setup>
import { Search, RefreshRight, Download, Upload } from '@element-plus/icons-vue'
import { fjPageApi, fjSubmitApi, fjRemoveApi, fjUploadApi, fjDownloadByByteApi } from './inspectionRequestApi'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PreviewFiles from '@/components/PreviewFiles/PreviewFiles.vue'
import { Base64 } from 'js-base64'
import { getDictListApi } from '@/api/zkxt'
import {
    getTaskTypeLabel,
    normalizeTaskTypeOptions,
    taskTypeCascaderProps,
} from '../taskTypeOptions'
 
const router = useRouter()
 
 
 
// 初始化查询参数
const initSearchParams = () => ({
    nickName: '',
    resultType: '',
    current: 1, // 当前页
    size: 10, // 每页大小
})
 
// 查看文档
const previewVisible = ref(false)
const previewVisibleImg = ref(false)
const searchUrl = ref('')
 
// 上传名称
const uploadName = ref('')
 
const workOrderTypeXT = ref([])
 
const searchParams = ref(initSearchParams()) // 查询参数
const total = ref(0) // 总条数
const loading = ref(true) // 列表加载中
const list = ref([]) // 列表数据
const selectedIds = ref([]) // 勾选的ID列表
const selectedFiles = ref([]) // 勾选的文件列表
const queryParamsRef = ref(null) // 查询表单实例
 
const isShowEditView = ref(false)
const titleTxt = ref('上传巡查报告')
const editParams = ref({
    id: '',
    nickName: '',
    resultType: '',
    link: '',
})
const ruleFormRef = ref()
const submitting = ref(false)
const rules = ref({
    nickName: [{ required: true, message: '请输入', trigger: ['blur'] }],
    resultType: [{ required: true, message: '请选择', trigger: ['change'] }],
    link: [{ required: true, message: '请上传', trigger: ['change'] }],
})
 
// 获取字典
function getDictList() {
    getDictListApi('task_inspection_type').then(res => {
        workOrderTypeXT.value = normalizeTaskTypeOptions(res.data.data || [])
    })
}
 
function toTaskTypeQueryValue(value) {
    return Array.isArray(value) ? value.join(',') : value
}
 
// 将字节大小转换为可读格式的函数
const formatFileSize = (bytes) => {
  if (bytes === 0 || bytes === null) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
 
// 获取列表
async function getList() {
    loading.value = true
    try {
        const res = await fjPageApi({
            ...searchParams.value,
            resultType: toTaskTypeQueryValue(searchParams.value.resultType),
        })
        list.value = res?.data?.data?.records ?? []
        total.value = res?.data?.data?.total ?? 0
    } finally {
        loading.value = false
    }
}
 
// 重置查询
function resetForm() {
    queryParamsRef.value?.resetFields()
    searchParams.value.current = 1
    getList()
}
 
// 查询
function handleSearch() {
    searchParams.value.current = 1
    getList()
}
 
// 新增/编辑/查看 弹框
function openForm(row) {
    isShowEditView.value = true
    titleTxt.value = '编辑'
    editParams.value.id = row.id
    editParams.value.nickName = row.nickName
    editParams.value.resultType = row.resultType
    editParams.value.link = row.link
}
 
 
// 'zip', 'rar', 'jar', 'tar', 'gzip', '7z',
const allSupportedExtensions = [
    'doc', 'docx', 'xls', 'xlsx', 'xlsm', 'ppt', 'pptx', 'csv', 'tsv', 'dotm', 'xlt', 'xltm', 'dot', 'dotx', 'xlam', 'xla',
    'wps', 'dps', 'et', 'ett', 'wpt',
    'odt', 'ods', 'ots', 'odp', 'otp', 'six', 'ott', 'fodt', 'fods',
    'vsd', 'vsdx', 'wmf', 'emf', 'psd',
    'pdf', 'ofd', 'rtf', 'epub',
    'xmind', 'bpmn', 'eml',
    'obj', '3ds', 'stl', 'ply', 'gltf', 'glb', 'off', '3dm', 'fbx', 'dae', 'wrl', '3mf', 'ifc', 'brep', 'step', 'iges', 'fcstd', 'bim',
    'dwg', 'dxf',
    'txt', 'xml', 'md', 'java', 'php', 'py', 'js', 'css',
    'jpg', 'jpeg', 'png', 'gif', 'bmp', 'ico', 'jfif', 'webp', 'tif', 'tiff', 'tga', 'svg',
    'mp3', 'wav', 'mp4', 'flv', 'avi', 'mov', 'rm', 'webm', 'ts', 'mkv', 'mpeg', 'ogg', 'mpg', 'rmvb', 'wmv', '3gp', 'swf'
];
const { VITE_APP_PREVIEW_URL } = import.meta.env
 
// kkfileView 中,word/pdf 默认转成只读 pdf 预览,excel 才是可编辑的 html 模式。
// 对这些类型追加 officePreviewType=html,让其以可编辑的 html 方式打开
const editableOfficeTypes = ['doc', 'docx', 'pdf']
 
// 在线查看文档
function seeOnlineWord(row) {
    // 获取点之后的文件格式名
    const fileType = (row?.link?.split('.').pop() || '').toLowerCase()
    if (!row.link) {
        ElMessage.warning('文件链接不存在')
    } else if (allSupportedExtensions.includes(fileType)){
        // let url = `${VITE_APP_PREVIEW_URL}/onlinePreview?url=` + encodeURIComponent(Base64.encode(row.link))
        // // word/pdf 以可编辑的 html 模式打开(与 excel 一致)
        // if (editableOfficeTypes.includes(fileType)) {
        //     url += '&officePreviewType=html'
        // }
        // window.open(url)
        const route = router.resolve({
            path: '/documentPreview/officeEdit',
            query: {
                attachId: row.id,
                mode: 'view',
            },
        })
        window.open(route.href, '_blank')
    } else {
        ElMessage.warning(`${fileType}文件格式,可以下载再查看`)
    }
}
 
// 取行的文件扩展名(列表数据没有 extension 字段,回退用 link 解析)
function getRowExtension(row) {
    return (row?.extension || row?.link?.split('.').pop() || '').toLowerCase()
}
 
// 是否为 zip 文件(zip 不支持在线编辑)
function isZipRow(row) {
    return getRowExtension(row) === 'zip'
}
 
function openOfficeEdit(row) {
    if (!row?.id) {
        ElMessage.warning('附件ID不存在')
        return
    }
    if (isZipRow(row)) {
        ElMessage.warning('zip文件格式,不能编辑')
        return
    }
 
    const route = router.resolve({
        path: '/documentPreview/officeEdit',
        query: {
            attachId: row.id,
            mode: 'edit',
        },
    })
    window.open(route.href, '_blank')
    // 标记已跳转去编辑,切回本页时刷新列表
    pendingEditRefresh = true
}
 
// 删除
async function handleDelete(row) {
    const tips = row ? '该条' : '选中的项'
    await ElMessageBox.confirm(`确认删除${tips}吗?`, '提示', {
        type: 'warning',
        customClass: 'gd-confirm-custom',
        confirmButtonClass: 'gd-confirm-button',
        cancelButtonClass: 'gd-confirm-cancel-button',
    })
    const ids = row ? row.id : selectedIds.value.join(',')
    await fjRemoveApi({ ids })
    ElMessage.success('删除成功')
    selectedIds.value = []
    getList()
}
 
// 勾选值设置
function handleSelectionChange(rows) {
    selectedFiles.value = rows
    selectedIds.value = rows.map(item => item.id)
}
let loadingData
// 文档下载
async function handleDownload() {
    // 如果是勾选一个可以直接下载,超过一个打包下载
    // 依次下载每个文件(添加延迟以避免浏览器限制)
    if (selectedFiles.value.length === 0) {
        ElMessage.warning('请选择要下载的文件')
        return
    }
    // if (selectedFiles.value.length === 1) {
    //     selectedFiles.value.forEach(async (file, index) => {
    //         if (file.link) {
    //             try {
    //                 // 使用 fetch 获取 blob 数据来强制下载,避免浏览器打开文件
    //                 const response = await fetch(file.link)
    //                 if (!response.ok) {
    //                     throw new Error(`Failed to fetch file: ${response.status}`)
    //                 }
    //                 const blob = await response.blob()
    //                 const url = URL.createObjectURL(blob)
    //                 const a = document.createElement('a')
    //                 a.href = url
    //                 a.download = file.originalName || `attachment_${index + 1}`
    //                 document.body.appendChild(a)
    //                 a.click()
    //                 document.body.removeChild(a)
    //                 // 释放 URL 对象
    //                 setTimeout(() => URL.revokeObjectURL(url), 100)
    //                 ElMessage.success('下载成功')
    //             } catch (error) {
    //                 console.error('Download error:', error)
    //                 ElMessage.error(`下载文件 ${file.originalName} 失败: ${error.message}`)
    //             }
    //         }
    //     })
    // } else {
            try {
            const fileIds = selectedFiles.value.map(i => i.id).join(',')
            await fjDownloadByByteApi({ attachIds: fileIds }).then(res => {
            const blob = res.data
            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            a.download = `巡查报告.zip`
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            URL.revokeObjectURL(url)
                    ElMessage.success('下载成功')
                })
            } catch (e) {
            } finally {
                // loadingData.close()
            }
 
    // }
}
 
// 文档上传
async function handleUpload() {
    isShowEditView.value = true
    titleTxt.value = '上传巡查报告'
}
 
// 上传文件前处理
function onUploadFileBefore(file) {
    // 执行文件上传
    let data = new FormData()
    // 获取文件扩展名
  const fileExtension = file.name.split('.').pop().toLowerCase();
    data.append('file', file)
 
    fjUploadApi(data).then(res => {
        if (res.data.code === 200) {
            ElMessage.success('上传成功')
            // 保存文件URL到表单
            uploadName.value = res.data.data.originalName
            editParams.value.link = res.data.data.link
            editParams.value.name = res.data.data.name
            editParams.value.originalName = res.data.data.originalName
            editParams.value.attachSize = file.size;
            editParams.value.extension = fileExtension
            editParams.value.domainUrl = res.data.data.link.replace(res.data.data.name, '')
        } else {
            ElMessage.error(res.msg || '上传失败')
        }
    })
 
    return false // 阻止组件的默认上传行为
}
 
// 保存上传文件数据
async function submit(formValidate) {
    if (!formValidate) return
    await formValidate.validate(async (valid, fields) => {
        if (valid) {
            submitting.value = true
            try {
                await fjSubmitApi(editParams.value)
                ElMessage.success('保存成功')
                isShowEditView.value = false
                getList()
            } finally {
                submitting.value = false
            }
        }
    })
}
 
function handleClose() {
    // 清除表单内容
    uploadName.value = ''
    editParams.value = {
        id: '',
        nickName: '',
        resultType: '',
        uploadFile: '',
    }
}
 
// 在线编辑跳转标记:从编辑页切回本页时刷新列表
let pendingEditRefresh = false
function handleVisibilityChange() {
    if (document.visibilityState === 'visible' && pendingEditRefresh) {
        pendingEditRefresh = false
        getList()
    }
}
 
onMounted(() => {
    getDictList()
    getList()
    document.addEventListener('visibilitychange', handleVisibilityChange)
})
 
onBeforeUnmount(() => {
    document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>
<style scoped lang="scss">
// 操作列里链接的文字(span)被主题强制刷成蓝色 #0075FF,
// 禁用时需在这里把 span 一并置灰,否则「在线编辑」禁用了还是蓝的
:deep(.operation-btns) {
    .el-link.is-disabled,
    .el-link.is-disabled span {
        color: #c0c4cc !important;
        cursor: not-allowed !important;
    }
}
</style>