<template>
  <Spin :spinning="loading">
    <BasicTree
      ref="basicTree"
      class="depart-rule-tree"
      checkable
      :treeData="treeData"
      :checkedKeys="checkedKeys"
      :selectedKeys="selectedKeys"
      :expandedKeys="expandedKeys"
      :checkStrictly="checkStrictly"
      style="height: 688px; width: 834px;overflow: auto"
      :style="{ height, overflow: 'auto' }"
      @check="onCheck"
      @expand="onExpand"
      @strictly-change="onStrictlyChange"
    >
      <template #title="{ slotTitle }">
        <span>{{ slotTitle }}</span>
      </template>
    </BasicTree>

    <div class="j-box-bottom-button offset-20">
      <div class="j-box-bottom-button-float" :class="[`${prefixCls}`]" style="right: 0; left: 0">
        <Dropdown :trigger="['click']" placement="top">
          <template #overlay>
            <Menu>
              <MenuItem key="3" @click="toggleCheckALL(true)">全部勾选</MenuItem>
              <MenuItem key="4" @click="toggleCheckALL(false)">取消全选</MenuItem>
              <MenuItem key="5" @click="toggleExpandAll(true)">展开所有</MenuItem>
              <MenuItem key="6" @click="toggleExpandAll(false)">收起所有</MenuItem>
            </Menu>
          </template>
          <c-button style="float: left">
            树操作
            <Icon icon="ant-design:up-outlined" />
          </c-button>
        </Dropdown>
        <c-button
          v-show="hasPermission('system:depart:auth')"
          type="primary"
          preIcon="ant-design:save-filled"
          @click="onSubmit"
          >保存</c-button
        >
      </div>
    </div>
  </Spin>
</template>
<script lang="ts" setup>
  import { ref, unref, nextTick, watch } from 'vue';
  import { BasicTree } from '@jdlinker/ui';
  import { usePermission } from '@jdlinker/func';
  import { useDesign } from '@jdlinker/func';
  import { queryRolePermission, queryTreeListForRole, saveRolePermission } from '../role/role.api';
  import {
    queryDepartPermission,
    queryRoleTreeList,
    saveDepartPermission,
    saveDeptRolePermission
  } from '../depart/depart.api';
  import { onlyMessage } from '@jdlinker/utils';
  import { queryDeptRolePermission, queryTreeListForDeptRole } from '../departUser/depart.user.api';
  import { Spin, Dropdown, Menu } from 'ant-design-vue';

  const { prefixCls } = useDesign('j-depart-form-content');
  const { hasPermission } = usePermission();
  const props = defineProps({
    data: { type: Object, default: () => ({}) },
    height: { type: String, default: '688px' }
  });
  // dataId 表示角色id、部门id、部门角色id
  const dataId = ref();
  const departId = ref();
  const basicTree = ref();
  const loading = ref<boolean>(false);
  const treeData = ref<any[]>([]);
  const expandedKeys = ref<Array<any>>([]);
  const selectedKeys = ref<Array<any>>([]);
  const checkedKeys = ref<Array<any>>([]);
  const halfCheckedKeys = ref<Array<any>>([]);
  const checkStrictly = ref(false);
  const emit = defineEmits(['successPerm']);

  async function onSubmit() {
    try {
      if (!loading.value) {
        loading.value = true;
        if (props.data?.roleId) {
          await saveRolePerm();
          emit('successPerm', { roleId: props.data?.roleId });
        } else if (props.data?.id) {
          await saveDepartPerm();
          emit('successPerm', unref(dataId));
        } else if (props.data?.departRoleId) {
          await saveDepartRolePerm();
          emit('successPerm', { departRoleId: props.data?.departRoleId });
        }
      } else {
        console.log('请等待上次执行完毕!');
      }
    } finally {
      loading.value = false;
    }
  }
  // 保存角色权限
  const saveRolePerm = async () => {
    const params = {
      roleId: unref(dataId),
      checkedIds: unref(checkedKeys),
      halfCheckedIds: unref(halfCheckedKeys)
    };
    const saveRes = await saveRolePermission(params);
    const permResult = await queryRolePermission({ roleId: unref(dataId) });
    halfCheckedKeys.value = permResult.halfChecked;
    if (saveRes?.success) {
      onlyMessage('保存成功', 'success');
    }
  };
  // 保存部门权限
  const saveDepartPerm = async () => {
    const params = {
      departId: unref(dataId),
      checkedIds: unref(checkedKeys),
      halfCheckedIds: unref(halfCheckedKeys)
    };
    const saveRes = await saveDepartPermission(params);
    const permResult = await queryDepartPermission({ departId: unref(dataId) });
    halfCheckedKeys.value = permResult.halfChecked;
    if (saveRes?.success) {
      onlyMessage('保存成功', 'success');
    }
  };

  // 保存部门角色权限
  const saveDepartRolePerm = async () => {
    const params = {
      roleId: unref(dataId),
      checkedIds: unref(checkedKeys),
      halfCheckedIds: unref(halfCheckedKeys)
    };
    const saveRes = await saveDeptRolePermission(params);
    const permResult = await queryDeptRolePermission({ roleId: unref(dataId) });
    halfCheckedKeys.value = permResult.halfChecked;
    if (saveRes?.success) {
      onlyMessage('保存成功', 'success');
    }
  };

  // tree勾选复选框事件
  function onCheck(o, e) {
    checkedKeys.value = o.checked ? o.checked : o;
    halfCheckedKeys.value = e.halfCheckedKeys;
  }

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

  // tree展开事件
  function onExpand($expandedKeys) {
    expandedKeys.value = $expandedKeys;
  }

  // 切换展开收起
  async function toggleExpandAll(flag) {
    basicTree.value.expandAll(flag);
    await nextTick();
    expandedKeys.value = basicTree.value.getExpandedKeys();
  }

  // 切换全选
  async function toggleCheckALL(flag) {
    basicTree.value.checkAll(flag);
    await nextTick();
    checkedKeys.value = basicTree.value.getCheckedKeys();
  }

  // 加载角色菜单树
  async function loadRoleData() {
    try {
      loading.value = true;
      //初始化数据
      const roleResult = await queryTreeListForRole();
      treeData.value = roleResult.treeList;
      //初始化角色菜单数据
      const permResult = await queryRolePermission({ roleId: unref(dataId) });
      checkedKeys.value = permResult.checked;
      halfCheckedKeys.value = permResult.halfChecked;
    } finally {
      loading.value = false;
      await toggleExpandAll(false);
    }
  }
  // 加载部门菜单树
  async function loadDeptData() {
    try {
      loading.value = true;
      //初始化数据
      const { treeList } = await queryRoleTreeList();
      treeData.value = treeList;
      //初始化部门菜单数据
      const permResult = await queryDepartPermission({ departId: unref(dataId) });
      checkedKeys.value = permResult.checked;
      halfCheckedKeys.value = permResult.halfChecked;
    } finally {
      loading.value = false;
      await toggleExpandAll(false);
    }
  }

  async function loadDeptRoleData() {
    try {
      loading.value = true;
      // 用户角色授权功能，查询菜单权限树
      const { treeList } = await queryTreeListForDeptRole({ departId: unref(departId) });
      treeData.value = treeList;
      // 查询角色授权
      const permResult = await queryDeptRolePermission({ roleId: unref(dataId) });
      checkedKeys.value = permResult.checked;
      halfCheckedKeys.value = permResult.halfChecked;
    } finally {
      loading.value = false;
      await toggleExpandAll(false);
    }
  }
  watch(
    () => props.data,
    () => {
      if (props.data?.roleId) {
        dataId.value = props.data?.roleId;
        loadRoleData();
      } else if (props.data?.id) {
        dataId.value = props.data?.id;
        loadDeptData();
      } else if (props.data?.departRoleId) {
        dataId.value = props.data?.departRoleId;
        departId.value = props.data?.departId;
        loadDeptRoleData();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
  // 【VUEN-188】解决滚动条不灵敏的问题
  .depart-rule-tree :deep(.scrollbar__bar) {
    pointer-events: none;
  }
  .ant-empty-normal {
    margin: 430px 0;
  }
</style>
