<template>
  <el-dialog v-dialogDrag :title="title" :visible.sync="dialogVisible" width="30%" :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 { postTrainingRulesData, putTrainingRulesData, getPlaceholderList } from '@/api/management/operation';
import { listPublishMap } from '@/api/jmap/map';

export default {
    name: 'TrainingEdit',
    props: {
        type: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            loading: false,
            dialogVisible: false,
            formModel: {
                trainingName: '',
                trainingType: '',
                operateType: '',
                mapId: '',
                minDuration: '',
                maxDuration: '',
                trainingRemark: '',
                productTypes: []
            },
            mapIdList: [],
            trainingTypeList: [],
            trainingOperateTypeMap: {},
            placeholderList: []
        };
    },
    computed: {
        form() {
            const isAdd = this.type === 'ADD';
            const form = {
                labelWidth: '120px',
                items: [
                    { prop: 'mapId', label: this.$t('lesson.mapName'), type: 'select', required: true, options: this.mapIdList, disabled: true },
                    { prop: 'trainingType', label: this.$t('lesson.trainingType'), type: 'select', required: true, options: this.trainingTypeList, disabled: !isAdd, change: true, onChange: this.changeList },
                    { prop: 'operateType', label: this.$t('lesson.operationType'), type: 'select', required: true, options: this.trainingOperateTypeMap[this.formModel.trainingType], disabled: !isAdd },
                    { label: '', type: 'button', options: this.placeholderList, style: 'margin-bottom: 0; margin-top: -10px;', typeBtn: 'info', click: this.addTrainName },
                    { prop: 'trainingName', label: this.$t('lesson.trainingName'), type: 'text', required: true, rightWidth: true, tooltip: true, info: this.$t('lesson.tipNamePlaceholderInfo') },
                    { prop: 'minDuration', label: this.$t('lesson.minDuration'), type: 'number', required: true, min:1},
                    { prop: 'maxDuration', label: this.$t('lesson.maxDuration'), type: 'number', required: true, min:1},
                    { label: '', type: 'button', options: this.placeholderList, style: 'margin-bottom: 0; margin-top: -10px;', typeBtn: 'info', click: this.addTrainRemark },
                    { prop: 'trainingRemark', label: this.$t('lesson.trainingRemark'), type: 'textarea', required: true, tooltip: true, info: this.$t('lesson.tipExplainPlaceholderInfo') }
                ]
            };
            return form;
        },
        rules() {
            const crules = {
                trainingName: [
                    { required: true, message: this.$t('rules.inputTrainingName'), trigger: 'blur' }
                ],
                trainingType: [
                    { required: true, message: this.$t('rules.inputTrainingType'), trigger: 'change' }
                ],
                operateType: [
                    { required: true, message: this.$t('rules.inputOperationType'), trigger: 'change' }
                ],
                mapId: [
                    { required: true, message: this.$t('rules.selectMapName'), trigger: 'change' }
                ],
                minDuration: [
                    { required: true, message: this.$t('rules.inputMinDuration'), trigger: 'blur' }
                ],
                maxDuration: [
                    { required: true, message: this.$t('rules.inputMaxDuration'), trigger: 'blur' }
                ],
                trainingRemark: [
                    { required: true, max: 500, message: this.$t('rules.inputTrainingRemark'), trigger: 'blur' }
                ]
            };
            return crules;
        },
        title() {
            if (this.type === 'ADD') {
                return this.$t('lesson.createOperateRule');
            } else {
                return this.$t('lesson.editOperateRule');
            }
        }
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            // 获取地图列表
            this.mapIdList = [];
            listPublishMap().then(response => {
                this.mapIdList = response.data.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.id;
                    return params;
                });
            });

            // 获取实训类型
            this.trainingTypeList = [];
            this.$Dictionary.trainingType().then(list => {
                this.trainingTypeList = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                });
            });
            // 获取实训操作类型
            this.trainingOperateTypeMap = {};
            this.$Dictionary.stationControl().then(list => {
                this.trainingOperateTypeMap['01'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 控制权实训
            });
            this.$Dictionary.signalOperation().then(list => {
                this.trainingOperateTypeMap['02'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 信号机实训
            });
            this.$Dictionary.switchOperation().then(list => {
                this.trainingOperateTypeMap['03'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 道岔实训
            });
            this.$Dictionary.sectionOperation().then(list => {
                this.trainingOperateTypeMap['04'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 区段实训
            });
            this.$Dictionary.stationStandOperation().then(list => {
                this.trainingOperateTypeMap['05'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 站台实训
            });
            this.$Dictionary.trainPlanOperation().then(list => {
                this.trainingOperateTypeMap['06'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 行车计划实训
            });
            this.$Dictionary.trainOperation().then(list => {
                this.trainingOperateTypeMap['07'] = list.map(item => {
                    const params = {};
                    params.label = item.name;
                    params.value = item.code;
                    return params;
                }); // 列车实训
            });

        },
        async show(data) {
            this.loading = false;
            this.dialogVisible = true;
            if (data && data.id) {
                // 获取操作占位列表
                const res = await getPlaceholderList({ trainingType: data.trainingType });
                this.placeholderList = res.data;
                this.formModel = {
                    id: data.id,
                    trainingName: this.repliceName(data.trainingName, this.placeholderList),
                    trainingType: data.trainingType,
                    operateType: data.operateType,
                    productTypes: data.productTypes,
                    mapId: data.mapId,
                    minDuration: data.minDuration,
                    maxDuration: data.maxDuration,
                    trainingRemark: this.repliceName(data.trainingRemark, this.placeholderList)
                };
            } else {
                this.formModel = {
                    mapId: this.$route.query.mapId
                };
            }
        },
        repliceName(fieldValue, enumList) {
            if (enumList && enumList.length > 0) {
                for (let i = 0; i < enumList.length; i++) {
                    if (fieldValue.includes(`{${enumList[i].id}}`)) {
                        fieldValue = fieldValue.replace(`{${enumList[i].id}}`, `{${enumList[i].name}}`);
                    }
                }
                return fieldValue;
            }
        },
        changeList(val) {
            // 获取操作占位列表
            getPlaceholderList({ trainingType: val}).then(res => {
                this.placeholderList = res.data;
            });
        },
        addTrainName(val) {
            this.formModel.trainingName = `${this.formModel.trainingName}{${val.name}}`;
        },
        addTrainRemark(val) {
            this.formModel.trainingRemark = `${this.formModel.trainingRemark}{${val.name}}`;
        },
        doSave() {
            const self = this;
            this.$refs.dataform.validateForm(() => {
                if (self.type === 'ADD') {
                    self.create();
                } else {
                    self.update();
                }
            });
        },
        create() {
            const self = this;
            this.placeholderList.forEach(item => {
                if (this.formModel.trainingName.includes(`{${item.name}}`)) {
                    const name = this.formModel.trainingName.replace(`{${item.name}}`, `{${item.id}}`);
                    this.formModel.trainingName = name;
                }
                if (this.formModel.trainingRemark.includes(`{${item.name}}`)) {
                    const remark = this.formModel.trainingRemark.replace(`{${item.name}}`, `{${item.id}}`);
                    this.formModel.trainingRemark = remark;
                }
            });

            this.loading = true;
            postTrainingRulesData(this.formModel).then(response => {
                self.loading = false;
                self.$message.success(this.$t('lesson.createOperateSuccess'));
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                self.loading = false;
                self.$message.error(`${this.$t('error.createOperateRuleFailed')}:${error.message}`);
            });
        },
        update() {
            const self = this;
            this.placeholderList.forEach(item => {
                if (this.formModel.trainingName.includes(`{${item.name}}`)) {
                    const name = this.formModel.trainingName.replace(`{${item.name}}`, `{${item.id}}`);
                    this.formModel.trainingName = name;
                }
                if (this.formModel.trainingRemark.includes(`{${item.name}}`)) {
                    const remark = this.formModel.trainingRemark.replace(`{${item.name}}`, `{${item.id}}`);
                    this.formModel.trainingRemark = remark;
                }
            });

            this.loading = true;
            putTrainingRulesData(this.formModel).then(response => {
                self.loading = false;
                self.$message.success(this.$t('lesson.updateOperateSuccess'));
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                self.loading = false;
                self.$message.error(`${this.$t('error.updateOperateRuleFailed')}:${error.message}`);
            });
        },
        handleClose() {
            this.formModel = {
                trainingName: '',
                trainingType: '',
                operateType: '',
                mapId: '',
                minDuration: '',
                maxDuration: '',
                trainingRemark: ''
            };
            this.$refs.dataform.resetForm();
            this.dialogVisible = false;
        }
    }
};
</script>
