<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="角色权限配置" width="650px" destroyOnClose showFooter>
    <a-spin :spinning="loading">
      <BasicTree
        ref="treeRef"
        checkable
        toolbar
        :treeData="treeData"
        :checkedKeys="checkedKeys"
        :selectedKeys="selectedKeys"
        :checkStrictly="false"
        :clickRowToExpand="false"
        title="所拥有的权限"
        @check="onCheck"
        @select="onTreeNodeSelect"
        @strictly-change="onStrictlyChange"
      >
        <template #title="{ slotTitle, ruleFlag }">
          {{ slotTitle }}
          <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
        </template>
      </BasicTree>
    </a-spin>
    <!--右下角按钮-->
    <template #footer>
      <c-button @click="closeDrawer">取消</c-button>
      <c-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">
        仅保存
      </c-button>
      <c-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</c-button>
    </template>
    <RoleDataRuleDrawer @register="registerDrawer1" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner, BasicTree, TreeItem, Button as CButton } from '@jdlinker/ui';
  import RoleDataRuleDrawer from './RoleDataRuleDrawer.vue';
  import { queryTreeListForRole, queryRolePermission, saveRolePermission } from '../role.api';

  //树的信息
  const treeData = ref<TreeItem[]>([]);
  //树的选择节点信息
  const checkedKeys = ref([]);
  const halfCheckedKeys = ref([]);
  const checkStrictly = ref(false);
  //树的选中的节点信息
  const selectedKeys = ref([]);
  const roleId = ref('');
  //树的实例
  const treeRef = ref(null);
  const loading = ref(false);

  const [registerDrawer1, { openDrawer: openDataRuleDrawer }] = useDrawer();
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset();
    loading.value = true;
    setDrawerProps({ confirmLoading: false, loading: true });
    roleId.value = data.roleId;
    //初始化数据
    const roleResult = await queryTreeListForRole();
    treeData.value = roleResult.treeList;
    //初始化角色菜单数据
    const permResult = await queryRolePermission({ roleId: unref(roleId) });
    checkedKeys.value = permResult.checked;
    halfCheckedKeys.value = permResult.halfChecked;
    setDrawerProps({ loading: false });
    loading.value = false;
  });
  /**
   * 点击选中
   */
  function onCheck(o, e) {
    checkedKeys.value = o.checked ? o.checked : o;
    halfCheckedKeys.value = e.halfCheckedKeys;
  }
  /**
   * 切换层级关联/层级独立
   */
  function onStrictlyChange(v) {
    checkStrictly.value = v;
  }
  /**
   * 选中节点，打开数据权限抽屉
   */
  function onTreeNodeSelect(key) {
    if (key && key.length > 0) {
      selectedKeys.value = key;
    }
    openDataRuleDrawer(true, { functionId: unref(selectedKeys)[0], roleId: unref(roleId) });
  }
  /**
   * 数据重置
   */
  function reset() {
    treeData.value = [];
    checkedKeys.value = [];
    halfCheckedKeys.value = [];
    selectedKeys.value = [];
    roleId.value = '';
    checkStrictly.value = false;
  }
  /**
   * 获取tree实例
   */
  function getTree() {
    const tree: any = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  async function handleSubmit(exit) {
    let params = {
      roleId: unref(roleId),
      checkedIds: unref(getTree().getCheckedKeys()),
      halfCheckedIds: unref(halfCheckedKeys)
    };
    if (loading.value === false) {
      await doSave(params);
    } else {
      console.log('请等待上次执行完毕!');
    }
    if (exit) {
      // 如果关闭
      closeDrawer();
    } else {
      // 没有关闭需要重新获取选中数据
      const permResult = await queryRolePermission({ roleId: unref(roleId) });
      halfCheckedKeys.value = permResult.halfChecked;
    }
  }

  async function doSave(params) {
    loading.value = true;
    await saveRolePermission(params);
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
</script>

<style lang="less" scoped>
  /** 固定操作按钮 */
  .jeecg-basic-tree {
    position: absolute;
    width: 618px;
  }
  :deep(.ant-tree .ant-tree-treenode) {
    padding: 0 0 1px 0;
  }
</style>
