<template>
  <div>
    <el-switch
      v-model="isOpen"
      active-text="级联"
      inactive-text=""
      v-if="orgTrees && orgTrees.length"
    />
    <el-tree
      ref="orgTree"
      v-loading="loading"
      :data="orgTrees"
      show-checkbox
      :check-strictly="!isOpen"
      :props="{ children: 'children', label: 'title' }"
      node-key="key"
    />
    <el-button v-if="orgTrees && orgTrees.length > 0" v-permission="['role:org:assign']" :disabled="!roleId" type="primary" @click="saveRoleOrgs">
      {{ $t('ec.dialog.save') }}
    </el-button>
  </div>
</template>

<script>

import { findTreeByTenant } from 'ecip-web/api/vue/org/saasOrgApi'
import { getRoleOrg, assignRoleOrg } from 'ecip-web/api/vue/role/sysrRoleApi'
import { superAdmin } from '@/settings'
import permissionMixin from 'ecip-web/utils/permission-mixin'

export default {
  name: 'OrgAuthTab',
  mixins: [permissionMixin],
  props: {
    tenantId: {
      type: String,
      required: false
    },
    roleId: {
      type: String,
      required: false
    }
  },
  data() {
    return {
        isOpen:false,
      loading: false,
      emptyText: this.$t('ec.table.loading'),
      orgTrees: [], // 组织树
      roleOrgs: [] // 角色的组织权限
    }
  },
  /*  computed: {
    conditionChange() {
      const { tenantId } = this
      return { tenantId }
    }
  },*/
  watch: {
    /*    tenantId: {
      handler(val) {
        this.getOrgTrees(val)
      },
      immediate: true
    },
    conditionChange: {
      handler(val) {
        this.getOrgTrees(this.tenantId)
      },
      immediate: true
    },*/
    roleId: {
      handler(val) {
        if (val) {
          this.getRoleOrg(val)
        }
      },
      immediate: true
    }
  },
  methods: {
    init(tenantId) {
      this.getOrgTrees(tenantId)
    },
    async getOrgTrees(tenantId) {
      if (superAdmin && !tenantId) {
        this.orgTrees = []
        return
      }
      try {
        this.loading = true
        const { data } = await findTreeByTenant({ tenantId: tenantId })
        this.orgTrees = data
      } finally {
        this.loading = false
      }
    },
    async getRoleOrg(roleId) {
      this.loading = true
      const { data } = await getRoleOrg(roleId)
      this.$refs.orgTree.setCheckedKeys(data)
      this.loading = false
    },
    async saveRoleOrgs() {
      const checkedNodes = this.$refs.orgTree.getCheckedNodes()
      const checkedIds = []
      if (checkedNodes) {
        checkedNodes.forEach(node => {
          checkedIds.push(node.key)
        })
      }
      const saveLoading = this.$loading({
        lock: true,
        spinner: 'el-icon-loading'
      })
      try {
        await assignRoleOrg(this.roleId, checkedIds)
      } finally {
        saveLoading.close()
        this.$notify.success(this.$t('ec.role.orgAuthSuccess'))
      }
    }
  }
}
</script>

<style scoped>

</style>
