<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" center>
        <data-form ref="dataform" :form="form" :formModel="formModel" :rules="rules"></data-form>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="doSave" v-loading="loading">确 定</el-button>
            <el-button @click="handleClose">取 消</el-button>
        </span>
    </el-dialog>
</template>

<script>
    import { create, checkDicCodeExist, getData, update } from '@/api/management/dictionary'
    import { postTrainingRulesData, putTrainingRulesData, getPlaceholderList } from '@/api/management/operation';
    import { validateCharCode } from '@/utils/validate'
    import { getSkinStyleList } from '@/api/management/mapskin';

    export default {
        name: 'TrainingEdit',
        props: {
            type: {
                type: String,
                required: true
            }
        },
        data() {
            return {
                loading: false,
                dialogVisible: false,
                formModel: {
                    trainingName: '',
                    trainingType: '',
                    operateType: '',
                    skinStyle: '',
                    minDuration: '',
                    maxDuration: '',
                    trainingRemark: '',
                    productTypes: [],
                },
                skinStyleList: [],
                trainingTypeList: [],
                trainingOperateTypeMap: {},
                placeholderList: [],
            }
        },
        computed: {
            form() {
                let isAdd = this.type === 'ADD'
                let form = {
                    labelWidth: '120px',
                    items: [
                        { prop: 'skinStyle', label: '皮肤类型', type: 'select', required: true, options: this.skinStyleList, disabled: !isAdd },
                        { prop: 'trainingType', label: '实训类型', type: 'select', required: true, options: this.trainingTypeList, disabled: !isAdd, change: true, onChange: this.changeList },
                        { prop: 'operateType', label: '操作类型', 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: '实训名称', type: 'text', required: true, rightWidth: true, tooltip: true, info: '选择占位符 ‘{}’ 不可删除，否则名称显示会有问题！' },
                        { prop: 'minDuration', label: '最佳用时', type: 'text', required: true },
                        { prop: 'maxDuration', label: '最大用时', type: 'text', required: true },
                        { label: '', type: 'button', options: this.placeholderList, style: 'margin-bottom: 0; margin-top: -10px;', typeBtn: 'info', click: this.addTrainRemark },
                        { prop: 'trainingRemark', label: '实训说明', type: 'textarea', required: true, tooltip: true, info: '选择占位符 ‘{}’ 不可删除，否则说明显示会有问题！' },
                    ]
                }
                return form
            },
            rules() {
                let crules = {
                    trainingName: [
                        { required: true, message: '请输入实训名称', trigger: 'blur' },
                    ],
                    trainingType: [
                        { required: true, message: '请输入实训类型', trigger: 'change' },
                    ],
                    operateType: [
                        { required: true, message: '请输入操作类型', trigger: 'change' }
                    ],
                    skinStyle: [
                        { required: true, message: '请选择皮肤类型', trigger: 'change' },
                    ],
                    minDuration: [
                        { required: true, message: '请输入最佳用时', trigger: 'blur' }
                    ],
                    maxDuration: [
                        { required: true, message: '请输入最大用时', trigger: 'blur' },
                    ],
                    trainingRemark: [
                        { required: true, max: 500, message: '请输入实训说明', trigger: 'blur' },
                    ],
                }
                return crules
            },
            title() {
                if (this.type === 'ADD') {
                    return '创建操作规则'
                } else {
                    return '编辑操作规则'
                }
            }
        },
        mounted() {
            this.init();
        },
        methods: {
            init() {
                // 获取皮肤列表
                this.skinStyleList = [];
                getSkinStyleList().then(response => {
                    this.skinStyleList = response.data.map(item => {
                        let params = {}
                        params.label = item.name;
                        params.value = item.code;
                        return params;
                    });
                })

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


            },
            async show(data) {
                this.loading = false;
                this.dialogVisible = true
                if (data && data.id) {
                    // 获取操作占位列表
                    let res = await getPlaceholderList({ trainingType: data.trainingType, skinStyle: data.skinStyle });
                    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,
                        skinStyle: data.skinStyle,
                        minDuration: data.minDuration,
                        maxDuration: data.maxDuration,
                        trainingRemark: this.repliceName(data.trainingRemark, this.placeholderList),
                    };
                }
            },
            repliceName(fieldValue, enumList) {
                if (enumList && enumList.length > 0) {
                    for (let i = 0; enumList && 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, skinStyle: '02' }).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() {
                let self = this
                this.$refs.dataform.validateForm(() => {
                    if (self.type === 'ADD') {
                        self.create()
                    } else {
                        self.update()
                    }
                })
            },
            create() {
                let self = this
                this.placeholderList.forEach(item => {
                    if (this.formModel.trainingName.includes(`{${item.name}}`)) {
                        let name = this.formModel.trainingName.replace(`{${item.name}}`, `{${item.id}}`);
                        this.formModel.trainingName = name;
                    }
                    if (this.formModel.trainingRemark.includes(`{${item.name}}`)) {
                        let 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('创建操作定义成功')
                    self.handleClose()
                    self.$emit('reloadTable')
                }).catch(error => {
                    self.loading = false;
                    self.$message.error('创建操作定义失败：' + error.message)
                })
            },
            update() {
                let self = this
                this.placeholderList.forEach(item => {
                    if (this.formModel.trainingName.includes(`{${item.name}}`)) {
                        let name = this.formModel.trainingName.replace(`{${item.name}}`, `{${item.id}}`);
                        this.formModel.trainingName = name;
                    }
                    if (this.formModel.trainingRemark.includes(`{${item.name}}`)) {
                        let 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('创建操作定义成功')
                    self.handleClose()
                    self.$emit('reloadTable')
                }).catch(error => {
                    self.loading = false;
                    self.$message.error('创建操作定义失败：' + error.message)
                })
            },
            handleClose() {
                this.formModel = {
                    trainingName: '',
                    trainingType: '',
                    operateType: '',
                    skinStyle: '',
                    minDuration: '',
                    maxDuration: '',
                    trainingRemark: '',
                }
                this.$refs.dataform.resetForm()
                this.dialogVisible = false
            }
        }
    }
</script>