<template>
	<span>
		<el-button link type="primary" :disabled="!row.id" @click="open">
			附件（{{ fileCount }}）
		</el-button>
		<el-dialog
			v-model="visible"
			:title="`${row.number || ''} 产出附件`"
			width="620px"
			append-to-body
			destroy-on-close
		>
			<sc-upload-filed
				v-model="fileIds"
				:file_="sourceFiles"
				:disabled="disabled"
				:multiple="true"
				tip="支持文件、图片和视频，可一次选择多个文件"
				@uploading-change="uploading = $event"
			>
				<el-button v-if="!disabled" type="primary">上传文件</el-button>
			</sc-upload-filed>
			<template #footer>
				<el-button @click="visible = false">关闭</el-button>
				<el-button v-if="!disabled" type="primary" :loading="saving" :disabled="uploading" @click="save">保存</el-button>
			</template>
		</el-dialog>
	</span>
</template>

<script>
export default {
	name: "OutputMaterialFiles",
	props: {
		row: { type: Object, required: true },
		disabled: { type: Boolean, default: false },
	},
	data() {
		return {
			visible: false,
			saving: false,
			uploading: false,
			fileIds: [],
			sourceFiles: [],
		};
	},
	computed: {
		fileCount() {
			return (this.row.files_ || []).length;
		},
	},
	methods: {
		open() {
			this.sourceFiles = [...(this.row.files_ || [])];
			this.fileIds = this.sourceFiles.map((file) => file.id);
			this.uploading = false;
			this.visible = true;
		},
		async save() {
			if (this.uploading) {
				this.$message.warning("请等待文件上传完成");
				return;
			}
			this.saving = true;
			try {
				const result = await this.$API.wpm.mlogbw.files.req(this.row.id, { files: this.fileIds });
				this.row.files = result.files;
				this.row.files_ = result.files_;
				this.visible = false;
				this.$message.success("附件已保存");
			} finally {
				this.saving = false;
			}
		},
	},
};
</script>
