<template>
  <div class="main-content-item-right width-computed">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        id="Root-queryForm"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('dictManage.root.tableTitle')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        id="Root-querytable"
        :scroll="{
          extra: 24,
          y: true,
        }"
        :height="500"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="Root-buttonGroup" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="Root-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, watch } from 'vue';
import { message, HModal } from '@crami/ui';
import { getInfo, ICP_CONFIG, usePageParams } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import { usePageParams } from '@/utils/usePageData'; */
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';
// import {  saveLineData, editLineData  } from './commonApi';
export default defineComponent({
  name: 'Root',
  components: {},
  props: {
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  emits: ['success'],
  setup(_, { emit }) {
    const { t } = useI18n();
    const pageParams: any = usePageParams();
    const commonParams = computed(() => {
      return { ...getInfo(ICP_CONFIG), ...pageParams.value };
    });

    const initForm = computed(() => {
      return {
        APPLICATION_ID: _.propsData?.value1,
      };
    });
    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            mode: 'search',
            name: commonParams.value?.listView,
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
              },
              column: 3,
              // layout: 'vertical',
              // labelCol: { span: 8 }, //标签
              // wrapperCol: { span: 20 },
              //   initialValue: {这里设置查询条件初始值},
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const onFinish = data => {
      // 处理data数据
      console.log(data);
      const formData = formRef.value.getFilterData();
      search(formData);
    };

    const beforeRequest = (type, params: any) => {
      if (type == 'column') {
        if (params && params.data && typeof params.data == 'object') {
          params.data = JSON.stringify(params.data);
        }
      }
      const APP_ID = params.filter?.find(item => item.field == 'APPLICATION_ID');

      return {
        ...params,
        filter: APP_ID
          ? params.filter
          : (params.filter || []).concat({
              andOrFlag: 'AND',
              field: 'APPLICATION_ID',
              operation: '=',
              value: _.propsData?.value1,
            }),
      };
    };

    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: commonParams.value?.listView,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: commonParams.value?.listView,
        },
      },
      beforeRequest: beforeRequest,
      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: 'Root',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: commonParams.value?.menuName,
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'Root',
      items: [],
    });
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        refreshTable();
        emit('success');
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result?.msg);
        }
      }
    };

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

    const refreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };
    // 重置
    const onReset = () => {
      search([]);
    };

    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, false);
    };

    watch(
      () => _.propsData,
      () => {
        refreshTable();
      },
      { deep: true },
    );
    return {
      t,
      onFinish,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,

      // clearData,
      // model,

      refreshTable,
      // newJsFun,

      gridRef,
      tableProps,
      initForm,
      onReset,
      refreshCurrentPage,
      commonParams,
    };
  },
});
</script>
