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

<script>
import { postOperateStepData, putOperateStepData, getPlaceholderList } from '@/api/management/operation';

export default {
    name: 'TrainingDetailEdit',
    props: {
        type: {
            type: String,
            required: true
        },
        dicId: {
            type: String,
            required: true
        },
        deviceList: {
            type: Array,
            default() {
                return [];
            }
        }
    },
    data() {
        return {
            dialogVisible: false,
            formModel: {
                operateCode: '',
                orderNum: '',
                deviceType: '',
                val: '',
                tip: ''
            },
            placeholderList: []
        };
    },
    computed: {
        form() {
            const isAdd = this.type === 'ADD';
            const form = {
                labelWidth: '120px',
                items: [
                    { prop: 'orderNum', label: this.$t('lesson.stepNo'), type: 'text', required: true, disabled: !isAdd },
                    { prop: 'operateCode', label: this.$t('lesson.operateCode'), type: 'text', required: true, disabled: !isAdd },
                    { prop: 'deviceType', label: this.$t('lesson.deviceType'), type: 'select', required: true, options: this.deviceList, disabled: !isAdd },
                    { prop: 'val', label: this.$t('lesson.stepReturn'), type: 'text', required: false, disabled: !isAdd },
                    { label: '', type: 'button', options: this.placeholderList, style: 'margin-bottom: 0; margin-top: -10px;', typeBtn: 'info', click: this.addTrainRemark },
                    { prop: 'tip', label: this.$t('lesson.stepTips'), type: 'textarea', required: true, tooltip: true, info: this.$t('lesson.tipExplainPlaceholderInfo') }
                ]
            };
            return form;
        },
        rules() {
            const crules = {
                operateCode: [
                    { required: true, message: this.$t('rules.inputOperateCode'), trigger: 'blur' }
                ],
                orderNum: [
                    { required: true, message: this.$t('rules.inputStepNo'), trigger: 'blur' }
                ],
                tip: [
                    { required: true, max: 500, message: this.$t('rules.inputStepTips'), trigger: 'blur' }
                ]
            };
            return crules;
        },
        title() {
            if (this.type === 'ADD') {
                return this.$t('lesson.createStepInfo');
            } else {
                return this.$t('lesson.editStepInfo');
            }
        }
    },
    methods: {
        async show(data) {
            this.dialogVisible = true;
            const res = await getPlaceholderList({ trainingType: this.$route.query.type, skinCode: this.$route.query.skinCode });
            this.placeholderList = res.data;
            if (data && data.operateCode) {
                // 获取操作占位列表
                this.formModel = {
                    operateCode: data.operateCode,
                    orderNum: data.orderNum,
                    deviceType: data.deviceType,
                    definitionId: data.definitionId,
                    val: data.val,
                    id: data.id,
                    tip: this.repliceName(data.tip, this.placeholderList)
                };
            }
        },
        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;
            }
        },
        addTrainRemark(val) {
            this.formModel.tip = `${this.formModel.tip}{${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.tip.includes(`{${item.name}}`)) {
                    const tip = this.formModel.tip.replace(`{${item.name}}`, `{${item.id}}`);
                    this.formModel.tip = tip;
                }
            });
            this.formModel.definitionId = this.$route.query.id;
            this.formModel.orderNum = Number(this.formModel.orderNum);
            postOperateStepData(this.formModel).then(response => {
                self.$message.success(this.$t('lesson.createOperateSuccess'));
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                self.$message.error(`${this.$t('error.createOperateStepFailed')}:${error.message}`);
            });
        },
        update() {
            const self = this;
            this.placeholderList.forEach(item => {
                if (this.formModel.tip.includes(`{${item.name}}`)) {
                    const tip = this.formModel.tip.replace(`{${item.name}}`, `{${item.id}}`);
                    this.formModel.tip = tip;
                }
            });
            this.formModel.orderNum = Number(this.formModel.orderNum);
            putOperateStepData(this.formModel).then(response => {
                self.$message.success(this.$t('lesson.updateOperateSuccess'));
                self.handleClose();
                self.$emit('reloadTable');
            }).catch(error => {
                self.$message.error(`${this.$t('error.updateOperateStepFailed')}:${error.message}`);
            });
        },
        handleClose() {
            this.formModel = {
                operateCode: '',
                orderNum: '',
                deviceType: '',
                val: '',
                tip: ''
            };
            this.$refs.dataform.resetForm();
            this.dialogVisible = false;
        }
    }
};
</script>
