<template>
  <!--功能权限、数据权限-->
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="角色权限配置" width="650px" destroyOnClose showFooter>
    <Tabs defaultActiveKey="permission">
      <TabPane tab="功能权限" key="permission" forceRender>
        <RolePermission :data="permissionData" @successPerm="loadRuleData" />
      </TabPane>
      <TabPane tab="数据权限" key="dataPermission" forceRender>
        <CollapseContainer v-if="tree.length > 0" title="数据规则" :canExpan="false">
          <RoleTreeCheckbox :tree="tree" :height="ruleHeight" />
        </CollapseContainer>
        <CollapseContainer v-if="dataScope" title="数据范围" :canExpan="false">
          <RoleDataScopeMenu :dataScope="dataScope" :height="scopeHeight" :sourceId="sourceId" @success="loadRules" />
        </CollapseContainer>
        <div class="j-box-bottom-button offset-20">
          <div class="j-box-bottom-button-float" :class="[`${prefixCls}`]" style="right: 0; left: 0">
            <c-button type="primary" preIcon="ant-design:save-filled" @click="onSubmit">保存</c-button>
          </div>
        </div>
      </TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, watch, unref } from 'vue';
  import { BasicDrawer, useDrawerInner, Button as CButton, CollapseContainer } from '@jdlinker/ui';
  import RolePermission from './RolePermission.vue';
  import RoleDataScopeMenu from './RoleTree/RoleDataScopeMenu.vue';
  import RoleTreeCheckbox from './RoleTree/RoleTreeCheckbox.vue';
  import _ from 'lodash-es';
  import {
    queryRules,
    queryTreeRoleListForRole,
    queryTreeRuleListForDepartRole,
    saveRoleRule,
    saveDepartRoleRule
  } from './role.api';
  import { onlyMessage } from '@jdlinker/utils';
  import { prefixCls, useRoleStore } from '@jdlinker/func';
  import { Tabs, TabPane } from 'ant-design-vue';

  const roleStore = useRoleStore();
  const permissionData = ref<any>({});
  const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false, loading: true });
    permissionData.value = data;
    setDrawerProps({ loading: false });
  });
  const tree = ref<any>([]);
  const ruleHeight = ref<string>('416px');
  const scopeHeight = ref<string>('222px');
  const sourceId = ref();
  const dataScope = ref([]);
  async function loadRoleData(roleId) {
    const roleResult = await queryTreeRoleListForRole({ roleId: roleId });
    tree.value = roleResult.treeList || [];
    roleStore.initCheckedData(roleResult.drChecked || []);
    roleStore.initTreeMap(roleResult.treeList || [], permissionData.value.type);
    await loadRules();
  }

  async function loadDepartRoleData(roleId) {
    console.log('loadDepartRoleData...', roleId);
    const roleResult = await queryTreeRuleListForDepartRole({ roleId: roleId });
    tree.value = roleResult.treeList || [];
    roleStore.initCheckedData(roleResult.drChecked || []);
    roleStore.initTreeMap(roleResult.treeList, permissionData.value.type);
    await loadRules();
  }

  async function loadRuleData(data) {
    if (data?.roleId) {
      await loadRoleData(data?.roleId);
    } else if (data?.departRoleId) {
      loadDepartRoleData(data?.departRoleId);
    }
  }

  watch(
    () => permissionData.value,
    (e: any) => {
      console.log('watch...departRoleId', permissionData.value);
      if (e?.roleId) {
        loadRoleData(e?.roleId);
        sourceId.value = e?.roleId;
      } else if (e?.departRoleId) {
        permissionData.value.departRoleId = e?.departRoleId;
        loadDepartRoleData(e?.departRoleId);
        sourceId.value = e?.departRoleId;
      }
    },
    { immediate: true }
  );

  async function onSubmit() {
    console.log('onSubmit', permissionData.value);
    const checkedData = roleStore.checkedData;
    if (_.isEmpty(checkedData)) {
      onlyMessage('请注意，现未勾选任何数据权限!', 'error');
      return;
    }
    const params = {
      roleId: unref(sourceId),
      dataRuleIds: checkedData,
      lastCheckedData: roleStore.lastCheckedData
    };
    try {
      if (permissionData.value.roleId) {
        await saveRoleRule(params);
      } else if (permissionData.value.departRoleId) {
        await saveDepartRoleRule(params);
      }
      onlyMessage('保存成功', 'success');
    } catch (error) {
      console.log(error);
    }
  }

  const loadRules = async () => {
    console.log('loadRules....');
    dataScope.value =
      (await queryRules({
        ruleType: 1,
        expandRoleType: permissionData.value.type,
        sourceId: unref(sourceId)
      })) || [];
  };
</script>

<style lang="less" scoped>
  :deep(.ant-tabs-nav) {
    margin: 0;
  }
  :deep(.p-2) {
    padding: 0 0.5rem;
  }
</style>
