<template>
  <div>
    <el-dialog :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>
    <add-training ref="addTraining" @selectTrain="selectTrain" />
  </div>
</template>

<script>
import { addUserTraining } from '@/api/jmap/training';
import { getPublishLessonList } from '@/api/jmap/lesson';
import { getDimUserList } from '@/api/management/user';
import AddTraining from './addTraining';

export default {
	name: 'UsersTrainingAdd',
	components: {
		AddTraining
	},
	props: {
		type: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			dialogVisible: false,
			formModel: {
				lessonId: '',
				trainingId: '',
				trainingName: '',
				userId: '',
				userName: '',
				duration: ''
			},
			LessonList: [],
			UserList: [],
			UserLoading: false
		};
	},
	computed: {
		form() {
			this.type === 'ADD';
			const form = {
				labelWidth: '150px',
				items: [
					{ prop: 'lessonId', label: this.$t('system.lessonName'), type: 'select', required: true, options: this.LessonList },
					{ prop: 'trainingName', label: this.$t('system.trainingName'), type: 'text', required: true, rightWidth: true, disabled: true, buttontip: this.$t('system.selectTraining'), buttonClick: this.buttonClick, placeholder: this.$t('rules.pleaseSelectTraining') },
					{ prop: 'userName', label: this.$t('system.userName'), type: 'complete', required: false, querySearchAsync: this.querySearchAsync, handleSelect: this.prdSelect, placeholder: this.$t('system.pleaseInputNames') },
					{ prop: 'duration', label: this.$t('system.trainingTime'), type: 'text', required: true, rightWidth: true, message: 's' }
				]
			};
			return form;
		},
		rules() {
			const crules = {
				lessonId: [
					{ required: true, message: this.$t('rules.pleaseInputLessonName'), trigger: 'change' }
				],
				trainingName: [
					{ required: true, message: this.$t('rules.pleaseSelectTraining'), trigger: 'change' }
				],
				userName: [
					{ required: true, message: this.$t('rules.userNameInput'), trigger: 'change' }
				],
				duration: [
					{ required: true, message: this.$t('rules.timeInput'), trigger: 'blur' }
				]
			};
			return crules;
		},
		title() {
			return this.$t('system.createUserTraining');
		}
	},
	mounted() {
		this.initLoadPage();
	},
	methods: {
		initLoadPage() {
			// 加载发布课程列表
			this.LessonList.length = 0;
			this.UserList.length = 0;
			getPublishLessonList().then(response => {
				const data = response.data;
				if (data && data.length) {
					data.forEach(elem => {
						this.LessonList.push({ value: elem.id, label: elem.name });
					});
				}
			});
		},
		// 搜索查询input
		async querySearchAsync(queryString, cb) {
			// 根据queryString 查询用户 并显示
			const results = [];
			if (queryString) {
				try {
					const params = {
						fuzzyParam: queryString
					};
					const res = await getDimUserList(params);
					const list = res.data;
					list.forEach(item => {
						const value = {
							id: item.id,
							value: `${item.nickname}(${item.name})${item.mobile}`
						};
						results.push(value);
					});
					cb(results);
				} catch (error) {
					console.error(error, '查询用户list');
					cb(results);
				}
			} else {
				cb(results);
			}
		},
		prdSelect(item) {
			this.formModel.userId = item.id;
		},
		selectTrain(data) {
			this.formModel.trainingId = data.id;
			this.formModel.trainingName = data.name;
		},
		buttonClick() {
			if (this.formModel.lessonId) {
				this.$refs.addTraining.show(this.formModel.lessonId);
			} else {
				this.$message.error('请先选择课程名称');
			}
		},
		show(data) {
			this.dialogVisible = true;
		},
		doSave() {
			const self = this;
			this.$refs.dataform.validateForm(() => {
				self.save();
			});
		},
		save() {
			const self = this;
			if (this.formModel.userId) {
				addUserTraining(this.formModel).then(response => {
					self.$message.success(this.$t('system.addSuccess'));
					self.handleClose();
					self.$emit('reloadTable');
				}).catch(error => {
					self.$message.error(this.$t('error.addFailed') + error.message);
				});
			} else {
				self.$message.error(this.$t('rules.chooseUser'));
			}
		},
		handleClose(done) {
			this.formModel = {
				lessonId: '',
				trainingId: '',
				trainingName: '',
				userId: '',
				userName: '',
				duration: ''
			};
			this.dialogVisible = false;
		}
	}
};
</script>
