<template>

  <vxe-grid
    ref="roleResource"
    border
    highlight-hover-row
    max-height="1000"
    class="vxe-table-element"
    resizables
    sync-resize
    auto-resize
    :loading="loading"
    :toolbar="resourceTableToolbar"
    :columns="resourceColumns"
    :tree-config="{children: 'children'}"
    :checkbox-config="{checkStrictly:!isOpen,showHeader:isOpen}"
    :data="resourceTrees"
    @checkbox-all="({selection}) => { rsrcSelected = selection}"
    @checkbox-change="({selection}) => { rsrcSelected = selection }"
  >
    <template v-slot:rsrcEnableStatus="{ row }">
      <el-switch v-model="row.rsrcStatus" :disabled="!checkPermission(['resource:edit'])" active-color="#13ce66" :active-value="1" :inactive-value="0" />
    </template>
    <template v-slot:resourceStatus="{ row }">
      <el-switch v-if="roleId" :disabled=" !enableRsrcAuthBtn || !checkPermission(['role:resource:assign']) || !checkPermission(['role:resource:cancel'])" :value="resourceStatus(row.id)" active-color="#13ce66" :active-value="true" :inactive-value="false" @change="(status) => assignOneRsrc(status, row)" />
    </template>

    <template v-slot:rsrcStatusHeader>
      <span>
        {{ $t('ec.role.authStatus') }}
        <vxe-tooltip :content="$t('ec.role.selectAlert')" enterable>
          <i class="el-icon-question" />
        </vxe-tooltip>
      </span>
    </template>
    <template v-slot:rsrc_buttons>
      <el-button v-permission="['role:resource:assign']" type="primary" :disabled="rsrcSelected.length === 0 || !roleId" @click="assignRsrc()">
        {{ $t('ec.role.auth') }}
      </el-button>
      <el-button v-permission="['role:resource:cancel']" type="danger" :disabled="rsrcSelected.length === 0 || !roleId" @click="cancelRsrcAssign()">
        {{ $t('ec.role.authCancel') }}
      </el-button>
      <el-button @click="toggleResources">{{ $t('ec.table.expandCollapse') }}</el-button>
      <el-switch
        v-if="resourceTrees && resourceTrees.length"
        v-model="isOpen"
        active-text="级联"
        inactive-text=""
        style="margin-left: 10px;"
      />
    </template>
  </vxe-grid>
</template>

<script>
import {
  getRoleResource,
  saveRoleResource,
  cancelRoleResource
} from 'ecip-web/api/vue/role/sysrRoleApi'
import { findTreeByAppTenant as findResourceTreeByAppTenant } from 'ecip-web/api/vue/resource/sysrResourceApi'
import { superAdmin } from '@/settings'
import permissionMixin from 'ecip-web/utils/permission-mixin'
const enableRsrcAuthBtn = window._CONFIG['enableRsrcAuthBtn'] === undefined ? false : window._CONFIG['enableRsrcAuthBtn']

export default {
  name: 'RsrcAuthTab',
  mixins: [permissionMixin],
  props: {
    roleId: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      enableRsrcAuthBtn,
      isOpen: false,
      loading: false,
      expand: false,
      rsrcSelected: [], // 已选的资源权限
      resourceTrees: [], //  菜单树
      roleResources: [], //  角色的功能权限
      resourceTableToolbar: {
        id: 'vue.user.resource.sysrResourceView-toolbar',
        // custom: true,
        slots: {
          buttons: 'rsrc_buttons'
        },
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      resourceColumns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'ec.resource.name', field: 'rsrcName', minWidth: 200, treeNode: true, showOverflow: true },
        // { title: 'ec.table.enableStatus', field: 'rsrcStatus', width: 80, slots: { default: 'rsrcEnableStatus' }},
        { title: 'ec.role.authStatus', width: 100, slots: { default: 'resourceStatus', header: 'rsrcStatusHeader' }}
      ]
    }
  },
  watch: {
    /* appId: {
      handler(val) {
        this.getRsrcTreeByAppTenant(val, this.tenantId)
      },
      immediate: true
    },
    tenantId: {
      handler(val) {
        this.getRsrcTreeByAppTenant(this.appId, val)
      },
      immediate: true
    },*/
    roleId: {
      handler(val) {
        if (val) {
          this.getRoleResource(val)
        }
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    init(appId, tenantId) {
      // 一般用init 是新增的情况所以默认开启级联模式和全选模式，方便全选
      this.isOpen = true
      this.getRsrcTreeByAppTenant(appId, tenantId)
    },
    async getRsrcTreeByAppTenant(appId, tenantId) {
      this.rsrcSelected = []
      if (superAdmin && !appId) {
        this.resourceTrees = []
        return
      }
      try {
        this.loading = true
        const { data } = await findResourceTreeByAppTenant(appId, tenantId)
        this.resourceTrees = data
      } finally {
        this.loading = false
      }
    },
    async getRoleResource(roleId) {
      this.loading = true
      const { data } = await getRoleResource(roleId)
      this.roleResources = data
      this.loading = false
    },
    assignRsrc() {
      this.$confirm(this.$t('ec.role.rsrcAuthConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        const saveLoading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading'
        })
        const assignRsrcIds = this.rsrcSelected.map(item => item.id)
        await saveRoleResource(this.roleId, assignRsrcIds)
        saveLoading.close()
        this.$notify.success(this.$t('ec.role.auth') + this.$t('ec.message.success'))
        await this.getRoleResource(this.roleId)
      })
    },
    cancelRsrcAssign() {
      this.$confirm(this.$t('ec.role.rsrcAuthCancelConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        const saveLoading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading'
        })
        const assignRsrcIds = this.rsrcSelected.map(item => item.id)
        await cancelRoleResource(this.roleId, assignRsrcIds)
        this.$notify.success(this.$t('ec.role.authCancel') + this.$t('ec.message.success'))
        saveLoading.close()
        await this.getRoleResource(this.roleId)
      })
    },
    resourceStatus(cellValue) {
      if (!this.roleResources) {
        return false
      }
      return this.roleResources.includes(cellValue)
    },
    async assignOneRsrc(status, row) {
      let rsrcIds = []
      // 引入级联来判断
      if (this.isOpen) {
        this.getRsrcIds(row, rsrcIds)
      } else {
        rsrcIds.push(row.id)
      }

      let message
      const saveLoading = this.$loading({
        lock: true,
        spinner: 'el-icon-loading'
      })
      if (status) {
        await saveRoleResource(this.roleId, rsrcIds)
        message = this.$t('ec.role.auth') + this.$t('ec.message.success')
      } else {
        await cancelRoleResource(this.roleId, rsrcIds)
        message = this.$t('ec.role.authCancel') + this.$t('ec.message.success')
      }
      saveLoading.close()
      this.$notify.success(message)
      await this.getRoleResource(this.roleId)
    },
    toggleResources() {
      this.expand = !this.expand
      this.$refs.roleResource.setAllTreeExpansion(this.expand)
    },
    // 递归获取本节点及所有子节点的ID集合
    getRsrcIds(row, resultAry = []) {
      if (row.children && row.children.length > 0) {
        resultAry.push(row.id)
        for (let i = 0; i < row.children.length; i++) {
          this.getRsrcIds(row.children[i], resultAry)
        }
      } else {
        resultAry.push(row.id)
      }
    }
  }
}
</script>

<style scoped>

</style>
