<template>
  <el-dialog
    :title="$t('staffCommunity.chooseOrgTitle')"
    :visible.sync="visible"
    width="60%"
  >
    <el-tree
      ref="orgTree"
      :data="orgs"
      node-key="id"
      show-checkbox
      :props="defaultProps"
      @check-change="handleCheckChange"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="confirmChoose">{{ $t('common.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listOrgTree } from '@/api/staff/staffCommunityApi'

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 { data } = await listOrgTree({
          communityId: this.$store.getters.communityId
        })
        this.orgs = data
      } catch (error) {
        this.$message.error(this.$t('staffCommunity.fetchOrgError'))
      }
    },
    handleCheckChange(data, checked) {
      if (checked) {
        this.currentOrg = {
          orgId: data.id,
          allOrgName: data.name
        }
      }
    },
    confirmChoose() {
      if (!this.currentOrg.orgId) {
        this.$message.warning(this.$t('staffCommunity.selectOrgTip'))
        return
      }
      this.$emit('switchOrg', this.currentOrg)
      this.visible = false
    }
  }
}
</script>

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