<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="租户权限配置" width="650px" destroyOnClose :showFooter="showFooter">
    <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>
    <!--右下角按钮-->
    <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>
  </BasicDrawer>
  <TenantDataRuleDrawer @register="registerDrawer1" />
  <TenantPermissionSuccessModel @register="registerDrawer2" style="width: 300px" :minHeight="200" />
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner, BasicTree, TreeItem, useModal, Button as CButton } from '@jdlinker/ui';
  import TenantDataRuleDrawer from './TenantDataRuleDrawer.vue';
  import TenantPermissionSuccessModel from './TenantPermissionSuccessModel.vue';
  import { queryTreeListForTenant, queryTenantPermission, saveTenantPermission } from './tenant.api';

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

  const [registerDrawer1, { openDrawer: openDataRuleDrawer }] = useDrawer();
  const [registerDrawer2, { openModal: openSuccessModel }] = useModal();
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset();
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, loading: true, showFooter: showFooter.value });
    tenantId.value = data.tenantId;
    //初始化数据
    const tenantResult = await queryTreeListForTenant();
    treeData.value = tenantResult.treeList;
    //初始化角色菜单数据
    const permResult = await queryTenantPermission({ tenantId: unref(tenantId) });
    checkedKeys.value = permResult.checked;
    halfCheckedKeys.value = permResult.halfChecked;
    defaultCheckedKeys.value = permResult.checked;
    treeRef.value.expandAll(false);
    setDrawerProps({ loading: false });
  });
  /**
   * 点击选中更新keys
   */
  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], tenantId: unref(tenantId) });
  }
  /**
   * 数据重置
   */
  function reset() {
    treeData.value = [];
    checkedKeys.value = [];
    halfCheckedKeys.value = [];
    defaultCheckedKeys.value = [];
    selectedKeys.value = [];
    tenantId.value = '';
    checkStrictly.value = false;
  }
  /**
   * 获取tree实例
   */
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  /**
   * 提交
   */
  async function handleSubmit(exit) {
    let params = {
      tenantId: unref(tenantId),
      checkedIds: unref(getTree().getCheckedKeys()).concat(unref(halfCheckedKeys)),
      halfCheckedIds: unref(halfCheckedKeys)
    };
    loading.value = true;
    let result = await saveTenantPermission(params);
    loading.value = false;
    exit && closeDrawer();
    send(JSON.parse(result));
  }

  function send(e) {
    openSuccessModel(true, {
      username: e.username,
      password: e.password
    });
  }
</script>

<style lang="less" scoped>
  /** 固定操作按钮 */
  .jeecg-basic-tree {
    position: absolute;
    width: 618px;
  }
</style>
