<template>
  <el-dialog
    :title="$t('staffAttendance.chooseOrg')"
    :visible.sync="visible"
    width="60%"
    @close="handleClose"
  >
    <el-tree
      ref="orgTree"
      :data="orgs"
      node-key="id"
      :props="defaultProps"
      :highlight-current="true"
      @node-click="handleNodeClick"
    ></el-tree>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm">{{ $t('common.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'
import { listOrgTree } from '@/api/oa/staffAttendanceManageApi'

export default {
  name: 'ChooseOrgTree',
  data() {
    return {
      visible: false,
      orgs: [],
      currentOrg: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    open() {
      this.visible = true
      this.loadOrgs()
    },
    
    async loadOrgs() {
      try {
        const params = {
          communityId: getCommunityId()
        }
        const { data } = await listOrgTree(params)
        this.orgs = data || []
      } catch (error) {
        console.error('Failed to load orgs:', error)
        this.$message.error(this.$t('staffAttendance.loadOrgFailed'))
      }
    },
    
    handleNodeClick(data) {
      this.currentOrg = data
    },
    
    handleConfirm() {
      if (!this.currentOrg || !this.currentOrg.id) {
        this.$message.warning(this.$t('staffAttendance.selectOrgFirst'))
        return
      }
      
      this.$emit('switchOrg', {
        orgId: this.currentOrg.id,
        allOrgName: this.getOrgFullName(this.currentOrg)
      })
      this.visible = false
    },
    
    getOrgFullName(node) {
      if (!node) return ''
      
      let names = []
      let currentNode = node
      
      while (currentNode) {
        names.unshift(currentNode.name)
        currentNode = this.$parent ? this.$parent.getNode(currentNode.parentId) : null
      }
      
      return names.join('/')
    },
    
    handleClose() {
      this.currentOrg = {}
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tree {
  max-height: 500px;
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
}
</style>