<template>
  <div class="main-content main-content-padding flex-content" id="DataPermissionPolicy">
    <h-card class="margin-right width-fixed no-card-head list-tree">
      <h-b-tree
        ref="treeRef"
        v-bind="props"
        :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' }"
        query-type="local"
        @select="select"
        @clickRightMenuItem="rightClick"
        @clickMenuItem="clickMenuItem"
        @beforeRightClick="beforeRightClick"
        close-icon="PlusSquareOutlined"
        open-icon="MinusSquareOutlined"
        id="DataPermissionPolicy-queryTree"
        :is-scroll-x="true"
        :height="700"
      />
    </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,
  onBeforeUnmount,
  getCurrentInstance,
  createVNode,
  computed,
} from 'vue';
import {
  getInfo,
  ICP_CONFIG,
  PAGE_DATA_PROVIDE_SYMBOL,
  PAGE_PARAMS_PROVIDE_SYMBOL,
  bus,
} 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 bus from '@/utils/bus'; */
import { useTree } from '@crami/bui-platform';
import { HModal, message, Icon } 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: 'DataPermissionPolicy',
  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_DATAPER_TREE', //commonParams.value?.ItemName,
        },
        method: commonApi().studioCache.getMetaInfo.method,
        url: commonApi().studioCache.getMetaInfo.url,
      });
      if (res.code == 200) {
        treeViewName.value = res.data?.treeView;
        paramsData.value = res.data || {};
        methods.refresh().then(() => {
          methods.defaultHandle();
        });
      }
    };
    // const paraList = {
    //   loadAllStructure: false,
    //   lang: getInfo(ICP_CONFIG)?.lang,
    //   connect: getInfo(ICP_CONFIG)?.connect,
    //   companyId: getInfo(ICP_CONFIG)?.companyId,
    // };

    const [treeRef, props, methods] = useTree({
      pageName: 'DataPermissionPolicy',
      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 => {
        return {
          ...params,
          // treeViewName: 'P_SYS_TENANT_ORG_TREEVIEW',
          treeViewName: treeViewName.value,
        };
      },
      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,
        };
      },
      afterRequest: data => {
        // provideData.value?.value1 && methods.setSelectedData([provideData.value?.value1]);
        return data;
      },
    });

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

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

      // 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?.P_SYS_DATAPERMISSION;
      if (page && data?.link[page]) {
        // 获取表格的公参（listViewName, menuName）
        const _params = {};
        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;
          });
        return _params;
      }
      return {};
    };

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

    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        methods.refresh().then(() => {
          comRef.value?.refreshTable();
          setParentNode();
          methods.setSelectedData([selectedNode.value.value1]);
        });
      } 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 rightClick = function (item: any, node: any) {
      console.log('点击了右键rightClick', item, node);
    };
    const checkDelete = async (params: any) => {
      const data = await useHttp({
        url: '/api/dataperservice/customNode/checkDelete',
        method: 'post',
        params: params,
      });
      const resultData = data.data;
      return resultData;
    };
    const deletetTreeOrg = (params: any) => {
      const data = useHttp({
        url: '/api/system/model/deleteObjectData',
        method: 'post',
        params: params,
      });
      return data;
    };
    const confirm = data => {
      const eid = data.resultData[0].value1;
      HModal.confirm({
        closable: true,
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        title: t('platform.common.prompt'),
        content: t('platform.common.deleteMsg'),
        okText: t('platform.common.ok'),
        cancelText: t('platform.common.cancel'),
        class: 'data-permission-treenodedelete-modal',
        onOk() {
          const param = {
            EIDStr: [eid],
            companyId: commonParams.value?.companyId,
            connect: commonParams.value?.connect,
            lang: commonParams.value?.lang,
          };
          deletetTreeOrg(param).then(res => {
            if (res.code == 200) {
              message.success(res.msg);
              methods.asyncUpdateNode(methods.getParentNode(selectedNode.value));
              methods.setSelectedData([methods.getParentNode(selectedNode.value).value1]);
            } else {
              message.error(res.msg);
            }
          });

          // if (res.code == 200) {
          //   message.success(res.msg);
          //   treeMethods.asyncUpdateNode(treeMethods.getParentNode(selectedNode.value));
          // } else {
          //   message.error(res.msg);
          // }
        },
        onCancel() {
          HModal.destroyAll();
        },
      });
    };
    const deleteTreeData = async (data: any) => {
      const params = {
        objectId: data.resultData[0].value1,
        companyId: commonParams.value?.companyId,
        connect: commonParams.value?.connect,
      };
      const result = await checkDelete(params);
      if (result.result) {
        // 弹窗确认删除
        confirm(data);
      } else {
        message.warning(result.label);
      }
    };
    const instance = getCurrentInstance();
    const clickMenuItem = function (params: any) {
      console.log(params);
      const tempForm = instance.appContext.config.globalProperties.$createModel.proxy;
      const update = props => {
        console.log(selectedTreeData);
        const schemas = [
          {
            dataIndex: 'PEID',
            // fieldProps: {
            value: selectedTreeData.value.value,
            // },
          },
          {
            dataIndex: 'NODE_TYPE',
            disabled: true,
            value: 2,
            with: '50%',
          },
          {
            dataIndex: 'GROUP_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  studioParams: {
                    ORG_IDS: tempForm.formMethods.getData().ORG_IDS,
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORG_IDS: tempForm.formMethods.getData().ORG_IDS,
                  },
                },
              };
            },
          },
          {
            dataIndex: 'ROLE_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  studioParams: {
                    ORG_IDS: tempForm.formMethods.getData().ORG_IDS,
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORG_IDS: tempForm.formMethods.getData().ORG_IDS,
                  },
                },
              };
            },
          },
          {
            dataIndex: 'POST_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  studioParams: {
                    ORG_IDS: tempForm.formMethods.getData().ORG_IDS,
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORG_IDS: tempForm.formMethods.getData().ORG_IDS,
                  },
                },
              };
            },
          },
        ];
        let arr = [];
        for (let i = 0; i < schemas.length; i++) {
          const item = schemas[i];
          for (let j = 0; j < props.schemas.length; j++) {
            const stem = props.schemas[j];
            if (item.dataIndex == stem.dataIndex) {
              arr.push(item);
            }
          }
        }
        tempForm.formMethods.updateSchema(arr, props);
      };
      tempForm.handleUpdate(update);
    };
    // // 处理右键事件前
    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.value5 == null ? node.value3 : node.value5;
      let name = paramsData.value.menu[key];
      if (name) {
        const res = await useHttp({
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'menuv2',
            name: 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('permission.dataPermissionPolicy.dataPermissionPolicy.treeRightErrorMsg'),
          );
        }
      } else {
        data.items = [];
      }
      return data;
    };
    onMounted(() => {
      console.log(bus);
      console.log('onMounted');
      bus.on('getInstance', clickMenuItem);
      bus.on('refreshTable', () => {
        comRef.value?.refreshTable();
      });
    });
    onBeforeUnmount(() => {
      bus.off('getInstance');
    });

    // 右键删除操作特殊处理
    // 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 {
      t,
      treeRef,
      props,
      state,
      displayFormat,
      treeViewName,
      select,
      getComponent,
      provideData,
      selectType,
      success,
      beforeRightClick,
      newJsFun,
      // newJsFunDel,
      comRef,
      rightClick,
      clickMenuItem,
      deleteTreeData,
    };
  },
});
</script>
