<template>
  <el-dialog v-dialogDrag :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" center :close-on-click-modal="false">
    <data-form ref="dataform" :form="form" :form-model="formModel" :rules="rules" />
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSave">{{ $t('global.confirm') }}</el-button>
      <el-button @click="dialogVisible = false">{{ $t('global.cancel') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { updateExam } from '@/api/management/userexam';

export default {
	name: 'PublishExamEdit',
	props: {
		type: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			dialogVisible: false,
			formModel: {
				id: '',
				userName: '',
				score: '',
				examName: '',
				result: ''
			}
		};
	},
	computed: {
		form() {
			const form = {
				labelWidth: '160px',
				items: [
					{ prop: 'userName', label: this.$t('system.userName'), type: 'text', required: false, disabled: true },
					{ prop: 'examName', label: this.$t('system.examName'), type: 'text', required: true, disabled: true },
					{ prop: 'score', label: this.$t('system.examScore'), type: 'text', required: true },
					{ prop: 'result', label: this.$t('system.examResult'), type: 'select', required: true, options: this.$ConstSelect.examResultList }
				]
			};
			return form;
		},
		rules() {
			const crules = {
				score: [
					{ required: true, message: this.$t('rules.pleaseInputName'), trigger: 'blur' }
				],
				result: [
					{ required: true, message: this.$t('rules.pleaseSelectStatus'), trigger: 'change' }
				]
			};
			return crules;
		},
		title() {
			return this.$t('system.editExamDetail');
		}
	},
	methods: {
		show(data) {
			this.dialogVisible = true;
			this.formModel = {
				id: data.id,
				userName: data.userName,
				score: data.score,
				examName: data.examName,
				result: data.result
			};
		},
		doSave() {
			const self = this;
			this.$refs.dataform.validateForm(() => {
				self.update();
			});
		},
		update() {
			const self = this;
			updateExam(this.formModel).then(response => {
				self.$message.success(this.$t('system.updateSuccess'));
				self.handleClose();
				self.$emit('reloadTable');
			}).catch(error => {
				self.$message.error(`${this.$t('error.updateFailed')}: ${error.message}`);
			});
		},
		handleClose(done) {
			this.formModel = {
				id: '',
				userName: '',
				score: '',
				examName: '',
				result: ''
			};
			if (done) {
				done();
			} else {
				this.dialogVisible = false;
			}
		}
	}
};
</script>
