<template>
  <PageWrapper :sidebarWidth="500">
    <template #sidebar>
      <DepartLeftTree ref="leftTree" @select="onTreeSelect" @root-tree-data="onRootTreeData" />
    </template>
    <div :class="[`${prefixCls}--col_div`]">
      <Tabs v-show="departData != null" defaultActiveKey="base-info">
        <TabPane tab="基本信息" key="base-info" forceRender>
          <DepartFormTab :data="departData" :rootTreeData="rootTreeData" @success="onSuccess" />
        </TabPane>
        <TabPane v-if="hasPermission('system:depart:authTab')" tab="部门权限" key="permission" forceRender>
          <RolePermission :data="departData" :height="height" @success-perm="loadData" />
        </TabPane>
        <TabPane tab="数据权限" key="dataPermission">
          <CollapseContainer v-if="tree.length > 0" title="数据规则" :canExpan="false">
            <RoleTreeCheckbox :tree="tree" :height="ruleHeight" :checkBoxWidth="checkBoxWidth" />
          </CollapseContainer>
          <CollapseContainer v-if="dataScope" title="数据范围" :canExpan="false">
            <RoleDataScopeMenu
              :dataScope="dataScope"
              :height="scopeHeight"
              :scopeWidth="scopeWidth"
              :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>
      <div v-show="departData == null" style="padding-top: 40px">
        <Empty description="尚未选择部门" />
      </div>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup name="system-depart">
  import { provide, ref, watch, unref } from 'vue';
  import { PageWrapper, CollapseContainer } from '@jdlinker/ui';
  import { useDesign, useRoleStore, usePermission } from '@jdlinker/func';
  import DepartLeftTree from './components/DepartLeftTree.vue';
  import DepartFormTab from './components/DepartFormTab.vue';
  import RolePermission from '../components/RolePermission.vue';
  import RoleTreeCheckbox from '../components/RoleTree/RoleTreeCheckbox.vue';
  import RoleDataScopeMenu from '../components/RoleTree/RoleDataScopeMenu.vue';
  import { queryRules, queryTreeRuleListForDepart, saveDepartRule } from '../components/role.api';
  import _ from 'lodash-es';
  import { onlyMessage } from '@jdlinker/utils';
  import { Empty, Tabs, TabPane } from 'ant-design-vue';

  const { hasPermission } = usePermission();
  const { prefixCls } = useDesign('depart-manage');

  provide('prefixCls', prefixCls);

  const roleStore = useRoleStore();
  const sourceId = ref();
  // 给子组件定义一个ref变量
  const leftTree = ref();
  const height = ref('640px');
  const checkBoxWidth = ref('810px');
  const scopeWidth = ref('672px');
  // 当前选中的部门信息
  const departData = ref<any>({});
  const rootTreeData = ref<any[]>([]);
  const tree = ref<any>([]);
  const dataScope = ref([]);
  const ruleHeight = ref<string>('390px');
  const scopeHeight = ref<string>('155px');
  // 左侧树选择后触发
  function onTreeSelect(data) {
    departData.value = data;
  }

  // 左侧树rootTreeData触发
  function onRootTreeData(data) {
    rootTreeData.value = data;
  }

  function onSuccess() {
    leftTree.value.loadRootTreeData();
  }

  async function loadData(departId) {
    const roleResult = await queryTreeRuleListForDepart({ departId: departId });
    tree.value = roleResult.treeList || [];
    roleStore.initCheckedData(roleResult.drChecked || []);
    roleStore.initTreeMap(roleResult.treeList || [], '2');
    await loadRules();
  }
  const loadRules = async () => {
    dataScope.value = await queryRules({ ruleType: 1, expandRoleType: 2, sourceId: unref(sourceId) });
  };

  watch(
    () => departData.value,
    (e: any) => {
      if (e?.id) {
        loadData(e?.id);
        sourceId.value = e?.id;
      }
    },
    { immediate: true }
  );

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

  // function tabChange(key: any) {
  //   if (key === 'permission') {
  //     // loadData(departData.value.id);
  //   } else if (key === 'dataPermission') {
  //     loadRules();
  //   }
  // }
</script>

<style lang="less" scoped>
  @import './index.less';
  :deep(.ant-tabs-nav-wrap) {
    padding-left: 15px;
  }
</style>
