<template>
    <el-form :model="formData" :rules="rules" ref="nodeForm" label-width="120px">
        <el-form-item label="动线流程名称" prop="node_name">
            <el-input v-model="formData.node_name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="详细说明">
            <el-input type="textarea" placeholder="请输入" v-model="formData.detail" maxlength="300"
                      show-word-limit></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="warning" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    import {updateNode} from '@/api/check'

    export default {
        name: 'EditNode',
        props: ['nodeData', 'nodeSort'],
        data() {
            return {
                formData: {
                    node_name: null,
                    detail: null
                },
                rules: {
                    node_name: [
                        {required: true, message: '请输入动线流程名称', trigger: 'blur'},
                        {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
                    ],
                    detail: [
                        {required: true, message: '请输入详细说明', trigger: 'blur'},
                        {min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur'}
                    ],
                }
            }
        },
        watch: {
            nodeData(v) {
                if (v) {
                    this.formData = Object.assign(this.formData, v)
                }
            }
        },
        mounted() {
            if (this.nodeData) {
                this.formData = Object.assign(this.formData, this.nodeData)
            }
        },
        methods: {
            resetForm() {
                this.$refs.nodeForm.resetFields()
                this.formData.detail = '';
            },
            handleConfirm() {
                const vm = this
                this.$refs.nodeForm.validate((valid) => {
                    if (valid) {
                        const obj = Object.assign({}, vm.formData)
                        if (obj.id) {
                            updateNode(obj.id, obj).then(res => {
                                this.$message.success('节点信息更新成功')
                                vm.$emit('changeNodeData', obj, this.nodeSort)
                            })
                        } else {
                            vm.$emit('changeNodeData', obj, this.nodeSort)
                        }
                        vm.resetForm()
                    }
                })
            }
        }
    }
</script>