<template>
  <div class="main-content" id="AdminGroup">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
        id="AdminGroup-queryForm"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="AdminGroup-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('admingroupmanagement.administrativeGroupList.tableTitle')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        :scrolls="{ y: true, extra: 24 }"
        :height="500"
        ref="gridRef"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="AdminGroup-buttonGroup" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="AdminGroup-buttonGroup-inline"
          />
        </template>
      </h-b-table>
    </h-card>
  </div>
</template>

<script lang="ts">
import { useTable, useButtonGroup, useForm } from '@crami/bui-platform';
import { computed, defineComponent, watchEffect, inject, watch } from 'vue';
import type { Ref } from 'vue';
import { message, HModal } from '@crami/ui';
// 模块联邦：替换成远程加载
import { getInfo, ICP_CONFIG, usePageParams, usePageData } from '@remote/icpx-platform/utils';
import type { ITreeNode } from '@crami/ui-types';
/* 
import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import { usePageParams, usePageData } from '@/utils/usePageData'; 
*/
/* import { commonApi } from '@/api/commonApi/index'; */
import { commonApi } from '@remote/icpx-platform/commonApi';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'AdminGroup',
  components: {},
  props: {
    activeKey: {
      type: String,
      required: true,
    },
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  emits: ['refreshNode'],
  setup(prop, { emit }) {
    const { t } = useI18n();
    const isDirect = inject('isDirect') as Ref<{ checked: boolean }>;

    const pageData = usePageData() as Ref<ITreeNode>;

    const pageParams: any = usePageParams();
    const value1 = computed(() => {
      return prop.propsData?.value1;
    });
    const title = computed(() => {
      return prop.propsData?.title;
    });
    const initForm = computed(() => {
      return {
        PARENT_ID: { label: title.value, value: value1.value },
      };
    });

    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        ...pageParams,
        ...pageData,
        ...isDirect.value,
        ...prop.propsData,
        activeKey: prop.activeKey,
      };
    });
    watch(
      () => [prop.propsData, isDirect.value],
      () => {
        refreshTable();
      },
    );

    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            ...{
              type: 'form_view',
              mode: 'search',
              name: 'P_SYS_DEPT_LISTVIEW', //commonParams.value?.listView,
            },
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props = {
              submitter: {
                isQuery: true,
              },
              column: 1,
              //此处更改只在dev
              // layout: 'vertical',
              // labelCol: { span: 20 }, //标签
              // wrapperCol: { span: 20 },
              // title: t('platform.common.search'),
              //   initialValue: {这里设置查询条件初始值},
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const onFinish = data => {
      // 处理data数据
      console.log(data);
      const formData = formRef.value.getFilterData();
      search(formData);
    };
    const onReset = () => {
      search([]);
    };
    const [gridRef, tableProps, tableMethods] = useTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: 'P_SYS_DEPT_LISTVIEW', //commonParams.value?.listView,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/system/dept/getPageList',
        method: 'post',
        studioParams: {
          viewName: commonParams.value?.listView,
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          timeZone: commonParams.value?.TIME_ZONE,
          objectType: '',
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
          parentId: commonParams.value?.value1,
          showUnder: commonParams.value?.checked,
          filter: params.filter,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 160,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
    });

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'AdminGroup',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: 'P_SYS_DEPT_MENU', //commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'AdminGroup',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        refreshTable();
        emit('refreshNode');
        HModal.destroyAll();
      } else {
        if (undefined == event || undefined == event.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };
    //页面刷新操作按钮
    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };

    //处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });

    const refreshTable = () => {
      //tableMethods.query();
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };
    return {
      t,
      onReset,
      onFinish,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      refreshTable,
      gridRef,
      tableProps,
      initForm,
      refreshCurrentPage,
    };
  },
});
</script>

<style scoped></style>
