<template>
  <el-dialog :visible.sync="dialogFormVisible" title="新增组" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="groupForm" label-well-code="right" label-width="100px">
      <el-row type="flex" justify="center">
        <el-col :span="16">
          <el-form-item label="组名称" prop="groupName">
            <el-input v-model.trim="groupForm.groupName" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isAdmin" type="flex" justify="center">
        <el-col :span="16">
          <el-form-item label="所属派出所" prop="deptid">
            <dept-select v-model="groupForm.deptid" :need-top="false" dept-type="03" placeholder="选择所属派出所"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import { addGroup } from '@/api/group'
export default {
  name: 'AddGroup',
  components: {
    DeptSelect
  },
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      groupForm: {
        groupName: '', // 组名称
        deptid: '' // 组织机构
      },
      rules: {
        groupName: [{ required: true, message: '组名称必填', trigger: ['blur', 'change'] }],
        deptid: [{ required: true, message: '所属派出所必选', trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      btnLoading: false, // 按钮加载动画
      deptShow: false // 组织机构是否显示
    }
  },
  methods: {
    initDialog: function(row = null) {
      this.btnLoading = false
      this.dialogFormVisible = true
      this.resetForm()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 重置表单
    resetForm() {
      this.groupForm = {
        groupName: '', // 组名称
        deptid: '' // 组织机构
      }
    },
    // 点击保存
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          // 调用后台请求
          addGroup(this.groupForm).then(response => {
            if (response.code === 200) {
              this.$message.success('添加成功！')
              this.cancel()
            }
            this.btnLoading = false
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    // 取消
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style scoped>

</style>
