<template>
  <el-dialog
    :title="`${type==='add'?'新增':'编辑'}区域`"
    append-to-body
    :visible.sync="visible"
    width="30%"
    @close="handleClose">
    <div class="formWrap">
      <el-form
        inline
        :model="form"
        ref="form"
        class="form-wrap"
        label-width="150px"
      >
        <el-form-item
          verify
          label="区域名称"
          prop="name">
          <el-input
            v-model="form.name"
            placeholder="不超过6个字"
            maxlength="6"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <span slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="danger"
        v-if="type==='edit'"
        @click="handleDelete">删除</el-button>
      <el-button
        type="primary"
        @click.stop="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { updateSeatArea, addSeatArea, deleteSeatArea } from '@/api/seat'

export default {
  props: {
    chartId: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      visible: false,
      type: 'add',
      config_id: 0,
      form: {
        name: '',
        x: 1,
        y: 1
      }
    }
  },
  methods: {
    show (type, info) {
      this.visible = true
      this.type = type

      this.config_id = info.config_id

      this.$nextTick(() => {
        this.$refs.form.resetFields()

        if (type === 'edit') {
          this.form = JSON.parse(JSON.stringify(info))
        }
      })
    },
    handleClose () {
      this.visible = false
      this.$refs.form.resetFields()
    },
    handleDelete () {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSeatArea(this.form).then(res => {
          this.$message.success('删除成功')

          this.visible = false

          this.$emit('update')
        })
      }).catch(() => {})
    },
    handleSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          switch (this.type) {
            case 'edit':
              updateSeatArea(this.form).then(res => {
                this.$message.success('更新成功')

                this.handleClose()

                this.$emit('update')
              })
              break
            case 'add':
              addSeatArea({ config_id: this.config_id, ...this.form }).then(res => {
                this.$message.success('添加成功')

                this.handleClose()

                this.$emit('update')
              })
              break
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.formWrap{
  padding: 20px 20px 0;
}
</style>
