<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="handleClose">{{ $t('global.cancel') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { putUserTraining } from '@/api/jmap/training';
export default {
	name: 'UsersTrainingEdit',
	props: {
		type: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			dialogVisible: false,
			formModel: {
				id: '',
				lessonName: '',
				userName: '',
				trainingName: '',
				duration: ''
				// trainingCount: '',
			}
		};
	},
	computed: {
		form() {
			this.type === 'ADD';
			const form = {
				labelWidth: '100px',
				items: [
					{ prop: 'lessonName', label: this.$t('system.lessonName'), type: 'text', required: false, disabled: true },
					{ prop: 'trainingName', label: this.$t('system.trainingName'), type: 'text', required: true, disabled: true },
					{ prop: 'userName', label: this.$t('system.userName'), type: 'text', required: true, disabled: true },
					{ prop: 'duration', label: this.$t('system.trainingTime'), type: 'text', required: true, rightWidth: true, message: 's' }
				]
			};
			return form;
		},
		rules() {
			const crules = {
				duration: [
					{ required: true, message: this.$t('rules.timeInput'), trigger: 'blur' }
				]
			};
			return crules;
		},
		title() {
			return this.$t('system.editTrainingDetail');
		}
	},
	methods: {
		show(data) {
			this.dialogVisible = true;
			if (data && data.id) {
				this.formModel = {
					id: data.id,
					lessonName: data.lessonName,
					userName: data.userName,
					trainingName: data.trainingName,
					duration: data.duration
				};
			}
		},
		doSave() {
			const self = this;
			this.$refs.dataform.validateForm(() => {
				self.update();
			});
		},
		update() {
			const self = this;
			const param = {
				id: this.formModel.id,
				duration: this.formModel.duration
			};
			putUserTraining(param).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: '',
				lessonName: '',
				userName: '',
				trainingName: '',
				duration: ''
			};
			this.dialogVisible = false;
		}
	}
};
</script>
