<template>
  <el-dialog
    :title="type==='edit'?'编辑':'添加'"
    :visible.sync="visible"
    width="50%"
    @close="handleClose">
    <el-form
      style="padding:20px"
      inline
      :model="form"
      ref="form"
      label-width="260px">
      <el-form-item
        verify
        class="is-required"
        label="是否启用"
        prop="isUse">
        <el-switch
          v-model="form.isUse"
          active-text="激活"
          inactive-text="禁用"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item
        label="免票年龄以下(不限制为-1)"
        prop="freeAgeBelow">
        <el-input v-model="form.freeAgeBelow"></el-input>
      </el-form-item>
      <el-form-item
        label="免票年龄以上(不限制为-1)"
        prop="freeAgeOver">
        <el-input v-model="form.freeAgeOver"></el-input>
      </el-form-item>
      <el-form-item
        label="免票的身份证开头地区(多个用逗号分隔)"
        prop="freeArea">
        <el-input v-model="form.freeArea"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="visible= false">取 消</el-button>
      <el-button
        type="primary"
        @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import { updateFreeConfig, addFreeConfig } from '@/api/freeConfig'
const defaultForm = {
  isUse: 1,
  freeAgeBelow: '',
  freeAgeOver: '',
  freeArea: ''
}
export default {
  data () {
    return {
      type: '',
      visible: false,
      form: {
        ...defaultForm
      }
    }
  },
  methods: {
    show (type, data) {
      this.type = type
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (type === 'edit' && data) {
          this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(data)))
        } else {
          this.form = JSON.parse(JSON.stringify(defaultForm))
        }
      })
    },
    handleClose () {
      this.visible = false
    },
    handleSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.type === 'edit') {
            updateFreeConfig(this.form).then(res => {
              this.$message.success('操作成功')
              this.handleClose()
              this.$emit('update')
            })
          } else {
            addFreeConfig(this.form).then(res => {
              this.$message.success('操作成功')
              this.handleClose()
              this.$emit('update')
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
