app-data-upload.vue 17.0 KB
Newer Older
1
<template>
2 3 4 5 6
    <div
        class="app-data-upload-view"
        v-loading.fullscreen="isUploading"
        element-loading-background="rgba(57, 57, 57, 0.2)"
    >
7 8 9 10 11
        <input
            ref="inputUpLoad"
            type="file"
            style="display: none"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
12
            @change="importFile"
13 14
        />
        <div class="main-content">
15
            <div v-if="importDataArray.length === 0 && !isUploading && uploadProgress !== 100" class="upload-container" @click="handleUpLoad">
16
                <img class="icon-import" src="@/assets/img/icon-import.svg" />
17
                <span class="select-file-text">{{ $t("components.appDataUploadView.selectfile") }}</span>
18
            </div>
19 20 21 22 23 24 25 26 27
            <div class="data-info-container" v-if="importDataArray.length > 0 || isUploading || uploadProgress == 100">
                <el-progress
                    class="progress"
                    v-show="isUploading"
                    :text-inside="true"
                    :stroke-width="14"
                    :percentage="uploadProgress"
                ></el-progress>
                <span class="font-class">{{ promptInfo }}</span>
28
            </div>
29 30
        </div>
        <el-row class="button-container">
31
            <el-button type="primary" @click="handleCancel">{{ $t("components.appDataUploadView.cancel") }}</el-button>
32
            <el-button
33
                :disabled="importDataArray.length === 0"
34 35 36 37
                :loading="isUploading"
                type="primary"
                class="primary-button"
                @click="uploadServer"
38
                >{{ $t("components.appDataUploadView.uploadserver") }}</el-button
39
            >
40 41 42 43 44
        </el-row>
    </div>
</template>

<script lang="ts">
45 46 47 48 49 50
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";
51

52
@Component({})
53
export default class AppDataUploadView extends Vue {
54 55 56 57 58 59 60
    /**
     * 传入视图上下文
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    @Prop() protected viewdata!: string;
61

62 63 64 65 66 67 68
    /**
     * 传入视图参数
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    @Prop() protected viewparam!: string;
69 70

    /**
71
     * 代码表服务对象
72
     *
73
     * @type {CodeListService}
74 75 76
     * @memberof AppDataUploadView
     */

77
    public codeListService: CodeListService = new CodeListService({ $store: this.$store });
78

79 80 81 82 83 84 85 86
    /**
     * 实体服务对象
     *
     * @protected
     * @type {EntityService}
     * @memberof AppDataUploadView
     */
    protected entityService: any;
87 88

    /**
89
     * 视图参数
90
     *
91
     * @type {*}
92 93
     * @memberof AppDataUploadView
     */
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    protected viewparams: any = {};

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

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

    /**
113 114 115 116 117 118 119 120 121
     * 导入标识
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    protected importId: string = "";

    /**
     * 是否已有导入数据
122 123 124 125
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
126
    public hasImported: boolean = false;
127 128

    /**
129
     * 导入数据识别项属性
130
     *
131
     * @type {string}
132 133
     * @memberof AppDataUploadView
     */
134
    public importUniqueItem: string = "";
135 136

    /**
137 138 139 140 141 142 143 144 145
     * 提示信息
     *
     * @type {string}
     * @memberof AppDataUploadView
     */
    public promptInfo: string = "";

    /**
     * 导入状态
146 147 148 149
     *
     * @type {boolean}
     * @memberof AppDataUploadView
     */
150
    public isUploading: boolean = false;
151 152

    /**
153
     * 导入成功数据
154
     *
155 156 157 158 159 160 161 162 163
     * @type {string}
     * @memberof AppDataUploadView
     */
    public importSuccessData: Array<any> = [];

    /**
     * 导入失败数据
     *
     * @type {string}
164 165
     * @memberof AppDataUploadView
     */
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
    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;
207 208 209 210 211 212 213 214

    /**
     * 视图参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppDataUploadView
     */
215
    @Watch("viewparam", { immediate: true, deep: true })
216
    onParamData(newVal: any, oldVal: any) {
217
        if (newVal) {
218 219
            Object.assign(this.viewparams, JSON.parse(this.viewparam));
            this.initBasic();
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
    /**
     * 初始化基础数据
     *
     * @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());
        }
        //获取代码表值
        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;
                }
            }
266 267 268
        }
    }

269 270 271 272 273 274 275 276 277
    /**
     * 下载导入数据模板
     *
     * @memberof AppDataUploadView
     */
    public downloadTemp() {
        this.importExcel(this.viewparams.appDeLogicName + this.$t("components.appDataUploadView.datatemp"), []);
    }

278 279 280 281 282
    /**
     * 选择文件
     *
     * @memberof AppDataUploadView
     */
283
    public handleUpLoad() {
284
        this.importSuccessData = [];
285 286 287
        (this.$refs.inputUpLoad as any).click();
    }

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
    /**
     * 上传服务器
     *
     * @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;
        this.importDataArray = [];
        this.sliceUploadService(tempDataArray, 0);
    }

    /**
     * 数据切片上传
     *
     * @memberof AppDataUploadView
     */
    public sliceUploadService(dataArray: Array<any>, cnt: number) {
        if (cnt > dataArray.length) {
            this.isUploading = false;
            this.uploadProgress = 100;
315 316
            this.$Notice.success({ desc: this.$t("components.appDataUploadView.completed") as string });
            this.handleCancel();
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
            return;
        }
        let sliceArray: Array<any> = [];
        if (dataArray) {
            sliceArray = dataArray.slice(cnt, cnt + this.sliceUploadCnt);
        }
        try {
            this.entityService
                .ImportData(this.viewdata, { name: this.importId, importData: sliceArray })
                .then((res: any) => {
                    const result: any = res.data;
                    if (result && result.rst !== 0) {
                        this.promptInfo = this.$t("components.appDataUploadView.importfailed") as string;
                        this.isUploading = false;
                        return;
                    }
                    this.importSuccessData = result.data;
                    this.promptInfo = this.$t("components.appDataUploadView.completed") as string;
                    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) {
            this.isUploading = false;
            this.promptInfo = this.$t("components.appDataUploadView.importfailed") as string;
        }
    }

348
    /**
349
     * 取消
350 351 352
     *
     * @memberof AppDataUploadView
     */
353
    public handleCancel() {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        this.$emit("close", []);
    }

    /**
     * 导出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", //非必填
            });
        });
376 377 378
    }

    /**
379
     * 确认
380 381 382
     *
     * @memberof AppDataUploadView
     */
383 384 385 386 387 388 389 390 391 392
    public handleOK() {
        this.$emit("close", this.importSuccessData);
    }

    /**
     * 导入Excel
     *
     * @memberof AppDataUploadView
     */
    public importFile($event: any) {
393 394
        let obj = $event.target || $event.srcElement;
        if (!obj.files) {
395 396
            return;
        }
397 398 399 400 401 402 403 404 405 406 407 408 409
        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);
            this.promptInfo = `${this.$t('components.appDataUploadView.selectfilesucess')}, ${this.$t('components.appDataUploadView.totaldata')} ${this.importDataArray.length} ${this.$t('components.appDataUploadView.total')}`;
            (this.$refs.inputUpLoad as any).value = "";
        };
        reader.readAsBinaryString(f);
410 411 412
    }

    /**
413
     * 获取excel第一行的内容
414 415 416
     *
     * @memberof AppDataUploadView
     */
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    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;
432 433 434
    }

    /**
435
     * 增加对应字段空白内容
436 437 438
     *
     * @memberof AppDataUploadView
     */
439 440 441 442 443 444 445 446 447 448
    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;
                }
449
            }
450 451
        }
        return xlsxData;
452 453 454
    }

    /**
455
     * 获取图表所需代码表
456
     *
457 458
     * @memberof AppDataUploadView
     */
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    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);
                }
            });
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
        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}`
                        );
                    });
504
            }
505
        });
506 507 508
    }

    /**
509 510 511 512 513 514 515 516 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
     * 转化数据
     *
     * @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);
        });
545 546 547
    }

    /**
548
     * 翻译代码表
549
     *
550 551
     * @memberof AppDataUploadView
     */
552 553 554 555 556 557 558 559 560
    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;
561
        }
562
        return curCodeList;
563 564 565 566
    }
}
</script>

567 568 569
<style lang="less">
@import "./app-data-upload.less";
</style>