<template>
  <div>
    <vxe-modal
      :value="isShow"
      show-footer
      title="部门"
      show-confirm-button
      :width="600"
      :height="400"
      esc-closable
      @input="e => $emit('update:isShow',e)"
    >
      <el-form ref="elForm" :model="form" :rules="rules" label-position="top" label-width="100">
        <el-form-item label="部门名称" prop="name" required>
          <el-input v-model="form.name" clearable />
        </el-form-item>
        <el-form-item label="父级部门" prop="pid">
          <Treeselect
            v-model="form.pid"
            :options="formatList"
            no-children-text="无子部门"
            :normalizer="node => ({
              id: node.id,
              label: node.name,
              children: node.children,
              isDefaultExpanded: true
            })"
          />
        </el-form-item>
        <el-form-item label="分管负责人" prop="manager_id">
          <user-picker v-model="form.manager_id" width="100%" />
        </el-form-item>
        <el-form-item label="主要领导" prop="leader_id">
          <user-picker v-model="form.leader_id" width="100%" />
        </el-form-item>
        <el-form-item label="排序" prop="sortnumber">
          <el-input-number v-model="form.sortnumber" controls-position="right" :precision="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" :loading="loading" @click="submit">确认</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import UserPicker from '@/components/UserPicker/index.vue'
import { save } from '@/api/department'
export default {
  components: {
    UserPicker
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    isShow: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      form: {
        name: '',
        pid: 0,
        manager_id: '',
        leader_id: '',
        sortnumber: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入模块名称' }
        ]
      }
    }
  },
  computed: {
    formatList() {
      return [
        {
          name: '#根部门',
          id: 0
        },
        ...this.list
      ]
    }
  },
  methods: {
    submit() {
      this.$refs['elForm'].validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            await save(this.form)
            this.$message.success('新增成功')
            this.$emit('refresh')
            this.$emit('update:isShow', false)
            this.loading = false
            this.$refs['elForm'].resetFields()
          } catch (err) {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
