<template>
  <BasicDrawer
    title="部门角色权限配置"
    :width="650"
    :loading="loading"
    :showFooter="showFooter"
    okText="保存并关闭"
    @ok="onSubmit(true)"
    @close="onClose"
    @register="registerDrawer"
  >
    <div>
      <Spin :spinning="loading">
        <template v-if="treeData.length > 0">
          <BasicTree
            title="所拥有的部门权限"
            ref="treeRef"
            toolbar
            checkable
            :treeData="treeData"
            :checkedKeys="checkedKeys"
            :selectedKeys="selectedKeys"
            :checkStrictly="checkStrictly"
            :clickRowToExpand="false"
            @check="onCheck"
            @select="onSelect"
            @strictly-change="onStrictlyChange"
          >
            <template #title="{ slotTitle, ruleFlag }">
              <span>{{ slotTitle }}</span>
              <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
            </template>
          </BasicTree>
        </template>
        <Empty v-else description="无可配置部门权限" />
      </Spin>
    </div>

    <template #centerFooter>
      <c-button type="primary" :loading="loading" ghost @click="onSubmit(false)">仅保存</c-button>
    </template>
  </BasicDrawer>
  <DepartRoleDataRuleDrawer @register="registerDataRuleDrawer" />
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner, Button as CButton, BasicTree } from '@jdlinker/ui';
  import DepartRoleDataRuleDrawer from './DepartRoleDataRuleDrawer.vue';
  import { queryTreeListForDeptRole, queryDeptRolePermission, saveDeptRolePermission } from '../depart.user.api';
  import { Empty, Spin } from 'ant-design-vue';

  defineEmits(['register']);
  const showFooter = ref(true);
  const treeRef = ref<any>(null);
  const loading = ref(false);
  const departId = ref('');
  const roleId = ref('');
  const treeData = ref<Array<any>>([]);
  const checkedKeys = ref<Array<any>>([]);
  const halfCheckedKeys = ref([]);
  const selectedKeys = ref<Array<any>>([]);
  const allTreeKeys = ref<Array<any>>([]);
  const checkStrictly = ref(false);

  // 注册抽屉组件
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, showFooter: unref(showFooter) });
    roleId.value = data.record.id;
    departId.value = data.record.departId;
    await loadData();
  });
  // 注册数据规则授权弹窗抽屉
  const [registerDataRuleDrawer, dataRuleDrawer] = useDrawer();

  async function loadData() {
    try {
      loading.value = true;
      // 用户角色授权功能，查询菜单权限树
      const { ids, treeList } = await queryTreeListForDeptRole({ departId: unref(departId) });
      if (ids.length > 0) {
        allTreeKeys.value = ids;
        treeData.value = treeList;
        // 查询角色授权
        const permResult = await queryDeptRolePermission({ roleId: unref(roleId) });
        checkedKeys.value = permResult.checked;
        halfCheckedKeys.value = permResult.halfChecked;
      } else {
        reset();
      }
    } finally {
      loading.value = false;
    }
  }

  // 重置页面
  function reset() {
    treeData.value = [];
    halfCheckedKeys.value = [];
    checkedKeys.value = [];
    loading.value = false;
  }

  function onCheck(o, e) {
    checkedKeys.value = o.checked ? o.checked : o;
    halfCheckedKeys.value = e.halfCheckedKeys;
  }

  /**
   * 切换层级关联/层级独立
   */
  function onStrictlyChange(v) {
    checkStrictly.value = v;
  }

  // tree选中事件
  function onSelect($selectedKeys, { selectedNodes }) {
    if (selectedNodes[0]?.ruleFlag) {
      let functionId = $selectedKeys[0];
      dataRuleDrawer.openDrawer(true, { roleId, departId, functionId });
    }
    selectedKeys.value = [];
  }

  function doClose() {
    reset();
    closeDrawer();
  }

  function onClose() {
    reset();
  }

  async function onSubmit(exit) {
    try {
      loading.value = true;
      let params = {
        roleId: unref(roleId),
        checkedIds: unref(checkedKeys),
        halfCheckedIds: unref(halfCheckedKeys)
      };
      await saveDeptRolePermission(params);
      if (exit) {
        doClose();
      }
    } finally {
      loading.value = false;
      if (!exit) {
        loadData();
      }
    }
  }
</script>

<style lang="less" scoped>
  :deep(.ant-tree .ant-tree-treenode) {
    padding: 0 0 1px 0;
  }
</style>
