<template>
  <div class="main-content main-content-padding flex-content" id="AuthIndex">
    <!-- 授权主体 -->
    <h-card
      class="platform-authmanage-box platform-authmanage-left margin-right list-tree has-card-head"
    >
      <template #title>
        {{ t('authManage.authBody') }}
        <h-tooltip placement="right" id="AuthIndex-tooltip">
          <template #title>
            <span v-html="t('authManage.authBodyTip')"></span>
          </template>
          <ExclamationCircleOutlined class="exclamation-icon" />
        </h-tooltip>
      </template>
      <h-tabs class="authmanage-tabs" v-model:activeKey="authActiveKey" id="AuthIndex-queryTabs">
        <!-- TODO: 先去掉多语言-->
        <!-- <h-tab-pane
          v-for="item in authObject"
          :key="item.uniqueKey"
          :tab="item.locale ? t(item.locale) : item.name"
        >
          <object-tree-node
            :paraList="handleData(item.paraList)"
            :name="item.locale ? t(item.locale) : item.name"
            @objectSelectTree="objectSelectTree"
          />
        </h-tab-pane> -->
        <h-tab-pane v-for="item in authObject" :key="item.uniqueKey" :tab="item.name">
          <object-tree-node
            :paraList="handleData(item.paraList)"
            :name="item.name"
            @objectSelectTree="objectSelectTree"
          />
        </h-tab-pane>
      </h-tabs>
    </h-card>
    <!-- 授权应用 -->
    <h-card
      class="platform-authmanage-box platform-authmanage-center margin-right list-tree has-card-head"
      :title="t('authManage.authApp')"
    >
      <div class="appList-box">
        <h-b-card-pane
          id="AuthIndex-cardPane"
          v-bind="cardPaneProps"
          v-model:value="selectData.appId"
          ref="cardPaneRef"
          :ellipsis="true"
          row-key="EID"
          show-key="ENAME"
          @change="selectApp"
        ></h-b-card-pane>
      </div>
    </h-card>
    <!-- 授权功能 -->
    <h-card
      class="platform-authmanage-box platform-authmanage-right list-tree has-card-head"
      :title="t('authManage.authFun')"
    >
      <h-tabs
        class="authmanage-tabs"
        v-model:activeKey="selectData.permissionType"
        id="AuthIndex-selectTabs"
        :destroyInactiveTabPane="true"
      >
        <!-- TODO: 先去掉多语言-->
        <!-- <h-tab-pane
          v-for="item in authFunData"
          :key="item.uniqueKey"
          :tab="item.locale ? t(item.locale) : item.name"
        > -->
        <h-tab-pane v-for="item in authFunData" :key="item.uniqueKey" :tab="item.name">
          <template v-if="selectData?.objectId && selectData?.appId">
            <auth-page />
          </template>
          <template v-else>
            <h-empty class="platform-empty" :image="simpleImage" />
          </template>
        </h-tab-pane>
      </h-tabs>
    </h-card>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, watch, provide, computed } from 'vue';
import { useHttp } from '@crami/http';
import ObjectTreeNode from './ObjectTreeNode.vue';
import AuthPage from './AuthPage.vue';
import { Empty } from '@crami/ui';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { useCardPane } from '@crami/bui-platform';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'AuthIndex',
  components: { ObjectTreeNode, AuthPage },
  setup() {
    const { t } = useI18n();
    const simpleImage = ref(Empty.PRESENTED_IMAGE_SIMPLE);
    // 授权主体当前选中值
    const authActiveKey = ref('');
    // 授权主体数据
    const authObject: any = ref('');
    onMounted(() => {
      getAuthObjectTabs();
      // getAuthorizationFun();
    });

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    // 获取授权主体link tab
    const getAuthObjectTabs = () => {
      useHttp({
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          name: 'P_SYS_MPERMISSION_LINKS',
          // name: commonParams.value?.LinksName,
          type: 'pageLinks',
        },
        method: commonApi().studioCache.getMetaInfo.method,
      }).then(res => {
        if (res.code == 200 && res.data?.pageLinkList?.length > 0) {
          authObject.value = res.data?.pageLinkList.filter(item => !item.isHidden) || [];
          const selectedData = authObject.value?.filter(item => item.isSelected) || [];
          authActiveKey.value = selectedData[0]?.uniqueKey || authObject.value[0]?.uniqueKey || '';
        }
      });
    };

    // 授权主体数据
    const authFunData: any = ref('');
    // 获取授权功能link tab数据
    const getAuthorizationFun = name => {
      useHttp({
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          name: 'P_SYS_MPERMISSION_TYPE',
          // name: name,
          type: 'pageLinks',
        },
        method: commonApi().studioCache.getMetaInfo.method,
      }).then(res => {
        if (res.code == 200 && res.data?.pageLinkList?.length > 0) {
          authFunData.value = res.data?.pageLinkList.filter(item => !item.isHidden) || [];
          const selectedData = authFunData.value?.filter(item => item.isSelected) || [];
          selectData.permissionType =
            selectedData[0]?.uniqueKey || authFunData.value[0]?.uniqueKey || '';
        }
      });
    };

    // 授权已选中数据和授权应用选中数据
    const selectData = reactive({
      objectId: '',
      appId: '',
      appName: '',
      permissionType: '',
      project: '',
    });

    // 授权主题所以所有类型下选中的数据
    const selectAllData = ref({});

    // 授权主体触发节点选中事件
    const objectSelectTree = data => {
      const node = data?.node?.dataRef;
      if (data.selected) {
        selectData.objectId = node?.value1;
        selectAllData.value[authActiveKey.value] = node?.value1;
      } else {
        selectData.objectId = '';
        selectAllData.value[authActiveKey.value] = '';
      }
    };

    // 监听授权主体tab的变化更新当前选中节点数据
    watch(
      () => authActiveKey.value,
      () => {
        if (authActiveKey.value) {
          selectData.objectId =
            (selectAllData.value && selectAllData.value[authActiveKey.value]) || '';
          authObject.value?.map(item => {
            if (item.uniqueKey == authActiveKey.value) {
              const paraList: any = handleData(item.paraList);
              paraList.PageLinkName && getAuthorizationFun(paraList.PageLinkName);
            }
          });
        }
      },
    );

    // 处理传递的参数
    const handleData = (data: any) => {
      let list = {};
      if (data && Object.keys(data)?.length > 0) {
        Object.keys(data)?.map(d => {
          list[data[d].name] = data[d].value;
        });
      }
      return list;
    };

    // 选择应用
    const selectApp = eid => {
      selectData.appId = eid;
      const dataSource = cardPaneProps?.dataSource || [];
      const currentData = dataSource?.filter(item => item.EID == eid);
      selectData.appName = currentData[0]?.ECODE;
      selectData.project = currentData[0]?.PROLINE;
    };

    provide('selectData', selectData);
    const y = new Date().getFullYear();
    const m = new Date().getMonth() + 1;
    const d = new Date().getDate();
    const paraList = {
      CompanyId: [commonParams.value?.companyId],
      Current_Time: [`${y}-${m > 9 ? m : '0' + m}-${d > 9 ? d : '0' + d}`],
    };
    const [cardPaneRef, cardPaneProps] = useCardPane({
      configApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        params: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: 'P_SYS_PER_APPLICATION_LISTVIEW', //commonParams.value?.listViewName,
          paraList: JSON.stringify(paraList),
          filter: [
            {
              andOrFlag: 'AND',
              field: 'APPSTATE',
              operation: '=',
              value: 'ON',
            },
          ],
        },
      },
    });

    return {
      t,
      commonParams,
      authObject,
      authActiveKey,
      simpleImage,
      authFunData,
      objectSelectTree,
      selectData,
      handleData,
      selectApp,
      cardPaneRef,
      cardPaneProps,
    };
  },
});
</script>

<style lang="less" scoped>
@import '@/theme/default/variables.less';
.platform-authmanage-left {
  width: 300px;
  height: calc(100vh - 156px);
  overflow: hidden;
}
.platform-authmanage-center {
  width: 240px;
  height: calc(100vh - 156px);
  // margin: 0 24px;
  .appList-box {
    margin-top: 20px;
    height: calc(100vh - 246px);
    overflow-y: auto;
  }
}
.platform-authmanage-right {
  width: calc(100% - 540px - @margin-right - @margin-right);
  height: calc(100vh - 156px);
  position: relative;
  overflow: hidden;
}
.platform-authmanage-left,
.platform-authmanage-right {
  :deep(.ant-tabs-top) {
    & > .ant-tabs-nav::before {
      border-bottom: none;
    }
    .ant-tabs-tab {
      padding: 16px 0;
    }
  }
}
.platform-authmanage-box {
  :deep(.ant-card-body) {
    padding: 0 20px;
  }
  :deep(.ant-tabs-nav) {
    margin-bottom: 20px;
  }
  .card-title {
    font-size: 16px;
    font-weight: 700;
    padding: 17px 0;
    margin-bottom: 0;
    line-height: 22px;
    border-bottom: 1px dotted @border-color-split;
    color: #000;
  }
  :deep(.crami-hbtree-header) {
    padding-top: 0px;
    margin-bottom: 14px;
  }
  .exclamation-icon {
    color: @normal-color;
    margin-left: 4px;
    // cursor: pointer;
    &:hover {
      color: @info-color;
    }
  }
  .platform-empty {
    // margin-top: 15%;
  }
}
</style>
