app-data-upload.vue 19.1 KB
Newer Older
1
<template>
tony001's avatar
tony001 committed
2 3 4 5
    <div class="app-data-upload-view" v-loading.fullscreen="isUploading"
        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="importFile" />
Mosher's avatar
Mosher committed
6
        <div class="main-content">
tony001's avatar
tony001 committed
7 8
            <div v-if="importDataArray.length === 0 && !isUploading && uploadProgress !== 100" class="upload-container"
                @click="handleUpLoad">
Mosher's avatar
Mosher committed
9
                <img class="icon-import" src="@/assets/img/icon-import.svg" />
10
                <span class="select-file-text">{{ $t("components.appDataUploadView.selectfile") }}</span>
11
            </div>
12
            <div class="data-info-container" v-if="importDataArray.length > 0 || isUploading || uploadProgress == 100">
tony001's avatar
tony001 committed
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
                <el-progress class="progress" v-show="isUploading" :text-inside="true" :stroke-width="14"
                    :percentage="uploadProgress"></el-progress>
                <div class="message-container">
                    <div class="result-list">
                        <template v-if="(errorInfos.length === 0)">
                            <span>{{ promptInfo }}</span>
                        </template>
                        <template v-else>
                            <span>导入错误信息</span>
                            <ui>
                                <li class="error-item" v-for="(item, index) in errorInfos" :key="index">
                                    <span v-if="item.index">{{ $t('components.appDataUploadView.start') }} {{item.index}} {{ $t('components.appDataUploadView.row') }}</span><span v-html="item.info"></span>
                                </li>
                            </ui>
                        </template>  
                    </div>
                </div>
            </div>
        </div>
        <div class="second-content">
            <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">{{ $t('components.appDataUploadView.datatemplate') }}</span>
38
            </div>
Mosher's avatar
Mosher committed
39 40
        </div>
        <el-row class="button-container">
41
            <el-button type="primary" @click="handleCancel">{{ $t("components.appDataUploadView.cancel") }}</el-button>
tony001's avatar
tony001 committed
42 43 44
            <el-button :disabled="importDataArray.length === 0" :loading="isUploading" type="primary"
                class="primary-button" @click="uploadServer">{{ $t("components.appDataUploadView.uploadserver")
                }}</el-button>
45 46 47 48 49
        </el-row>
    </div>
</template>

<script lang="ts">
50 51 52 53 54 55
import XLSX from "xlsx";
import CodeListService from "@/codelist/codelist-service";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import { Environment } from "@/environments/environment";
import moment from "moment";
import { Util } from "@/utils";
56

Mosher's avatar
Mosher committed
57
@Component({})
58
export default class AppDataUploadView extends Vue {
59 60 61 62 63 64 65
    /**
     * 传入视图上下文
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    @Prop() protected viewdata!: string;
66

67 68 69 70 71 72 73
    /**
     * 传入视图参数
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    @Prop() protected viewparam!: string;
74 75

    /**
76
     * 代码表服务对象
77
     *
78
     * @type {CodeListService}
79 80 81
     * @memberof AppDataUploadView
     */

82
    public codeListService: CodeListService = new CodeListService({ $store: this.$store });
83

84 85 86 87 88 89 90 91
    /**
     * 实体服务对象
     *
     * @protected
     * @type {EntityService}
     * @memberof AppDataUploadView
     */
    protected entityService: any;
92 93

    /**
94
     * 视图参数
95
     *
Mosher's avatar
Mosher committed
96
     * @type {*}
97 98
     * @memberof AppDataUploadView
     */
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    protected viewparams: any = {};

    /**
     * 导入数据模型
     *
     * @type {Array<*>}
     * @memberof AppDataUploadView
     */
    protected importDataModel: Array<any> = [];

    /**
     * 导入数据集合
     *
     * @type {Array<*>}
     * @memberof AppDataUploadView
     */
    public importDataArray: Array<any> = [];
116 117

    /**
118 119 120 121 122 123 124 125 126
     * 导入标识
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    protected importId: string = "";

    /**
     * 是否已有导入数据
127 128 129 130
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
131
    public hasImported: boolean = false;
132 133

    /**
134
     * 导入数据识别项属性
135
     *
136
     * @type {string}
137 138
     * @memberof AppDataUploadView
     */
139
    public importUniqueItem: string = "";
140 141

    /**
142 143 144 145 146 147 148 149 150
     * 提示信息
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    public promptInfo: string = "";

    /**
     * 导入状态
151 152 153 154
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
Mosher's avatar
Mosher committed
155
    public isUploading: boolean = false;
156

157 158 159 160
    /**
     * 导入失败数据
     *
     * @type {string}
161 162
     * @memberof AppDataUploadView
     */
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
    public importErrorData: Array<any> = [];

    /**
     * 读取完成的数据
     *
     * @type {*}
     * @memberof AppDataUploadView
     */
    public workBookData: any;

    /**
     * 所有的代码表
     *
     * @type {*}
     * @memberof AppDataUploadView
     */
    public allCodeList: any;

    /**
     * 属性Map(用作属性转化)
     *
     * @type {*}
     * @memberof AppDataUploadView
     */
    public allFieldMap: Map<string, any> = new Map();

    /**
     * 上传服务器数据切片数
     *
     * @type {number}
     * @memberof AppDataUploadView
     */
    public sliceUploadCnt: number = Environment.sliceUploadCnt;

    /**
     * 上传服务器进度条百分比
     *
     * @type {number}
     * @memberof AppDataUploadView
     */
    public uploadProgress: number = 0;
204

tony001's avatar
tony001 committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    /**
     * 是否忽略导入错误
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
    public ignoreError: boolean = false;

    /**
     * 错误消息集合
     *
     * @type {any[]}
     * @memberof AppDataUploadView
     */
    public errorInfos: any[] = [];

    /**
     * 导入成功计数
     *
     * @type {number}
     * @memberof AppDataUploadView
     */
    public successCount: number = 0;

229 230 231 232 233 234 235
    /**
     * 视图参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppDataUploadView
     */
236
    @Watch("viewparam", { immediate: true, deep: true })
237
    onParamData(newVal: any, oldVal: any) {
Mosher's avatar
Mosher committed
238
        if (newVal) {
239 240
            Object.assign(this.viewparams, JSON.parse(this.viewparam));
            this.initBasic();
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
    /**
     * 初始化基础数据
     *
     * @memberof AppDataUploadView
     */
    public async initBasic() {
        if (this.viewparams.importId) {
            this.importId = this.viewparams.importId;
        }
        if (this.viewparams.importData) {
            this.importDataModel = Object.values(this.viewparams.importData);
            this.bubbleSort(this.importDataModel, this.importDataModel.length);
        }
        this.importDataModel.forEach((item: any) => {
            if (item.isuniqueitem) {
                this.importUniqueItem = item.headername;
            }
            this.allFieldMap.set(item.headername, item);
        });
        if (this.viewparams.serviceName) {
            this.entityService = await window.entityServiceRegister.getService(this.viewparams.serviceName.toLowerCase());
        }
tony001's avatar
tony001 committed
266
        this.ignoreError = this.viewparams.ignoreError === true || this.viewparams.ignoreError === 'true' ? true : false;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        //获取代码表值
        this.allCodeList = await this.getChartAllCodeList();
    }

    /**
     * 冒泡排序
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppDataUploadView
     */
    public bubbleSort(array: Array<any>, length: number) {
        for (let i = 0; i < length; i++) {
            for (let j = 0; j < length - i - 1; j++) {
                if (array[j].order > array[j + 1].order) {
                    let temp: any;
                    temp = array[j + 1];
                    array[j + 1] = array[j];
                    array[j] = temp;
                }
            }
288 289 290
        }
    }

291 292 293 294 295 296
    /**
     * 下载导入数据模板
     *
     * @memberof AppDataUploadView
     */
    public downloadTemp() {
tony001's avatar
tony001 committed
297
        this.importExcel(this.viewparams.appDeLogicName + this.$t("components.appDataUploadView.datatemplate"), []);
298 299
    }

300 301 302 303 304
    /**
     * 选择文件
     *
     * @memberof AppDataUploadView
     */
Mosher's avatar
Mosher committed
305
    public handleUpLoad() {
306 307 308
        (this.$refs.inputUpLoad as any).click();
    }

309 310 311 312 313 314 315 316 317 318 319 320 321 322
    /**
     * 上传服务器
     *
     * @memberof AppDataUploadView
     */
    public uploadServer() {
        if (this.importDataArray.length == 0 || !this.entityService) {
            return;
        }
        let tempDataArray: Array<any> = [];
        this.transformData(this.importDataArray, tempDataArray);
        this.hasImported = true;
        this.isUploading = true;
        this.uploadProgress = 0;
tony001's avatar
tony001 committed
323
        this.successCount = 0;
324 325 326 327 328 329 330 331 332 333
        this.importDataArray = [];
        this.sliceUploadService(tempDataArray, 0);
    }

    /**
     * 数据切片上传
     *
     * @memberof AppDataUploadView
     */
    public sliceUploadService(dataArray: Array<any>, cnt: number) {
tony001's avatar
tony001 committed
334
        if (cnt >= dataArray.length) {
335 336
            this.isUploading = false;
            this.uploadProgress = 100;
Mosher's avatar
Mosher committed
337
            this.$Notice.success({ desc: this.$t("components.appDataUploadView.completed") as string });
tony001's avatar
tony001 committed
338
            this.promptInfo = `${this.$t('components.appDataUploadView.completed')}, ${this.$t('components.appDataUploadView.totaldata')} ${this.successCount} ${this.$t('components.appDataUploadView.total')}`;
339 340 341 342 343 344 345 346
            return;
        }
        let sliceArray: Array<any> = [];
        if (dataArray) {
            sliceArray = dataArray.slice(cnt, cnt + this.sliceUploadCnt);
        }
        try {
            this.entityService
tony001's avatar
tony001 committed
347
                .ImportData(this.viewdata, { name: this.importId, importData: sliceArray, ignoreError: this.ignoreError })
348 349
                .then((res: any) => {
                    const result: any = res.data;
tony001's avatar
tony001 committed
350 351 352 353 354 355 356
                    this.successCount += result.success;
                    if (result.total !== result.success) {
                        this.handleErrorInfo(result.errorinfo, cnt);
                        if (!this.ignoreError) {
                            this.isUploading = false;
                            return;
                        }
357 358 359 360 361 362 363 364 365
                    }
                    this.uploadProgress = Number(((cnt / dataArray.length) * 100).toFixed(2));
                    this.sliceUploadService(dataArray, cnt + this.sliceUploadCnt);
                })
                .catch((error: any) => {
                    this.isUploading = false;
                    this.promptInfo = this.$t("components.appDataUploadView.importfailed") as string;
                });
        } catch (error: any) {
tony001's avatar
tony001 committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
            this.handleErrorInfo(error.errorinfo, cnt);
            if (!this.ignoreError) {
                this.isUploading = false;
                return;
            }
            this.uploadProgress = Number(((cnt / dataArray.length) * 100).toFixed(2));
            this.sliceUploadService(dataArray, cnt + this.sliceUploadCnt);
        }
    }

    /**
     * 处理错误信息
     *
     * @memberof AppDataUploadView
     */
    public handleErrorInfo(infos: any[], cnt: number) {
        if (infos && infos.length) {
            infos.forEach((item: any) => {
                this.errorInfos.push(Object.assign({
                    index: cnt + item.row
                }, item));
            })
388 389 390
        }
    }

391
    /**
Mosher's avatar
Mosher committed
392
     * 取消
393 394 395
     *
     * @memberof AppDataUploadView
     */
Mosher's avatar
Mosher committed
396
    public handleCancel() {
tony001's avatar
tony001 committed
397
        this.$emit("close", this.successCount > 0 ? [{ count: this.successCount }] : []);
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    }

    /**
     * 导出excel
     *
     * @memberof AppDataUploadView
     */
    public async importExcel(filename: string, _data: any) {
        const tHeader: Array<any> = [];
        this.importDataModel.forEach((item: any) => {
            tHeader.push(item.headername);
        });
        this.$export.exportExcel().then((excel: any) => {
            excel.export_json_to_excel({
                header: tHeader, //表头 必填
                data: [], //具体数据 必填
                filename: filename, //非必填
                autoWidth: true, //非必填
                bookType: "xlsx", //非必填
            });
        });
419 420 421
    }

    /**
422
     * 确认
423 424 425
     *
     * @memberof AppDataUploadView
     */
426
    public handleOK() {
tony001's avatar
tony001 committed
427
        this.$emit("close", this.successCount > 0 ? [{ count: this.successCount }] : []);
428 429 430 431 432 433 434 435
    }

    /**
     * 导入Excel
     *
     * @memberof AppDataUploadView
     */
    public importFile($event: any) {
Mosher's avatar
Mosher committed
436 437
        let obj = $event.target || $event.srcElement;
        if (!obj.files) {
438 439
            return;
        }
440 441 442 443 444 445 446 447 448
        let f = obj.files[0];
        let reader = new FileReader();
        reader.onload = (e: any) => {
            let data = e.target.result;
            this.workBookData = XLSX.read(data, { type: "binary", cellDates: true });
            let xlsxData = XLSX.utils.sheet_to_json(this.workBookData.Sheets[this.workBookData.SheetNames[0]]);
            let list1 = this.getFirstRow(this.workBookData);
            xlsxData = this.addXlsxData(xlsxData, list1);
            this.importDataArray = Util.deepCopy(xlsxData);
tony001's avatar
tony001 committed
449
            this.promptInfo = this.$t('components.appDataUploadView.read') as string;
450 451 452
            (this.$refs.inputUpLoad as any).value = "";
        };
        reader.readAsBinaryString(f);
453 454 455
    }

    /**
456
     * 获取excel第一行的内容
457 458 459
     *
     * @memberof AppDataUploadView
     */
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    public getFirstRow(wb: any) {
        //// 读取的excel单元格内容
        let wbData = wb.Sheets[wb.SheetNames[0]];
        // 匹配excel第一行的内容
        let re = /^[A-Z]1$/;
        let temparr = [];
        // excel第一行内容赋值给数组
        for (let key in wbData) {
            if (wbData.hasOwnProperty(key)) {
                if (re.test(key)) {
                    temparr.push(wbData[key].h);
                }
            }
        }
        return temparr;
475 476 477
    }

    /**
478
     * 增加对应字段空白内容
479 480 481
     *
     * @memberof AppDataUploadView
     */
482 483 484 485 486 487 488 489 490 491
    public addXlsxData(xlsxData: any, list1: any) {
        // 空白字段替换值
        let addData = null;
        for (let i = 0; i < xlsxData.length; i++) {
            // 要被JSON的数组
            for (let j = 0; j < list1.length; j++) {
                // excel第一行内容
                if (!xlsxData[i][list1[j]]) {
                    xlsxData[i][list1[j]] = addData;
                }
Mosher's avatar
Mosher committed
492
            }
493 494
        }
        return xlsxData;
495 496 497
    }

    /**
498
     * 获取图表所需代码表
Mosher's avatar
Mosher committed
499
     *
500 501
     * @memberof AppDataUploadView
     */
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    public async getChartAllCodeList() {
        let codeListMap: Map<string, any> = new Map();
        if (Object.values(this.importDataModel).length > 0) {
            await Object.values(this.importDataModel).forEach(async (singleDataModel: any) => {
                if (singleDataModel.codelist) {
                    let tempCodeListMap: Map<any, any> = new Map();
                    let res: any = await this.getCodeList(singleDataModel.codelist);
                    if (res && res.length > 0) {
                        res.forEach((codeListItem: any) => {
                            tempCodeListMap.set(codeListItem.value, codeListItem.text);
                        });
                    }
                    codeListMap.set(singleDataModel.codelist.tag, tempCodeListMap);
                }
            });
Mosher's avatar
Mosher committed
517
        }
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        return codeListMap;
    }

    /**
     * 获取代码表
     *
     * @returns {Promise<any>}
     * @memberof AppDataUploadView
     */
    public getCodeList(codeListObject: any): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            if (codeListObject.tag && Object.is(codeListObject.type, "STATIC")) {
                const codelist = this.$store.getters.getCodeList(codeListObject.tag);
                if (codelist) {
                    resolve([...JSON.parse(JSON.stringify(codelist.items))]);
                } else {
                    console.log(`----${codeListObject.tag}----${this.$t("app.commonWords.codeNotExist") as string}`);
                }
            } else if (codeListObject.tag && Object.is(codeListObject.type, "DYNAMIC")) {
                this.codeListService
                    .getItems(codeListObject.tag)
                    .then((res: any) => {
                        resolve(res);
                    })
                    .catch((error: any) => {
                        console.log(
                            `----${codeListObject.tag}----${this.$t("app.commonWords.codeNotExist") as string}`
                        );
                    });
547
            }
Mosher's avatar
Mosher committed
548
        });
549 550 551
    }

    /**
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
     * 转化数据
     *
     * @memberof AppDataUploadView
     */
    public transformData(data: Array<any>, result: Array<any>) {
        data.forEach((item: any) => {
            let curObject: any = {};
            Object.keys(item).forEach((ele: any) => {
                // todo XLSX读取时间为国际时间(东8区)+8H转为标准时间
                if (item[ele] instanceof Date) {
                    const tempDate: Date = item[ele];
                    item[ele] = moment(tempDate)
                        .add(8, "h")
                        .format("YYYY-MM-DD HH:mm:ss");
                }
                if (this.allFieldMap.get(ele).codelist) {
                    let codelistTag: string = this.allFieldMap.get(ele).codelist.tag;
                    let codelistIsNumber: boolean = this.allFieldMap.get(ele).codelist.isnumber;
                    let curCodeList: any = this.transCodeList(codelistTag, codelistIsNumber, true);
                    Object.defineProperty(curObject, this.allFieldMap.get(ele).name, {
                        value: curCodeList.get(item[ele]),
                        writable: true,
                        enumerable: true,
                        configurable: true,
                    });
                } else {
                    Object.defineProperty(curObject, this.allFieldMap.get(ele).name, {
                        value: item[ele],
                        writable: true,
                        enumerable: true,
                        configurable: true,
                    });
                }
            });
            result.push(curObject);
        });
588 589 590
    }

    /**
591
     * 翻译代码表
Mosher's avatar
Mosher committed
592
     *
593 594
     * @memberof AppDataUploadView
     */
595 596 597 598 599 600 601 602 603
    public transCodeList(codeListTag: string, codelistIsNumber: boolean, isTransform: boolean) {
        let curCodeList: any = this.allCodeList.get(codeListTag);
        if (isTransform) {
            let tempCodelist: Map<string, string> = new Map();
            curCodeList.forEach((item: string, key: string) => {
                let value: any = codelistIsNumber ? Number(key) : key;
                tempCodelist.set(item, value);
            });
            curCodeList = tempCodelist;
604
        }
605
        return curCodeList;
606 607 608 609
    }
}
</script>

610 611
<style lang="scss">
@import "./app-data-upload.scss";
612
</style>