<template>
  <div>
    <div :class="$style['model-table-button']">
      <a-space>
        <a-button type="primary" @click="addRole">添加</a-button>
        <a-button :disabled="selectedRowKeys.length === 0" @click="deleteRole">删除</a-button>
      </a-space>
    </div>
    <sd-table
      ref="dataTable"
      row-key="id"
      :columns="columns"
      sortable
      :data-source.sync="roleData"
      :row-selection="{
        onChange: (keys) => {
          onSelectChange(keys)
        },
        selectedRowKeys: selectedRowKeys,
      }"
      :pagination="false"
    >
      <template slot="dispTitle" slot-scope="text, record">
        {{ record.name + '(' + record.code + '[' + record.id + ']' + ')' }}
      </template>
    </sd-table>

    <a-modal
      v-model="visible"
      :title="'设置[' + depInfo.name + ']角色个性化'"
      destroy-on-close
      v-bind="{ width: 800 }"
      :mask-closable="false"
      :confirm-loading="confirmLoading"
      @cancel="$emit('closed')"
      @ok="save"
    >
      <div :class="$style.wrap">
        <a-spin v-if="spinningAdd" :spinning="spinningAdd" :class="$style.spin" />
        <div :class="$style.tree">
          <a-tree
            v-if="treeData.length > 0"
            v-model="checkedKeys"
            checkable
            :block-node="true"
            :tree-data="treeData"
            :default-expanded-keys="defaultExpandedKeys"
            :default-checked-keys="defaultCheckedKeys"
          >
          </a-tree>
        </div>
        <div :class="$style.list">
          <sd-table :columns="columns" sortable :data-source.sync="selectedRoles">
            <template slot="dispTitle" slot-scope="text, record">
              {{ record.name + '(' + record.code + '[' + record.id + ']' + ')' }}
            </template>
          </sd-table>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-hiera-role-import'

export default {
  name: 'SdOrgHieraRole',
  metaInfo: {
    title: 'SdOrgHieraRole',
  },
  components,
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
  },
  inject: ['depInfo'],
  data() {
    return {
      confirmLoading: false,
      roleData: [],
      visible: false,
      selectedRowKeys: [],

      treeData: [],
      defaultExpandedKeys: ['global', 'local'],
      checkedKeys: [],
      spinningAdd: false,
      allRoles: [],
      defaultCheckedKeys: [],

      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          scopedSlots: {
            customRender: 'dispTitle',
          },
        },
      ],
    }
  },
  computed: {
    selectedRoles() {
      return this.allRoles.filter((item) => {
        return this.checkedKeys.includes(item.id)
      })
    },
  },

  methods: {
    addRole() {
      this.visible = true
    },
    deleteRole() {
      const params = {
        groupId: parseInt(this.unid, 10),
        roleIds: this.selectedRowKeys, // .join(','),
      }
      OrgService.deleteHieraRole(params)
        .then((res) => {
          if (res.status === 200) {
            message.success('删除成功')
            this.getHieraRole()
          } else {
            message.error(res.data?.message || '删除失败')
          }
        })
        .catch(() => message.error('删除失败'))
        .finally(() => {})
    },
    onSelectChange(keys) {
      this.selectedRowKeys = keys
    },
    isDisabled(item) {
      return (
        ['ADMINISTRATOR', 'SECURITYADMINISTRATOR', 'SECURITYAUDITOR', 'ANONYMOUS'].indexOf(
          item.code
        ) !== -1
      )
    },
    getHieraRole() {
      this.selectedRowKeys = []
      OrgService.getHieraRole({ id: this.unid }).then((res) => {
        this.roleData = res.data.datas
        this.defaultCheckedKeys = res.data.datas.map((item) => {
          return item.id
        })
        this.checkedKeys = this.defaultCheckedKeys
      })
    },
    init() {
      this.getHieraRole()
      OrgService.getHieraRoleList({ id: this.unid }).then((res) => {
        this.allRoles = res.data

        const sysRoles = []
        const localRoles = []
        this.allRoles.forEach((item) => {
          if (item.props.scope === 'global') {
            sysRoles.push({
              key: item.id,
              title: item.name + '(' + item.code + ')',
              disabled: this.isDisabled(item),
              isLeaf: true,
              scopedSlots: {
                title: 'title',
              },
            })
          } else {
            localRoles.push({
              key: item.id,
              title: item.name + '(' + item.code + ')',
              disabled: this.isDisabled(item),
              isLeaf: true,
              scopedSlots: {
                title: 'title',
              },
            })
          }
        })
        this.treeData = [
          {
            key: 'global',
            title: '全局角色',
            isLeaf: false,
            scopedSlots: {
              title: 'title',
            },
            children: sysRoles,
          },
          {
            key: 'local',
            title: '本地角色',
            isLeaf: false,
            scopedSlots: {
              title: 'title',
            },
            children: localRoles,
          },
        ]
      })
    },
    save() {
      return new Promise((resolve) => {
        const params = {
          groupId: parseInt(this.unid, 10),
          roleIds: this.checkedKeys.filter((item) => {
            return item !== 'global' && item !== 'local'
          }),
        }

        params.groupId = parseInt(this.unid, 10)
        this.spinningAdd = true

        this.confirmLoading = true
        return OrgService.addHieraRole(params)
          .then((res) => {
            if (res.status === 200) {
              message.success('保存成功')
              this.visible = false
              this.getHieraRole()
              resolve(true)
            } else {
              message.error(res.data?.message || '保存失败')
            }
          })
          .catch(() => message.error('保存失败'))
          .finally(() => {
            this.spinningAdd = false
            this.confirmLoading = false
          })
      })
    },
    close() {
      this.$emit('cancel')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.spin {
  position: absolute;
  width: 100%;
  line-height: 10;
}
.wrap {
  display: flex;

  .tree {
    width: 300px;
    height: 100%;
    overflow: scroll;
  }
  .list {
    width: calc(100% - 300px);
  }
}
</style>
