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

<script>
import { addTrainingRulesList } from '@/api/management/operation';
import { OperationList } from '@/scripts/OperationConfig';
import { getSkinCodeList } from '@/api/management/mapskin';

export default {
	name: 'AddBatch',
	data() {
		return {
			loading: false,
			dialogVisible: false,
			formModel: {
				skinCode: ''
			},
			skinCodeList: [],
			isShow: false
		};
	},
	computed: {
		form() {
			this.type === 'ADD';
			const form = {
				labelWidth: '120px',
				items: [
					{ prop: 'skinCode', label: this.$t('lesson.skinType'), type: 'select', required: true, options: this.skinCodeList }
				]
			};
			return form;
		},
		rules() {
			const crules = {
				skinCode: [
					{ required: true, message: this.$t('rules.inputSkinType'), trigger: 'change' }
				]
			};
			return crules;
		},
		title() {
			return this.$t('lesson.generationOperation');
		}
	},
	mounted() {
		this.init();
	},
	methods: {
		init() {
			// 获取皮肤列表
			this.skinCodeList = [];
			getSkinCodeList().then(response => {
				this.skinCodeList = response.data.map(item => {
					const params = {};
					params.label = item.name;
					params.value = item.code;
					return params;
				});
			});
		},
		show(total) {
			if (total) {
				this.isShow = true;
			}

			this.loading = false;
			this.dialogVisible = true;
		},
		doSave() {
			const self = this;
			this.$refs.dataform.validateForm(() => {
				if (this.isShow) {
					this.$confirm(this.$t('lesson.wellClearOperate'), this.$t('global.tips'), {
						confirmButtonText: this.$t('global.confirm'),
						cancelButtonText: this.$t('global.cancel'),
						type: 'warning'
					}).then(() => {
						self.create();
					}).catch(() => { });
				} else {
					self.create();
				}
			});
		},
		create() {
			const self = this;
			this.loading = true;
			addTrainingRulesList(this.formModel.skinCode, OperationList[this.formModel.skinCode].list).then(response => {
				self.loading = false;
				self.$message.success(this.$t('lesson.batchCreateSuccess'));
				self.handleClose();
				self.$emit('reloadTable'); // 刷新列表
			}).catch(error => {
				self.loading = false;
				self.$message.error(`${this.$('error.batchCreateFailed')}:${error.message}`);
			});
		},
		handleClose() {
			this.formModel = {
				skinCode: ''
			};
			this.$refs.dataform.resetForm();
			this.isShow = false;
			this.dialogVisible = false;
		}
	}
};
</script>
