<template>
  <div class="main-content main-content-padding flex-content" id="AdminGroupManagement">
    <h-card class="margin-right width-fixed no-card-head list-tree">
      <h-b-tree
        id="AdminGroupManagement-queryTree"
        ref="treeRef"
        v-bind="props"
        v-model:selectedKeys="props.selectedKeys"
        v-model:expandedKeys="props.expandedKeys"
        :show-line="false"
        :show-header="true"
        :show-tool-bar="false"
        :asyncQuery="true"
        :display-format="displayFormat"
        :fieldNames="{ title: 'title', key: 'value1' }"
        :is-scroll-x="true"
        close-icon="PlusSquareOutlined"
        open-icon="MinusSquareOutlined"
        @select="selectOrg"
        :useUniqueKey="true"
        :height="700"
      ></h-b-tree>
    </h-card>
    <div class="main-content-item-right width-computed">
      <h-card class="list-tab-box margin-bottom" v-if="tabData?.items?.length">
        <h-tabs
          v-model:activeKey="tabData.activeKey"
          @tabClick="onTabClick"
          id="AdminGroupManagement-queryTabs"
        >
          <h-tab-pane
            v-for="item in tabData?.items"
            :key="item.key"
            :tab="item.locale ? t(item.locale) : item.tab"
          ></h-tab-pane>
          <template #rightExtra>
            <h-space>
              <h-switch
                id="AdminGroupManagement-querySwitch"
                v-model:checked="checked"
                @click="changeSwitch"
              />
              <!-- :checked-children="t('admingroupmanagement.common.yes')"
                :un-checked-children="t('admingroupmanagement.common.no')" -->
              <span>{{ t('admingroupmanagement.common.querySwitch') }}</span>
            </h-space>
          </template>
        </h-tabs>
      </h-card>
      <template v-if="components[tabData.activeKey] && provideData.value1">
        <component
          :is="components[tabData.activeKey]"
          :active-key="tabData.activeKey"
          :props-data="provideData"
          @refreshNode="refreshNodeChildren"
        ></component>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, provide, reactive, onMounted, computed } from 'vue';
import { useTree } from '@crami/bui-platform';
import {
  getInfo,
  ICP_CONFIG,
  PAGE_DATA_PROVIDE_SYMBOL,
  PAGE_PARAMS_PROVIDE_SYMBOL,
  getPageLinksData,
  NoAuthPage,
} from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
/* import { PAGE_DATA_PROVIDE_SYMBOL, PAGE_PARAMS_PROVIDE_SYMBOL } from '@/utils/usePageData'; */
import { getByProjectAndType } from '@/api/platform/orgStructure/adminGroup';
import components from './index';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { message } from '@crami/ui';
import { useI18n } from '@crami/locale';
/* import { getPageLinksData, NoAuthPage } from '@/utils/hasPermissionUtil'; */

export default defineComponent({
  name: 'AdminGroupManagement',
  setup() {
    const { t } = useI18n();
    // 左侧树相关
    const inputData = ref('');
    const searchTree = data => {
      (treeRef.value as any).searchText(data.value);
    };

    const checked = ref(true);
    const changeSwitch = bool => {
      switchData.value = { checked: bool };
    };
    //树相关

    let treeViewName = ref('');
    let paramsData: any = ref({ treeView: '', link: {}, page: {}, menu: {} });

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

    onMounted(() => {
      getByProjectAndTypeFun();
    });
    //获取treeViewName
    const getByProjectAndTypeFun = () => {
      getByProjectAndType({
        ...commonApi().studioCache.getMetaInfo.params,
        type: 'tree',
        name: 'P_SYS_DEPT_TREE', //commonParams.value?.ItemName,
      }).then(res => {
        if (res.code == 200) {
          treeViewName.value = res.data?.treeView;
          paramsData.value = res.data || {};
          const links = res.data?.link;
          Object.keys(links).forEach(item => {
            if (getPageLinksData(links[item])?.pageLinkList?.length) {
              paramsData.value.link[item] = getPageLinksData(links[item]);
            } else {
              delete paramsData.value.link[item];
            }
          });
          components['Empty'] = NoAuthPage;
          methods.refresh().then(() => {
            methods.defaultHandle();
          });
        } else {
          message.warning(res.msg);
        }
      });
    };
    //控制显示内容
    const displayFormat = function (data: any) {
      return data.title;
    };
    //获取显示内容

    const [treeRef, props, methods] = useTree({
      //immediate:false,
      pageName: 'AdminGroupManagement',
      treeDataApi: {
        url: commonApi().system.getGetTreeRootDataList.url,
        method: commonApi().system.getGetTreeRootDataList.method,
        params: commonApi().system.getGetTreeRootDataList.params,
      },
      treeChildrenDataApi: {
        url: commonApi().system.getGetTreeChildDataList.url,
        method: commonApi().system.getGetTreeChildDataList.method,
        params: commonApi().system.getGetTreeChildDataList.params,
      },
      // asyncQueryApi: {
      //   url: 'http://10.0.59.229:7300/mock/622ff143ec91f63c580c0560/api/system/view/data',
      //   method: 'get',
      //   params: {
      //     type: 'query',
      //   },
      // },
      immediate: false,
      beforeRequest: (params: any) => {
        return {
          ...params,
          treeViewName: treeViewName.value,
        };
      },
      beforeRequestChildren: (params: any, node: any) => {
        return {
          ...params,
          key: node.key,
          value1: node.value1,
          value2: node.value2,
          value3: node.value3,
          value4: node.value4,
          value5: node.value5,
          value6: node.value6,
          treeViewName: treeViewName.value,
        };
      },
      afterRequest: (data: any) => {
        return data;
      },
    });
    // tab栏相关
    const tabData = reactive({
      activeKey: '',
      items: [],
    });
    const onTabClick = (activeKey: string) => {
      tabData.activeKey = activeKey;
      pageCommonParams.value = getPageParams(
        paramsData.value,
        provideData.value.value3,
        tabData.activeKey,
      );
      provideData.value = Object.assign({}, provideData.value, pageCommonParams.value);
    };
    const switchData = ref({
      checked: true,
    });
    provide('isDirect', switchData);

    // 解析pageLink
    const analyPageLink = (list: any[]) => {
      const items: any[] = list.map(v => {
        return {
          key: v.pageName,
          tab: v.name,
          // TODO: 多语言需要调用getDynamicLocale方法,暂时先取名称
          locale: v.name, //locale: v.locale,
          closable: false,
        };
      });
      return items;
    };
    const setPageLink = (node: any) => {
      const key = node.value3 || '';
      // 通过value3获取在link中的键值
      const linkKey = paramsData.value.page[key] || '';
      const linkObj: { pageLinkList: any[] } = paramsData.value.link[linkKey] || {
        pageLinkList: [],
      };
      const items = analyPageLink(linkObj.pageLinkList);
      tabData!.items = items;
      if (tabData?.activeKey.length == 0 && items?.length) {
        tabData!.activeKey = items[0].key;
      }

      if (items?.length == 0) {
        tabData.activeKey = 'Empty';
      }
    };

    const selectType = ref('');
    let provideData = ref({});
    const pageCommonParams = ref({});

    provide(PAGE_DATA_PROVIDE_SYMBOL, provideData);
    provide(PAGE_PARAMS_PROVIDE_SYMBOL, pageCommonParams);
    //选择组织
    const selectOrg = (data: any, e: any) => {
      const node: any = e.node.dataRef;
      setPageLink(node);
      pageCommonParams.value = getPageParams(paramsData.value, node.value3, tabData.activeKey);
      provideData.value = { ...node, ...pageCommonParams.value };
      console.log(pageCommonParams.value);
    };
    const getPageParams = (data = { page: any, link: any }, value = '', activeKey = '') => {
      console.log(activeKey);

      const page = data?.page[value.toLocaleUpperCase()];
      if (page && data?.link[page]) {
        let index = data.link[page].pageLinkList.findIndex(item => item.pageName == activeKey);
        console.log(index);
        // 获取表格的公参（listViewName, menuName）
        const _params = {};
        const paraList = data.link[page]?.pageLinkList[index]?.paraList || [];
        selectType.value = data.link[page]?.pageLinkList[index]?.pageName;
        paraList &&
          paraList.map(item => {
            _params[item.name] = item.value;
          });
        return _params;
      }
      return {};
    };

    const refreshNodeChildren = () => {
      // methods.refresh().then(() => {
      //   console.log('刷新树了');
      // });
      const datas = provideData.value;
      datas && methods.asyncUpdateNode(datas, false);
    };
    return {
      t,
      inputData,
      searchTree,
      treeRef,
      props,
      methods,
      checked,
      displayFormat,
      selectOrg,
      onTabClick,
      provideData,
      selectType,
      components,
      tabData,
      refreshNodeChildren,
      changeSwitch,
      commonParams,
    };
  },
});
</script>

<style lang="less" scoped></style>
