<template>
  <div class="main-content main-content-padding flex-content" id="Dict">
    <h-card class="margin-right width-fixed no-card-head list-tree">
      <h-b-tree
        ref="treeRef"
        v-bind="props"
        v-model:checkedKeys="props.checkedKeys"
        v-model:expandKeys="props.expandKeys"
        v-model:selectedKeys="props.selectedKeys"
        :checkable="state.checkable"
        :check-strictly="state.checkStrictly"
        :draggable="state.draggable"
        :show-header="state.showHeader"
        :show-search="state.showSearch"
        :show-tool-bar="state.showToolBar"
        :show-line="state.showLine"
        :display-format="displayFormat"
        :fieldNames="{ title: 'title', key: 'value1' }"
        :height="700"
        @select="select"
        close-icon="PlusSquareOutlined"
        open-icon="MinusSquareOutlined"
        id="Dict-queryTree"
      />
    </h-card>
    <template v-if="selectType">
      <component
        :is="getComponent()"
        ref="comRef"
        :propsData="provideData"
        @success="success"
      ></component>
    </template>
  </div>
</template>

<script lang="ts">
//暂定引入 最终确认使用那些
import {
  defineComponent,
  onMounted,
  ref,
  reactive,
  provide,
  defineAsyncComponent,
  computed,
} from 'vue';
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 { getPageLinksData, NoAuthPage } from '@/utils/hasPermissionUtil'; */

import { useTree } from '@crami/bui-platform';
import { message } from '@crami/ui';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

let modules: any = import.meta.glob('./*.vue');
modules &&
  Object.keys(modules).map(item => {
    modules[item] = defineAsyncComponent(modules[item]);
  });

export default defineComponent({
  name: 'Dict',
  setup: () => {
    const { t } = useI18n();
    const treeViewName = ref('');
    const paramsData: any = ref({});

    const displayFormat = function (data: any) {
      return data.title;
    };

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

    onMounted(() => {
      getByProjectAndTypeFun();
    });

    const getByProjectAndTypeFun = async () => {
      const res = await useHttp({
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'tree',
          // treeName: 'P_SYS_Enumerations',
          name: 'P_SYS_Enumerations', // commonParams.value?.ItemName,
        },
        method: commonApi().studioCache.getMetaInfo.method,
        url: commonApi().studioCache.getMetaInfo.url,
      }).then(({ code, data }) => {
        if (code == 200) {
          treeViewName.value = data?.treeView;
          paramsData.value = data || {};
          const links = data?.link;

          Object.keys(links).forEach(item => {
            console.log(getPageLinksData(links[item])?.pageLinkList?.length);
            if (getPageLinksData(links[item])?.pageLinkList?.length) {
              paramsData.value.link[item] = getPageLinksData(links[item]);
            } else {
              delete paramsData.value.link[item];
            }
          });

          modules.empty = NoAuthPage;

          methods.refresh().then(() => {
            methods.defaultHandle();
          });
        }
      });
    };

    const [treeRef, props, methods] = useTree({
      pageName: 'Dict',
      treeDataApi: {
        url: '/api/system/enum/getTreeRootDataList',
        // 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 => {
        return {
          ...params,
          treeViewName: treeViewName.value,
        };
      },
      afterRequest: (data: any) => {
        return methods.addIsLeaf(data);
      },
      // beforeRequestChildren: (params, node) => {
      //   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,
      //   };
      // },
    });

    const state = reactive({
      checkable: false,
      draggable: false,
      checkStrictly: false,
      showHeader: false,
      showToolBar: false,
      showSearch: false,
      showLine: false,
    });

    const selectType = ref('');
    const pageCommonParams = ref({});
    let provideData: any = ref({});
    // 树节点点击事件
    const select = (selectedKeys, data) => {
      if (selectedKeys?.length <= 0) return;
      const node = data?.node?.dataRef;

      // setPageLink(node);
      // 获取父节点
      const parentValue1 = treeRef.value.getParentNode(node);
      // 获取当前节点根节点
      const rootValue1 = treeRef.value.getRootNodeByNode(node);
      pageCommonParams.value = getPageParams(paramsData.value, node?.value3);
      provideData.value = {
        ...node,
        parentValue1: parentValue1?.value1,
        rootValue1: rootValue1?.value1,
      };
    };

    provide(PAGE_DATA_PROVIDE_SYMBOL, provideData);
    provide(PAGE_PARAMS_PROVIDE_SYMBOL, pageCommonParams);

    // 处理获取表格数据接口的公参包括listView和menuName
    const getPageParams = (data: any = [], value = '') => {
      const page = data?.page[value.toLocaleUpperCase()];
      let _params = {};

      if (page && data?.link[page]) {
        // 获取表格的公参（listViewName, menuName）
        const paraList = data.link[page]?.pageLinkList[0]?.paraList || [];
        selectType.value = data.link[page]?.pageLinkList[0]?.pageName;
        paraList &&
          paraList.map(item => {
            _params[item.name] = item.value;
          });
      } else {
        selectType.value = 'empty';
        _params = {};
      }
      return _params;
    };

    // 获取当前页面组件，通过defineAsyncComponent的方式引入
    const getComponent = () => {
      if (selectType.value && modules[selectType.value]) {
        const link = modules[selectType.value];
        return link;
      }
      return '';
    };
    const comRef = ref();
    // 操作成功，刷新树结构
    const success = () => {
      methods.refresh();
    };

    // // 处理右键事件前
    const beforeRightClick = async (data: any, node: any) => {
      const selectKeys = methods.getSelectedKeys();
      if (
        !selectKeys ||
        selectKeys.length <= 0 ||
        (provideData.value?.value1 && provideData.value?.value1 != node.value1)
      ) {
        methods.setSelectedData([node.value1]);
      }
      let key = node.value3;
      let name = paramsData.value.menu[key];
      if (name) {
        const res = await useHttp({
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'menuv2',
            name,
          },
          method: commonApi().studioCache.getMetaInfo.method,
          url: commonApi().studioCache.getMetaInfo.url,
        });

        if (res.code == 200) {
          data.items = res.data.items;
          data.items.map(element => {
            element['title'] = element.text;
            element['value'] = element.name;
            element.type = 'text';
          });
        } else {
          message.error(t('dictManage.treeRightErrorMsg'));
        }
      } else {
        data.items = [];
      }
      return data;
    };

    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        methods.refresh().then(() => {
          comRef.value?.refreshTable();
          setParentNode();
        });
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

    // 通过获取节点详情的方式获取到父级节点进行复制，此方法只适合二级的
    const setParentNode = async () => {
      if (!provideData.value?.value1) return;
      const source = await useHttp({
        params: {
          ...commonApi().system.getObjectDataTestList.params,
          objectID: provideData.value?.value1,
        },
        method: commonApi().system.getObjectDataTestList.method,
        url: commonApi().system.getObjectDataTestList.url,
      });
      if (source.code == 200 && source.data?.data && source.data?.data?.APPLICATION_ID) {
        provideData.value.parentValue1 = source.data?.data?.APPLICATION_ID;
      }
    };

    // 右键删除操作特殊处理
    // const newJsFunDel = (event: any) => {
    //   if (event.result?.code == 200) {
    //     message.success(event.result.msg);
    //     methods.refresh().then(() => {
    //       methods.cancelSelectedData();
    //       methods.defaultHandle();
    //     });
    //   } else {
    //     if (undefined == event?.result) {
    //       //TODO：后期可能会有处理
    //     } else {
    //       message.warning(event.result.msg);
    //     }
    //   }
    // };

    return {
      treeRef,
      props,
      state,
      displayFormat,
      treeViewName,
      select,
      getComponent,
      provideData,
      selectType,
      success,
      beforeRightClick,
      newJsFun,
      // newJsFunDel,
      comRef,
      commonParams,
    };
  },
});
</script>
<style lang="less" scoped>
.platform-dict-left {
  position: relative;
  width: 300px;
  margin-right: 20px;
  overflow: hidden;
  .platform-card-tree {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow-x: hidden;
    overflow-y: auto;
  }
}
.platform-dict-right {
  width: calc(100% - 320px);
}
</style>
