<template>
  <el-dialog v-dialogDrag :title="operation.title" :visible.sync="dialogShow" width="500px" :before-close="close">
    <el-form ref="form" :model="operateModel" label-width="auto" :rules="rules" size="mini" label-position="right" class="dialog-form">
      <el-form-item :label="this.$t('lesson.skinType') + ':'" prop="skinCode">
        <el-select v-model="operateModel.skinCode" disabled="true" @change="skinCodeChoose">
          <el-option
            v-for="option in skinCodeList"
            :key="option.code"
            :label="option.name"
            :value="option.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="this.$t('lesson.productType')" prop="prdCode">
        <el-select v-model="operateModel.prdCode" @change="prdChange">
          <el-option
            v-for="option in productList"
            :key="option.code"
            :label="option.name"
            :value="option.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="this.$t('lesson.trainingType') + ':'" prop="type">
        <el-select v-model="operateModel.type" @change="typeChange">
          <el-option
            v-for="option in trainingTypeLists"
            :key="option.code"
            :label="option.name"
            :value="option.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="this.$t('lesson.operationType') + ':'" prop="operateType">
        <el-select v-model="operateModel.operateType" multiple>
          <el-option
            v-for="option in trainingTypeMap[operateModel.type]"
            :key="option.code"
            :label="option.name"
            :value="option.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isUpdate" :label="this.$t('lesson.minTime')" prop="minDuration">
        <el-input-number v-model="operateModel.minDuration" :min="0" :max="10000" />s
      </el-form-item>
      <el-form-item v-if="isUpdate" :label="this.$t('lesson.maxTime')" prop="maxDuration">
        <el-input-number v-model="operateModel.maxDuration" :min="0" :max="10000" />s
      </el-form-item>
      <el-form-item v-if="isUpdate" :label="this.$t('lesson.trainingDescription')" prop="remarks">
        <el-input v-model="operateModel.remarks" type="textarea" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{$t('global.cancel')}}</el-button>
      <el-button type="primary" :loading="loading" @click="handleDeal">{{$t('global.confirm')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addAutoTraining, updateAutoTraining, deleteAutoTraining } from '@/api/jmap/training';
import { getOperateTrainingList } from '@/api/management/operation';
import { getCommodityMapProduct } from '@/api/management/mapprd';

export default {
	name: 'TrainingAdd',
	props: {
		skinCodeList: {
			type: Array,
			required: true
		},
		trainingTypeList: {
			type: Array,
			required: true
		},
		trainingOperateTypeMap: {
			type: Object,
			required: true
		}
	},
	data() {
		var minDurations = (rule, value, callback) => {
			if (!value) {
				return callback(new Error(this.$t('rules.enterStandardTime')));
			}
			setTimeout(() => {
				if (!Number.isInteger(value)) {
					callback(new Error(this.$t('rules.enterNumericValue')));
				} else {
					callback();
				}
			}, 100);
		};
		var maxDurations = (rule, value, callback) => {
			if (!value) {
				return callback(new Error(this.$t('rules.enterStandardTime')));
			}
			setTimeout(() => {
				if (!Number.isInteger(value)) {
					callback(new Error(this.$t('rules.enterNumericValue')));
				} else {
					if (value < this.operateModel.minDuration) {
						callback(new Error(this.$t('rules.greaterThanMinTime')));
					} else {
						callback();
					}
				}
			}, 100);
		};

		var checkOperateType = (rule, value, callback) => {
			if (value.length <= 0) {
				return callback(new Error(this.$t('rules.selectTrainingType')));
			} else if (this.operation.event == '02' && value.length !== 1) {
				return callback(new Error(this.$t('rules.selectOneTrainingType')));
			} else {
				callback();
			}
		};

		// var checkRemarks = (rule, value, callback) => {
		// 	if (this.operation.event == '02' && !value) {
		// 		return callback(new Error('请输入实训描述'));
		// 	}
		// 	callback();
		// };

		return {
			dialogShow: false,
			productTypesList: [],
			trainTypesList: [],
			productList: [],
			checkList: [],
			operateModel: {
				name: '',
				type: '',
				skinCode: this.$route.params.skinCode,
				prdCode: '',
				operateType: [],
				maxDuration: 0,
				minDuration: 0,
				remarks: ''
			},
			loading: false,
			trainingTypeLists: [],
			trainingTypeMap: {},
			operation: {
				event: '',
				title: ''
			},
			rules: {
				skinCode: [
					{ required: true, message: this.$t('rules.pleaseEnterMapName'), trigger: 'change' }
				],
				prdCode: [
					{ required: true, message: this.$t('rules.enterProductType'), trigger: 'change' }
				],
				type: [
					{ required: true, message: this.$t('rules.inputTrainingType'), trigger: 'change' }
				],
				operateType: [
					{ required: true, validator: checkOperateType, trigger: 'change' }
				],
				minDuration: [
					{ required: true, validator: minDurations, trigger: 'blur' }
				],
				maxDuration: [
					{ required: true, validator: maxDurations, trigger: 'blur' }
				]
				// remarks: [
				//     { required: true, validator: checkRemarks, trigger: 'blur' }
				// ]
			}
		};
	},
	computed: {
		isUpdate() {
			return this.operation.event == '02';
		}
	},
    mounted() {
        this.skinCodeChoose(this.$route.params.skinCode);
    },
	methods: {
		show(data) {
			this.operation = {
				event: data.event,
				title: data.title
			};
			this.dialogShow = true;
		},
		close() {
			this.dialogShow = false;
			this.loading = false;
		},
		skinCodeChoose(skinCode) {
			this.operateModel.prdCode = '';
			this.productList = [];
			if (skinCode) {
				getCommodityMapProduct(skinCode).then((response) => {
					this.productList = response.data;
					this.productList = this.productList.filter(elem => { return elem.prdType != '03'; });
				});
			}
		},
		async prdChange(prdCode) {
			this.trainingTypeMap = {};
			this.operateModel.operateType = [];

			const skinCodeObj = this.skinCodeList.find(elem => { return elem.code === this.operateModel.skinCode; }) || {};
			const prdTypeObj = this.productList.find(elem => { return elem.code === prdCode; }) || {};
			const res = await getOperateTrainingList({ skinCode: skinCodeObj.code, productType: prdTypeObj.prdType });
			if (res && res.code == 200) {
				this.trainingTypeLists = res.data;
				this.trainingTypeList.forEach(elem => {
					this.trainingTypeLists.forEach(item => {
						if (item.id == elem.code) {
							item.name = elem.name;
							item.code = elem.code;
						}

						this.trainingOperateTypeMap[item.id].forEach(i => {
							item.children.forEach(v => {
								if (i.code == v.id) {
									v.name = i.name;
									v.code = i.code;
								}
							});
						});
					});
				});

				this.trainingTypeLists.forEach(item => {
					item.children.forEach(v => {
						if (!this.trainingTypeMap[item.id]) {
							this.trainingTypeMap[item.id] = [];
						}

						this.trainingTypeMap[item.id].push({
							name: v.name,
							code: v.code
						});
					});
				});
			}
		},
		typeChange(type) {
			this.operateModel.operateType = [];
			this.trainTypesList = this.trainingOperateTypeMap[type] || [];
		},
		// 取消
		handleClose() {
			this.dialogShow = false;
		},
		// 确定
		handleDeal() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					this.loading = true;
					if (this.operation.event == '01') { // add
						// 创建实训
						const data = {
							skinCode: this.operateModel.skinCode,
							name: this.operateModel.name,
							prdCode: this.operateModel.prdCode,
							trainingType: this.operateModel.type,
							operateType: this.operateModel.operateType
						};

						addAutoTraining(data).then(response => {
							this.$message.success(this.$t('tip.automaticGenerationTrainingSuccess'));
							this.$emit('refresh');
							this.close();
						}).catch(() => {
							this.$messageBox(this.$t('tip.automaticGenerationTrainingFailure'));
							this.loading = false;
						});
					} else if (this.operation.event == '02') { // edit
						// 更新实训
						const data = {
							skinCode: this.operateModel.skinCode,
							name: this.operateModel.name,
							prdCode: this.operateModel.prdCode,
							trainingType: this.operateModel.type,
							operateType: this.operateModel.operateType,
							remarks: this.operateModel.remarks,
							minDuration: this.operateModel.minDuration,
							maxDuration: this.operateModel.maxDuration
						};

						updateAutoTraining(data).then(response => {
							this.$message.success(this.$t('tip.updateAutomaticGenerationTrainingSuccess'));
							this.$emit('refresh');
							this.close();
						}).catch(() => {
							this.$messageBox(this.$t('tip.updateAutomaticGenerationTrainingFailure'));
							this.loading = false;
						});
					} else if (this.operation.event == '03') { // delete
						// 删除实训
						const data = {
							skinCode: this.operateModel.skinCode,
							name: this.operateModel.name,
							prdCode: this.operateModel.prdCode,
							trainingType: `${this.operateModel.type}`,
							operateType: `${this.operateModel.operateType.join(',')}`
						};

						deleteAutoTraining(data).then(response => {
							this.$message.success(this.$t('tip.deleteAutomaticGenerationTrainingSuccess'));
							this.$emit('refresh');
							this.close();
						}).catch(() => {
							this.$messageBox(this.$t('tip.deleteAutomaticGenerationTrainingFailure'));
							this.loading = false;
						});
					}
				}
			});
		}
	}
};

</script>
<style scoped>
    .el-checkbox {
        margin-left: 20px;
    }
    .dialog-form {
        position: relative;
        left: 15px;
    }
</style>
