<template>
  <div>
    <el-dialog :title="exData.id ? '编辑': '新增'" :visible.sync="dialog" width="450px" :close-on-click-modal="false"
               top="50px">
      <el-form ref="form" :model="form" label-width="100px" class="bind-phone">
        <el-form-item v-if="!exData.id" label="项目选择：">
          <el-select v-model="form.department_project_id">
            <el-option v-for="(item, index) in projectArr" :key="index" :label="item.project_name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称：">
          <el-input v-model="form.department_name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门描述：">
          <el-input v-model="form.department_desc" placeholder="请输入部门描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-center">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="danger" :disabled="booLock" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  props: {
    value: {
      type: Boolean,
      default: true
    },
    exData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  computed: {
    ...mapGetters([
      'projectArr'
    ])
  },
  data () {
    return {
      dialog: !!this.value,
      form: {
        department_project_id: undefined,
        department_name: '',
        department_desc: ''
      },
      booLock: false
    }
  },
  methods: {
    async handleSubmit () {
      let url = this.exData.id ? '/department/edit' : '/department/add'
      this.booLock = true
      const data = await this.$fetch('/api/auth' + url, { ...this.form })
      this.booLock = false
      if (data.code === 200) {
        this.$message.success('提交成功')
        this.$emit('success')
        this.dialog = false
      }
    }
  },
  mounted () {
    if (this.projectArr.length == 0) {
      this.$store.dispatch('common/setProjectArr')
    }
    if (this.exData.id) {
      this.form.id = this.exData.id
      this.form.department_name = this.exData.department_name
      this.form.department_desc = this.exData.department_desc
    }
  },
  watch: {
    dialog (val) {
      if (!val) this.$emit('input', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.top-tip {
  margin-top: -20px;
  margin-bottom: 20px;
}
</style>
