<template>
  <div class="main-content main-content-padding flex-content" id="CodeManagement">
    <h-card class="margin-right width-fixed list-tree has-card-head">
      <template #title @click="rootCodeClick">
        <div class="code-root" @click="rootCodeClick">
          {{ t('code.codeManagement.codeManagementTitle') }}
        </div>
      </template>
      <h-b-tree
        id="CodeManagement-queryTree"
        ref="treeRef"
        v-bind="props"
        :show-line="false"
        :show-header="false"
        :show-tool-bar="false"
        :asyncQuery="true"
        :show-search="false"
        :display-format="displayFormat"
        :fieldNames="{ title: 'title', key: 'value1' }"
        :is-scroll-x="true"
        @select="selectOrg"
      >
        <template #switcherIcon="{ switcherCls }">
          <caret-down-outlined :class="switcherCls" class="code-arrow-icon" />
        </template>
      </h-b-tree>
    </h-card>

    <div class="main-content-item-right width-computed">
      <template v-if="tabData.items.length">
        <h-card class="list-tab-box-has-content" id="CodeManagement-queryTabs-card">
          <h-tabs
            v-model:activeKey="tabData.activeKey"
            @tabClick="onTabClick"
            id="CodeManagement-queryTabs"
          >
            <h-tab-pane
              v-for="item in tabData.items"
              :key="item.key"
              :tab="t(`code.codeManagement.${item.key}`)"
            ></h-tab-pane>
          </h-tabs>
        </h-card>
      </template>

      <template v-if="components[tabData.activeKey]">
        <component
          :is="components[tabData.activeKey]"
          :activeKey="tabData.activeKey"
          :propsData="provideData"
          @refreshNode="refreshNodeChildren"
          @checkEvent="checkEvent"
          @setExpandEvent="setExpandEvent"
        ></component>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, provide } from 'vue';
import { useTree } from '@crami/bui-platform';
import { getByProjectAndType } from '@/api/platform/orgStructure/adminGroup';
import components from './index';
import { CaretDownOutlined } from '@ant-design/icons-vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi'; */
import { useI18n } from '@crami/locale';
import { registerComponents, getPageLinksData, NoAuthPage } from '@remote/icpx-platform/utils';
/* import { registerComponents } from '@/utils/componentUtils';
import { getPageLinksData, NoAuthPage } from '@/utils/hasPermissionUtil'; */

export default defineComponent({
  name: 'CodeManagement',
  components: {
    CaretDownOutlined,
  },
  setup() {
    // 左侧树相关
    const inputData = ref('');
    const searchTree = data => {
      (treeRef.value as any).searchText(data.value);
    };
    const expandSeg = {
      expand: false,
      key: '',
      eid: '',
    };
    const { t } = useI18n();
    const checked = ref(true);

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

    onMounted(() => {
      getByProjectAndTypeFun();

      const modules = import.meta.glob('./components/*.vue');
      registerComponents(modules);
    });
    //获取treeViewName
    const getByProjectAndTypeFun = () => {
      getByProjectAndType({
        ...commonApi().studioCache.getMetaInfo.params,
        type: 'tree',
        name: 'P_SYS_CODE_SCHEME_TREE',
      }).then(res => {
        if (res.code == 200) {
          treeViewName.value = res.data?.treeView;
          paramsData.value = res.data || {};
          const links = paramsData.value?.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();
          });
        }
      });
    };
    //控制显示内容
    const displayFormat = function (data: any) {
      return data.title;
    };
    //获取显示内容
    const [treeRef, props, methods] = useTree({
      //immediate:false,
      pageName: 'CodeManagement',
      defaultSelected: false,
      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,
      },
      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;
      },
      afterSetChildren: (data: any) => {
        if (expandSeg.expand) {
          expandSeg.expand = false;
          const linkKey = paramsData.value.page[expandSeg.key] || '';
          const linkObj: { pageLinkList: any[] } = paramsData.value.link[linkKey] || {
            pageLinkList: [],
          };
          const items = analyPageLink(linkObj.pageLinkList);
          tabData!.items = items;
          if (tabData?.activeKey && items.length && tabData.activeKey !== items[0].key) {
            tabData!.activeKey = items[0].key;
          } else if (!items.length) {
            tabData.activeKey = 'Empty';
          }
          pageCommonParams.value = getPageParams(
            paramsData.value,
            expandSeg.key,
            tabData.activeKey,
          );
          const nodeObj = {
            value1: expandSeg.eid,
          };
          provideData.value = { ...nodeObj, ...pageCommonParams.value };
          methods.setSelectedKeys([expandSeg.eid]);
        }
      },
      afterRequestChildren: (data: any) => {
        return data;
      },
    });
    // tab栏相关
    const tabData = reactive({
      activeKey: 'CodeProgramme',
      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);
    };

    // 解析pageLink
    const analyPageLink = (list: any[]) => {
      const items: any[] = list
        .sort((a, b) => parseInt(a.order || '1') - parseInt(b.order || '1'))
        .map(v => {
          return {
            key: v.pageName,
            tab: v.name,
            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 && items.length && tabData.activeKey !== items[0].key) {
        tabData!.activeKey = items[0].key;
      } else if (!items.length) {
        tabData.activeKey = 'Empty';
      }
    };

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

    const setExpandEvent = () => {};

    const orgId = ref();
    provide('orgId', orgId);

    //选择组织
    const selectOrg = (id: any, e: any) => {
      orgId.value = id?.[0];
      const node: any = e.node.dataRef;
      setPageLink(node);
      pageCommonParams.value = getPageParams(paramsData.value, node.value3, tabData.activeKey);
      provideData.value = { ...node, ...pageCommonParams.value };
    };
    const getPageParams = (data = { page: any, link: any }, value = '', activeKey = '') => {
      const page = data?.page[value.toLocaleUpperCase()];
      if (page && data?.link[page]) {
        let index = data.link[page].pageLinkList.findIndex(item => item.pageName == activeKey);
        // 获取表格的公参（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 rootCodeClick = () => {
      methods.cancelSelectedData();
      onTabClick('CodeProgramme');
      tabData.items = [];
    };

    const refreshNodeChildren = (event: any) => {
      const activeKey = tabData.activeKey;
      methods.refresh().then(() => {
        if (event) {
          methods.setSelectedKeys([event]);
          // 关联权限后编码方案新增、编辑后会走到这里重新设置选中的树节点，这个时候tab就改为默认选中的第一个了，应该还是要保持新增\编辑接口提交前的
          tabData.activeKey = activeKey;
        }
      });
    };
    const checkEvent = event => {
      const key = event.ObjectType || '';
      if (key === 'P_SYS_CODE_SEGMENT') {
        const schemeNode = methods.getNodeByKey(event.schemeId);
        if (schemeNode.children === undefined || schemeNode.children.length === 0) {
          const expandKeys = [].concat(treeRef.value.getExpandedKeys());
          const temps = new Set();
          for (let i = 0; i < expandKeys.length; i++) {
            const item = expandKeys[i];
            temps.add(item);
          }
          temps.add(schemeNode.value1);
          treeRef.value.setExpandNodes([...temps]);
          expandSeg.expand = true;
          expandSeg.key = key;
          expandSeg.eid = event.ObjectID.EID;
          return;
        }
      }
      // 通过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 && items.length && tabData.activeKey !== items[0].key) {
        tabData!.activeKey = items[0].key;
      } else if (!items.length) {
        tabData.activeKey = 'Empty';
      }
      pageCommonParams.value = getPageParams(paramsData.value, key, tabData.activeKey);
      const nodeObj = {
        value1: event.ObjectID.EID,
      };
      provideData.value = { ...nodeObj, ...pageCommonParams.value };
      methods.setSelectedKeys([event.ObjectID.EID]);
    };

    return {
      t,
      inputData,
      searchTree,
      treeRef,
      props,
      methods,
      checked,
      displayFormat,
      selectOrg,
      onTabClick,
      provideData,
      selectType,
      components,
      tabData,
      refreshNodeChildren,
      rootCodeClick,
      checkEvent,
      setExpandEvent,
    };
  },
});
</script>

<style lang="less" scoped>
.code-root {
  font-weight: bold;
  font-size: 16px;
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
  &:hover {
    cursor: pointer;
  }
  .codeRootName {
    padding-left: 24px;
    height: 100%;
  }
}

:deep(#CodeManagement-queryTabs-card) {
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
