<template>
  <div class="org_user_chart chart">
    <SearchTreeMenu
      ref="treeMenuRef"
      class="org_tree"
      title="组织机构列表"
      :tree-data="org_list"
      @current-change="toChangeOrg"
    />
    <VListCard
      ref="vListCardRef"
      title="人员列表"
      class="ml-12 flex-1"
      itemLabelKey="name"
      :isCancel="isCancelList"
      :dataList="student_list"
      @change="onChangeStudent"
    />
  </div>
</template>

<script>
import { SearchTreeMenu } from '@/components/layout'
import VListCard from './VListCard.vue'
import { findAllOrgApi } from '@/api/system/org'
import { findStudentByOrgIdApi } from '@/api/system/user'

export default {
  components: { SearchTreeMenu, VListCard },

  props: {
    /**
     * 是否可以取消【列表】的选中
     */
    isCancelList: { type: Boolean },

    /**
     * 默认选中【树】的第一个
     */
    isActiveTreeByFirst: { type: Boolean, default: true },

    /**
     * 默认选中【列表】的第一个
     */
    isActiveListByFirst: { type: Boolean, default: true }
  },

  data: () => ({ org_list: [], student_list: [] }),

  inject: ['watchComponentVisible'],

  mounted () {
    this.watchComponentVisible(this.$el, this.findAllOrg)
  },

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

      this.isActiveTreeByFirst && this.$nextTick(() => {
        this.$refs.treeMenuRef.setCurrentKey(this.org_list[0]?.id)
        this.toChangeOrg(this.org_list[0])
      })
    },

    async toChangeOrg (org) {
      if (this.activeOrgId === org.id) return

      this.activeOrgId = org.id
      const { data } = await findStudentByOrgIdApi(this.activeOrgId)
      this.student_list = data

      this.isActiveListByFirst && this.$refs.vListCardRef.setActive(data[0])
    },

    onChangeStudent (student) {
      if (this.active_student === student) return
      this.$emit('change', this.active_student = student)
    }

  }
}
</script>

<style lang="scss" scoped>
.org_user_chart {
  display: flex;
  position: sticky;
  top: 0;

  &.chart {
    width: 360px;
    border: none;
  }

  .org_tree {
    padding: 12px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
  }

  .org_tree {
    width: 220px;

    ::v-deep.v-title {
      margin-bottom: 12px;
    }
  }

}
</style>
