app-data-upload.vue 21.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<template>
    <div class="app-data-upload-view" element-loading-background="rgba(57, 57, 57, 0.2)">
        <input
            ref="inputUpLoad"
            type="file"
            style="display: none"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            @change="fileChange"
        />
        <div class="main-content">
11 12 13 14 15 16 17
            <template v-if="asyncActionState">
                <div class="data-info-container">
                    <div class="message-container">
                        <div class="upload-progress-container">
                            <el-progress :percentage="dataProgress"></el-progress>
                            <div>{{ dataProgressText }}</div>
                        </div>
18 19
                    </div>
                </div>
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
            </template>
            <template v-else>
                <div v-if="!selectedFile" class="upload-container" @click="handleUpLoad">
                    <img class="icon-import" src="@/assets/img/icon-import.svg" />
                    <span class="select-file-text">{{ $t('components.appdatauploadview.selectfile') }}</span>
                </div>
                <div v-else class="data-info-container">
                    <div v-if="!isUploaded" class="message-container">
                        <div class="success-list" v-if="!isUploading">
                            {{ $t('components.appdatauploadview.selectfilesucess') }}
                        </div>
                        <div class="success-list" v-if="isUploading">
                            <div class="upload-progress-container">
                                <!-- <el-progress :percentage="uploadedProgress"></el-progress> -->
                                <div>正在上传文件,请稍候</div>
                            </div>
                        </div>
                    </div>
                    <div v-else class="message-container">
                        <div class="result-list">
                            <ul v-if="Object.keys(responseResult).length > 0">
                                <template v-if="ignoreError">
                                    <li class="title">
                                        <span>{{ $t('components.appdatauploadview.importresult') }}</span>
                                    </li>
                                    <li>
                                        <span>
                                            {{ $t('components.appdatauploadview.totaldata') }}
                                            {{ responseResult.total }}
                                            {{ $t('components.appdatauploadview.total') }}{{
                                                $t('app.commonwords.wrong')
                                            }}[{{ responseResult.error }}],{{ $t('app.commonwords.success') }}[{{
                                                responseResult.success
                                            }}]
                                        </span>
                                    </li>
                                </template>
                                <template v-if="responseResult.errorInfos && responseResult.errorInfos.length !== 0">
                                    <li class="title">
                                        <span>{{ $t('components.appdatauploadview.errorinfo') }}</span>
                                    </li>
                                    <li
                                        class="error-item"
                                        v-for="(item, index) in responseResult.errorInfos"
                                        :key="index"
                                    >
                                        <span v-if="item.index"
                                            >{{ $t('components.appdatauploadview.start') }} {{ item.index }}
                                            {{ $t('components.appdatauploadview.row') }}</span
                                        ><span v-html="item.errorinfo"></span>
                                    </li>
                                </template>
                            </ul>
                        </div>
74 75
                    </div>
                </div>
76
            </template>
77 78 79 80 81 82 83
        </div>
        <el-row class="second-content">
            <el-col>
                <div class="import-template-message">{{ $t('components.appdatauploadview.datatemplatemessage') }}</div>
                <div class="import-template">
                    <img class="icon-link" src="@/assets/img/icon-link.svg" />
                    <span style="cursor: pointer" @click="downloadTemp">
84
                        {{ viewparams.appDeLogicName + $t('components.appdatauploadview.datatemplate') }}</span
85 86 87
                    >
                </div>
            </el-col>
88 89 90 91 92
            <div
                class="import-template-download-info"
                v-if="isUploaded && responseResult.errorfile"
                @click="downloadFeedbackMsg"
            >
93 94 95 96
                {{ $t('components.appdatauploadview.downloadinfo') }}
            </div>
        </el-row>
        <el-row class="button-container">
97 98 99
            <el-button @click="handleCancel">{{
                asyncActionState ? '确认' : $t('components.appdatauploadview.cancel')
            }}</el-button>
100
            <el-button
101
                v-if="!asyncActionState"
102 103 104 105 106 107 108 109 110 111 112 113 114
                :disabled="!selectedFile"
                :loading="isUploading"
                type="primary"
                @click="uploadServer"
                >{{ $t('components.appdatauploadview.uploadserver') }}</el-button
            >
        </el-row>
    </div>
</template>

<script lang="ts">
import axios from 'axios';
import { AppServiceBase, Util } from 'ibiz-core';
115 116 117 118 119 120 121 122 123
import {
    ActionState,
    AppCenterService,
    AppNoticeService,
    NotificationFactory,
    NotificationItem,
    SubType,
} from 'ibiz-vue';
import { Subscription } from 'rxjs';
124 125 126 127 128 129 130 131 132 133
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';

@Component({})
export default class AppDataUploadView extends Vue {
    /**
     * 传入视图参数
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
134
    @Prop() public dynamicProps!: string;
135 136 137 138 139 140 141

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof AppDataUploadView
     */
142
    public viewparams: any = {};
143 144 145 146 147 148 149

    /**
     * 视图上下文
     *
     * @type {*}
     * @memberof AppDataUploadView
     */
150
    public viewdata: any = {};
151 152 153 154 155 156 157

    /**
     * 是否忽略错误
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
158
    public ignoreError: boolean = false;
159 160 161 162 163 164 165

    /**
     * 选择文件数据
     *
     * @type {*}
     * @memberof AppDataUploadView
     */
166
    public selectedFile: any | null = null;
167 168 169 170 171 172 173

    /**
     * 是否上传完成
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
174
    public isUploaded: boolean = false;
175 176 177 178 179 180 181

    /**
     * 上传进度
     *
     * @type {number}
     * @memberof AppDataUploadView
     */
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    public uploadedProgress: number = 0;

    /**
     * 数据导入进度
     *
     * @type {number}
     * @memberof AppDataUploadView
     */
    public dataProgress: number = 0;

    /**
     * 数据导入进度文本
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    public dataProgressText: string = '';
199 200 201 202 203 204 205

    /**
     * 是否上传过程中
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
206
    public isUploading: boolean = false;
207 208 209 210 211 212 213

    /**
     * 导入结果集合
     *
     * @type {Array<*>}
     * @memberof AppDataUploadView
     */
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
    public responseResult: any = {};

    /**
     * 是否启用异步导入
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
    public enableAsyncImport: boolean = false;

    /**
     * 异步导入状态(true:当前环境存在异步作业/false:当前环境不存在异步作业)
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
    public asyncActionState: boolean = false;

    /**
     * 应用状态事件
     *
     * @type {Subscription | undefined}
     * @memberof AppDataUploadView
     */
    public appStateEvent: Subscription | undefined;

    /**
     * vue  生命周期
     *
     * @memberof Breadcrumb
     */
    created() {
        const Environment = AppServiceBase.getInstance().getAppEnvironment();
        this.enableAsyncImport = Environment.enableAsyncImport;
        if (this.enableAsyncImport) {
            this.initAsyncActionState();
            this.handleAsyncAction();
        }
    }

    /**
     * 组件销毁
     */
    destroyed() {
        if (this.appStateEvent) {
            this.appStateEvent.unsubscribe();
        }
    }
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

    /**
     * 视图参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppDataUploadView
     */
    @Watch('dynamicProps', { immediate: true, deep: true })
    onParamData(newVal: any, oldVal: any) {
        if (newVal) {
            this.viewparams = eval('(' + newVal.viewparam + ')');
            this.viewdata = eval('(' + newVal.viewdata + ')');
            this.ignoreError = this.viewparams?.ignoreError;
        }
    }

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
    /**
     * 初始化异步消息状态
     *
     * @memberof AppDataUploadView
     */
    public initAsyncActionState() {
        const asyncActionService = NotificationFactory.getInstance().getSubInstance(SubType.ASYNCACTION);
        if (asyncActionService) {
            const items = asyncActionService.getItems(true);
            if (items && items.length > 0) {
                const targetItem = items.find((item: NotificationItem) => {
                    return (
                        this.viewparams.serviceName.toUpperCase() === item.actionparam &&
                        this.viewparams.importId === item.actionparam2 &&
                        item.state === ActionState.CREATING
                    );
                });
                if (targetItem) {
                    this.asyncActionState = true;
                    this.dataProgress = targetItem.completionrate ? targetItem.completionrate : 0;
                    this.dataProgressText = '正在导入数据,请稍候';
                }
            }
        }
    }

    /**
     * 处理异步消息
     *
     * @memberof AppDataUploadView
     */
    public handleAsyncAction() {
        this.appStateEvent = AppCenterService.getMessageCenter().subscribe(
            ({ name, action, data }: { name: string; action: string; data: any }) => {
                if (!Object.is(name, 'AsyncAction')) {
                    return;
                }
                if (Object.is(action, 'AddItem')) {
                    if (
                        Object.is(this.viewparams.importId, data.actionparam2) &&
                        Object.is(this.viewparams.serviceName.toUpperCase(), data.actionparam)
                    ) {
                        if (data.state === ActionState.CREATING) {
                            this.dataProgress = data.completionrate ? data.completionrate : 0;
                            this.dataProgressText = '正在导入数据,请稍候';
                        }
                        if (data.state === ActionState.CREATED) {
                            const actionresult = JSON.parse(data.actionresult);
                            this.dataProgress = 100;
                            this.dataProgressText = `数据导入成功,导入数据共计${actionresult.total}条,成功导入${actionresult.success}条`;
                        }
                    }
                }
            },
        );
    }

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
    /**
     * 选择文件
     *
     * @memberof AppDataUploadView
     */
    public handleUpLoad() {
        (this.$refs.inputUpLoad as any).click();
    }

    /**
     * 取消
     *
     * @memberof AppDataUploadView
     */
    public handleCancel() {
        this.$emit('close', []);
    }

    /**
     * 文件数据变化
     *
     * @memberof AppDataUploadView
     */
    public fileChange($event: any) {
        let obj = $event.target || $event.srcElement;
        if (!obj.files) {
            return;
        }
        this.selectedFile = obj.files?.[0];
    }

    /**
     * 设置UI状态
     *
     * @memberof AppDataUploadView
     */
    public setUIState(uploadedProgress: number, isUploading: boolean, isUploaded: boolean, result: any = {}) {
        this.uploadedProgress = uploadedProgress;
        this.isUploading = isUploading;
        this.isUploaded = isUploaded;
        this.responseResult = result;
    }

    /**
     * 下载导入数据模板
     *
     * @memberof AppDataUploadView
     */
    public downloadTemp() {
        let requestUrl: string = '';
386 387 388 389 390 391
        if (
            this.viewdata &&
            this.viewdata.srfparentkey &&
            this.viewdata.srfparentdename &&
            this.viewdata.srfparentdename !== this.viewdata.appEntityName
        ) {
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
            requestUrl += `/${Util.srfpluralize(this.viewdata.srfparentdename)}/${this.viewdata.srfparentkey}`;
        }
        requestUrl += `/${Util.srfpluralize(this.viewparams.serviceName)}/importtemplate`;
        if (this.viewparams.importId) {
            requestUrl += `?srfimporttag=${this.viewparams.importId}`;
        }
        axios({
            url: requestUrl,
            method: 'get',
            responseType: 'blob',
        }).then((response: any) => {
            if (response.status == 200) {
                let fileName = response.headers['content-disposition']
                    .split(';')
                    .find((str: string) => str.indexOf('filename=') != -1)
                    ?.slice(9);
                fileName = decodeURIComponent(fileName);
                let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
                let elink = document.createElement('a');
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
            }
        });
    }

    /**
     * 下载导入反馈信息
     *
     * @memberof AppDataUploadView
     */
427 428
    public downloadFeedbackMsg() {
        if (!this.responseResult || !this.responseResult.errorfile || !this.responseResult.errorfile.fileid) {
429 430 431
            this.$throw(this.$t('components.appdatauploadview.downloaderror'));
            return;
        }
432 433 434
        let downloadUrl: string = `${AppServiceBase.getInstance().getAppEnvironment().ExportFile}/${
            this.responseResult.errorfile.folder
        }/${this.responseResult.errorfile.fileid}`;
435 436 437 438 439
        const headers = {};
        axios({
            method: 'get',
            url: downloadUrl,
            headers: headers,
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
            responseType: 'blob',
        })
            .then((response: any) => {
                if (!response || response.status != 200) {
                    this.$throw(this.$t('components.appdatauploadview.downloaderror'));
                    return;
                }
                // 请求成功,后台返回的是一个文件流
                if (response.data) {
                    // 获取文件名
                    const filename = `导入错误${this.responseResult.errorfile.fileid}.xlsx`;
                    let filetype = this.calcFilemime('xlsx');
                    // 用blob对象获取文件流
                    let blob = new Blob([response.data], { type: filetype });
                    // 通过文件流创建下载链接
                    var href = URL.createObjectURL(blob);
                    // 创建一个a元素并设置相关属性
                    let a = document.createElement('a');
                    a.href = href;
                    a.download = filename;
                    // 添加a元素到当前网页
                    document.body.appendChild(a);
                    // 触发a元素的点击事件,实现下载
                    a.click();
                    // 从当前网页移除a元素
                    document.body.removeChild(a);
                    // 释放blob对象
                    URL.revokeObjectURL(href);
                } else {
                    this.$throw(this.$t('components.appfileupload.downloaderror'));
                }
            })
            .catch((error: any) => {
                console.error(error);
            });
475 476 477 478 479 480 481 482
    }

    /**
     * 计算文件mime类型
     *
     * @param filetype 文件后缀
     * @memberof AppDataUploadView
     */
483 484
    public calcFilemime(filetype: string): string {
        let mime = 'application/vnd.ms-excel';
485
        switch (filetype) {
486 487
            case '.xlsx':
                mime = 'application/vnd.ms-excel';
488
                break;
489 490
            case '.wps':
                mime = 'application/kswps';
491
                break;
492 493
            case '.doc':
                mime = 'application/msword';
494
                break;
495 496
            case '.docx':
                mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
497
                break;
498 499
            case '.txt':
                mime = 'text/plain';
500
                break;
501 502
            case '.zip':
                mime = 'application/zip';
503
                break;
504 505
            case '.png':
                mime = 'image/png';
506
                break;
507 508
            case '.gif':
                mime = 'image/gif';
509
                break;
510 511
            case '.jpeg':
                mime = 'image/jpeg';
512
                break;
513 514
            case '.jpg':
                mime = 'image/jpeg';
515
                break;
516 517
            case '.rtf':
                mime = 'application/rtf';
518
                break;
519 520
            case '.avi':
                mime = 'video/x-msvideo';
521
                break;
522 523
            case '.gz':
                mime = 'application/x-gzip';
524
                break;
525 526
            case '.tar':
                mime = 'application/x-tar';
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
                break;
        }
        return mime;
    }

    /**
     * 上传服务器
     *
     * @memberof AppDataUploadView
     */
    public uploadServer() {
        if (!this.selectedFile) {
            return;
        }
        try {
            let requestUrl: string = '';
            this.setUIState(0, true, false);
            if (this.viewdata && this.viewdata.srfparentkey && this.viewdata.srfparentdename) {
                requestUrl += `/${Util.srfpluralize(this.viewdata.srfparentdename)}/${this.viewdata.srfparentkey}`;
            }
547 548 549 550 551
            if (this.enableAsyncImport) {
                requestUrl += `/${Util.srfpluralize(this.viewparams.serviceName)}/asyncimportdata2`;
            } else {
                requestUrl += `/${Util.srfpluralize(this.viewparams.serviceName)}/importdata2`;
            }
552 553 554 555 556 557 558 559 560 561 562 563 564
            if (this.viewparams.importId) {
                requestUrl += `?srfimporttag=${this.viewparams.importId}`;
            }
            const data = new FormData();
            data.append('file', this.selectedFile);
            axios
                .post(requestUrl, data, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    onUploadProgress: (progressEvent: any) => {
                        this.uploadedProgress = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
                    },
                })
                .then((res: any) => {
565
                    // 忽略错误时的提示信息
566 567
                    const result: any = {};
                    if (res && res.status && res.status == 200) {
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
                        if (this.enableAsyncImport) {
                            AppNoticeService.getInstance().success(
                                '正在导入数据,您可以在消息中心中查看数据导入的状态。',
                                { duration: 5000, showClose: true },
                            );
                            this.$emit('close', []);
                        } else {
                            const { data: data } = res;
                            const { errorinfo, success, total, errorfile } = data;
                            result.total = total ? Number(total) : 0;
                            result.success = success ? Number(success) : 0;
                            result.errorfile = errorfile;
                            if (errorinfo && Object.keys(errorinfo).length > 0) {
                                result.error = Object.keys(errorinfo).length;
                                result.errorInfos = [];
                                Object.keys(errorinfo).forEach((item: any) => {
                                    result.errorInfos.push({
                                        index: Number(item) + 1,
                                        errorinfo: errorinfo[item].errorInfo,
                                    });
                                });
                            }
590 591 592
                        }
                    }
                    this.setUIState(0, false, true, result);
593 594 595
                })
                .catch((error: any) => {
                    // 不忽略错误时的提示信息
596 597 598
                    const errorResult: any = {};
                    if (error && error.status && error.status !== 200) {
                        errorResult.errorInfos = [];
599 600 601
                        errorResult.errorInfos.push({
                            errorinfo: error.data?.message || this.$t('app.commonwords.sysexception'),
                        });
602 603 604
                    }
                    this.setUIState(0, false, true, errorResult);
                });
605 606 607 608
        } catch (error) {
            this.setUIState(0, false, true, {
                errorInfos: [{ errorinfo: error.data || this.$t('app.commonwords.sysexception') }],
            });
609 610 611 612 613
        }
    }
}
</script>

614
<style lang="less">
615
@import './app-data-upload.less';
616
</style>