<template>
    <el-dialog title="添加单位" :visible.sync="dialogVisible" @close="reset">
        <el-form ref="form" :model="form" :rules="rules" label-width="120" label-position="left">
            <el-form-item label="单位名称" prop="name">
                <el-input v-model="form.name" placeholder="单位名称"></el-input>
            </el-form-item>
            <el-form-item label="排序" v-if="form.id">
                <el-input v-model="form.sort"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="formLoading" @click="onSubmitHandle">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import { tbShopUnitPost, tbShopUnitPut } from '@/api/shop'
export default {
    data() {
        return {
            dialogVisible: false,
            formLoading: false,
            form: {
                id: '',
                name: '',
                sort: 0,
                shopId: localStorage.getItem('shopId')
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: ' ',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    methods: {
        onSubmitHandle() {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        this.formLoading = true
                        let res = null
                        if (!this.form.id) {
                            res = await tbShopUnitPost(this.form)
                        } else {
                            res = await tbShopUnitPut(this.form)
                        }
                        this.close()
                        this.formLoading = false
                        this.$emit('success', res)
                        this.$notify({
                            title: '成功',
                            message: `${this.form.id ? '编辑' : '添加'}成功`,
                            type: 'success'
                        });
                    } catch (error) {
                        this.formLoading = false
                    }
                }
            })
        },
        show(obj) {
            this.dialogVisible = true
            if (obj && obj.id) {
                // 编辑
                this.form.name = obj.name
                this.form.id = obj.id
            }
        },
        close() {
            this.dialogVisible = false
        },
        reset() {
            this.form.id = ''
            this.form.name = ''
            this.form.sort = 0
        }
    }
}
</script>