ImportBillDialog.vue 8.98 KB
<template>
  <d2-dialog class="import-bill-dialog"
             title="对账单导入"
             width="800px"
             :btn-ok-label="importing ? '导入中' : '确定'"
             :is-visible="importBillVisible"
             @closeDialog="handleClose"
             @confirmDialog="handleConfirm">
    <glsx-combi-form ref="importFormRef"
                     default-width="560px"
                     label-width="130px"
                     :form-data="formData"
                     :form-obj="form"
                     :form-ref="importChildRef"
                     :form-rules="formRules"
                     :is-block="isBlock">
      <template slot="fileHtml">
        <div class="import-file-box">
          <el-button class="select-file-btn"
                     size="small"
                     type="primary"
                     plain
                     :disabled="importing">
            选择文件
            <input :key="fileInputKey"
                   ref="fileInput"
                   class="file-input"
                   type="file"
                   :accept="fileRule.accept"
                   @change="handleFileChange" />
          </el-button>
          <el-button class="template-btn"
                     type="text"
                     :disabled="importing"
                     @click="handleDownloadTemplate">
            下载模板
          </el-button>
          <div v-if="form.fileName" class="file-name-box">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ form.fileName }}</span>
            <i v-if="!importing"
               class="el-icon-close file-remove"
               @click="removeFile">
            </i>
          </div>
          <div class="file-tip">
            支持 xls、xlsx,文件不超过10M,最多上传1个。
          </div>
          <div v-if="importing || progress > 0" class="progress-text">
            导入进度:{{ progress }}%
          </div>
          <div v-if="showImportResult" class="import-result">
            <span class="result-label">操作结果:</span>
            <span>成功记录</span>
            <span class="success-num">{{ succNum }}</span>
            <span>失败记录</span>
            <span class="fail-num">{{ failNum }}</span>
          </div>
          <div v-if="failUrl" class="fail-file">
            导入失败,
            <el-button type="text" @click="handleDownloadFailFile">
              下载失败文件
            </el-button>
          </div>
        </div>
      </template>
    </glsx-combi-form>
  </d2-dialog>
</template>

<script>
import { getImportExcelProcess, importReconciliationBill } from "@api/accountManage";
import { mapActions, mapState } from "vuex";
import { downLoadFile } from "@/common/util";
import { readFileAsDataURL } from "@/libs/file";
import { startPolling } from "@/libs/interval";
import {
	buildImportBillFormData,
	buildImportBillPayload,
	buildImportTemplateDownloadTask,
	getImportPollStatus,
	getImportUuid,
	IMPORT_BILL_FILE_RULE,
	normalizeImportPollResult,
} from "../accountStateManage/importBill";

export default {
	name: "ImportBillDialog",
	props: {
		importBillVisible: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			isBlock: true,
			importChildRef: "importChildRef",
			fileRule: IMPORT_BILL_FILE_RULE,
			fileInputKey: Date.now(),
			form: {
				billType: "1",
				fileName: "",
				file: null,
			},
			formData: buildImportBillFormData(),
			formRules: {
				billType: [{ required: true, message: "请选择对账单类型", trigger: "change" }],
				fileName: [{ required: true, message: "请选择需要导入的对账单文件", trigger: "change" }],
			},
			importing: false,
			importCompleted: false,
			polling: null,
			progress: 0,
			succNum: 0,
			failNum: 0,
			failUrl: "",
		};
	},
	beforeDestroy() {
		this.stopPolling();
	},
	computed: {
		...mapState({
			dowloadList: state => state.d2admin.user.dowloadList,
		}),
		showImportResult() {
			return this.importCompleted || this.succNum > 0 || this.failNum > 0;
		},
	},
	methods: {
		...mapActions("d2admin/user", ["actionSetDownloadList"]),
		handleClose() {
			if (this.importing) {
				this.$message.warning("正在导入中,请稍后");
				return;
			}
			this.stopPolling();
			this.$emit("dialogClose");
		},
		handleFileChange(event) {
			const file = event.target.files && event.target.files[0];
			this.resetFileInput();
			if (!file || !this.validateFile(file)) {
				return;
			}
			this.resetImportStatus();
			this.form.file = file;
			this.form.fileName = file.name;
			this.validateField("fileName");
		},
		removeFile() {
			this.form.file = null;
			this.form.fileName = "";
			this.resetFileInput();
			this.resetImportStatus();
			this.validateField("fileName");
		},
		validateFile(file) {
			const fileName = file.name.toLowerCase();
			const validType = this.fileRule.extensions.some(ext => fileName.endsWith(ext));
			if (!validType) {
				this.$message.error("仅支持上传 xls、xlsx 文件");
				return false;
			}

			if (file.size / 1024 / 1024 > this.fileRule.maxSizeMb) {
				this.$message.error(`文件大小不能超过${this.fileRule.maxSizeMb}M`);
				return false;
			}
			return true;
		},
		handleConfirm() {
			if (this.importing) {
				return;
			}
			if (this.importCompleted) {
				this.$emit("handleConfirm");
				return;
			}
			this.$refs.importFormRef.$refs[this.importChildRef].validate(async (valid) => {
				if (!valid) {
					return;
				}
				await this.submitImport();
			});
		},
		handleDownloadTemplate() {
			if (!this.form.billType) {
				this.$message.warning("请先选择对账单类型");
				return;
			}
			const list = [
				...this.dowloadList,
				buildImportTemplateDownloadTask(this.form.billType),
			];
			this.actionSetDownloadList({ list, type: "dowloadList" });
		},
		async submitImport() {
			try {
				this.importing = true;
				this.importCompleted = false;
				this.failUrl = "";
				this.progress = 0;
				this.succNum = 0;
				this.failNum = 0;
				// 直接转 base64 后提交给导入接口。
				const event = await readFileAsDataURL(this.form.file);
				const base64 = event?.target?.result?.split(",")?.[1] || "";
				const payload = buildImportBillPayload({
					billType: this.form.billType,
					fileName: this.form.fileName,
					base64,
				});
				const result = await importReconciliationBill(payload);
				const uuid = getImportUuid(result);
				if (!uuid) {
					this.$message.error("导入任务创建失败");
					this.importing = false;
					return;
				}
				this.startImportPolling(uuid);
			} catch (error) {
				this.importing = false;
			}
		},
		startImportPolling(uuid) {
			this.stopPolling();
			const requestFn = () => getImportExcelProcess({ fileUuidList: [uuid] });
			const stopCondition = (result) => {
				// 查询结果可能是数组或对象,先统一格式再判断进度。
				const pollResult = normalizeImportPollResult(result);
				this.progress = pollResult.progress || 0;
				this.succNum = Number(pollResult.succNum) || 0;
				this.failNum = Number(pollResult.failNum) || 0;
				const status = getImportPollStatus(pollResult);
				if (status === "success") {
					this.importing = false;
					this.importCompleted = true;
					this.$message.success("导入成功");
					return true;
				}
				if (status === "failed") {
					this.importing = false;
					this.importCompleted = true;
					this.failUrl = pollResult.url || "";
					this.$message.error("导入失败,请查看失败文件");
					return true;
				}
				return false;
			};
			this.polling = startPolling(requestFn, 1000, stopCondition);
		},
		stopPolling() {
			if (this.polling) {
				this.polling();
				this.polling = null;
			}
		},
		resetFileInput() {
			this.fileInputKey = Date.now();
		},
		resetImportStatus() {
			this.failUrl = "";
			this.progress = 0;
			this.importCompleted = false;
			this.succNum = 0;
			this.failNum = 0;
		},
		validateField(field) {
			this.$nextTick(() => {
				this.$refs.importFormRef?.$refs?.[this.importChildRef]?.validateField(field);
			});
		},
		handleDownloadFailFile() {
			if (this.failUrl) {
				downLoadFile(this.failUrl);
			}
		},
	},
};
</script>

<style scoped>
.import-bill-dialog .import-file-box {
	line-height: 1;
}

.select-file-btn {
	position: relative;
	overflow: hidden;
}

.template-btn {
	margin-left: 10px;
	padding: 0;
}

.file-input {
	position: absolute;
	top: 0;
	right: 0;
	width: 100%;
	height: 100%;
	opacity: 0;
	cursor: pointer;
}

.file-name-box {
	display: inline-flex;
	align-items: center;
	max-width: 560px;
	margin-left: 10px;
	color: #606266;
	vertical-align: middle;
}

.file-name {
	max-width: 240px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	margin: 0 6px;
}

.file-remove {
	cursor: pointer;
}

.file-tip,
.progress-text,
.import-result,
.fail-file {
	margin-top: 10px;
	color: #909399;
	line-height: 18px;
}

.import-result {
	display: flex;
	align-items: center;
	gap: 10px;
	color: #606266;
}

.result-label {
	margin-right: 2px;
}

.success-num {
	color: #19be6b;
}

.fail-num {
	color: #f56c6c;
}

.fail-file {
	color: #f56c6c;
}
</style>