<template>
  <div class="v-page">
    <SearchTreeMenu
      ref="treeMenuRef"
      title="组织机构列表"
      :tree-data="org_list"
      @current-change="change"
      @onCreate="toCreateOrg"
      @onDelete="toDeleteOrg"
    />
    <div class="v-ctx" v-if="active_org">
      <FormLayout
        ref="formLayoutRef"
        :items="formItems"
        :model="active_org"
        :rules="rules"
        label-width="110px"
        label-position="right"
      />

      <ActionBar center @onConfirm="onConfirm" @onCancel="onCancel" />
    </div>
  </div>
</template>

<script>
import { SearchTreeMenu, FormLayout, ActionBar } from '@/components/layout'

import { createOrgApi, deleteOrgApi, findAllOrgApi, updateOrgApi } from '@/api/system/org'

export default {
  components: { SearchTreeMenu, FormLayout, ActionBar },

  data: () => ({ search: '', org_list: [], active_org: null }),

  created () {
    this.formItems = [
      { prop: 'name', label: '组织机构名称', model: { tag: 'el-input', attrs: { maxlength: '16', placeholder: '请输入组织机构名称' } } },
      {
        prop: 'desc',
        label: '组织机构描述',
        model: { tag: 'el-input', type: 'textarea', attrs: { 'show-word-limit': true, rows: 5, placeholder: '请输入组织机构描述' } }
      }
    ]

    this.rules = {
      name: { required: true, message: '请输入组织机构名称', trigger: 'blur' }
    }

    this.findAllOrg()
  },

  methods: {
    async findAllOrg () {
      const { data } = await findAllOrgApi()
      const { tree } = data.toTree()
      this.org_list = Object.freeze(tree)
    },

    change (org) {
      this.active_org = JSON.parse(JSON.stringify(org))
    },

    toCreateOrg () {
      this.active_org = { name: '', desc: '', pid: this.$refs.treeMenuRef.getCurrentNode()?.id || 0 }
    },

    async toDeleteOrg (node) {
      await this.$confirm('将删除一个组织, 是否继续?')
      await deleteOrgApi(node.id)
      this.onCancel()
      this.findAllOrg()
    },

    async onConfirm () {
      await this.$refs.formLayoutRef.validate()
      await (!this.active_org.id ? createOrgApi : updateOrgApi)(this.active_org)
      this.onCancel()
      this.findAllOrg()
    },

    onCancel () {
      this.active_org = null
      this.$refs.treeMenuRef.setCurrentKey()
    }
  }
}
</script>
