<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="600px"
    @close="handleClose">
    <el-form
      :model="form"
      ref="form"
      class="form-wrap"
      label-width="100px">
      <div class="dialog-info">
        <el-form-item
          style="width:100%"
          label="分组名称"
          prop="name"
          :rules="[{ required: true, message: '请输入分组名称', trigger: 'blur' }]"
        >
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item
          style="width:100%"
          label="描述"
          prop="description">
          <el-input
            type="textarea"
            v-model="form.description"></el-input>
        </el-form-item>
      </div>
    </el-form>

    <div slot="footer">
      <el-button @click="handleClose">
        取 消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addTicketTypeGroup, updateTicketTypeGroup } from '@/api/ticketTypeGroup'

const defaultForm = {
  id: '',
  name: '',
  description: ''
}

export default {
  data () {
    return {
      title: '',
      type: '',
      visible: false,
      loading: false,
      form: {
        ...defaultForm
      }
    }
  },
  methods: {
    show (type, row) {
      this.type = type
      this.title = type === 'edit' ? '编辑分组' : '新增分组'
      this.visible = true

      this.$nextTick(() => {
        this.reset()
        if (type === 'edit' && row) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(row)))
        } else {
          this.form = JSON.parse(JSON.stringify(defaultForm))
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    handleClose () {
      this.visible = false
    },
    handleSubmit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          this.loading = true
          if (this.type === 'edit') {
            updateTicketTypeGroup(params).then(res => {
              this.$message.success('修改成功')
              this.$emit('update')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          } else {
            addTicketTypeGroup(params).then(res => {
              this.$message.success('新增成功')
              this.$emit('update')
              this.handleClose()
            }).finally(() => {
              this.loading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form-wrap {
  .el-input,.el-select,.el-date-editor,.el-date-editor.el-input,.el-input-number {
    width: 100%;
  }
}
</style>
