<template>
  <el-dialog :title="$t('addStaff.chooseOrg')" :visible.sync="visible" width="50%" @close="handleClose">
    <el-tree ref="orgTree" :data="orgs" :props="defaultProps" node-key="id" highlight-current
      @node-click="handleNodeClick" class="org-tree-container" />
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('addStaff.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm">{{ $t('addStaff.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>
  
<script>
import { listOrgTree } from '@/api/staff/addStaffApi'

export default {
  name: 'ChooseOrgTree',
  data() {
    return {
/*************  ✨ Windsurf Command ⭐  *************/
/**
 * Lifecycle hook called when the component is mounted.
 * Initializes the jsTree with the current organization data.
 */

/*******  cd76f80b-513b-4475-894b-fd5714d067a7  *******/        visible: false,
      orgs: [],
      currentOrg: null,
      defaultProps: {
        children: 'children',
        label: 'text'
      }
    }
  },
  methods: {
    openOrgModal() {
      this.visible = true
      this.loadOrgs()
    },
    async loadOrgs() {
      this.orgs = []
      try {
        const res = await listOrgTree({
          communityId: '-1'
        })
        this.orgs.push(res.data)
      } catch (error) {
        this.$message.error(error.message || '加载组织树失败')
      }
    },
    handleNodeClick(data) {
      this.currentOrg = {
        orgId: data.id,
        allOrgName: data.text
      }
    },
    handleConfirm() {
      if (!this.currentOrg) {
        this.$message.warning('请选择组织')
        return
      }
      this.$emit('switchOrg', this.currentOrg)
      this.visible = false
    },
    handleClose() {
      this.currentOrg = null
      this.$refs.orgTree.setCurrentKey(null)
    }
  }
}
</script>
  
<style lang="scss" scoped>
.org-tree-container {
  min-height: 300px;
  max-height: 500px;
  overflow-y: auto;
}
</style>