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

<script lang="ts">
import { defineComponent, watchEffect, computed, ref } from 'vue';
import { useTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { message, HModal } from '@crami/ui';
// import { useRouter } from 'vue-router';
import PeopleSelector from '@remote/icpx-platform/PeopleSelector';
/* import PeopleSelector from '@/views/platform/components/PeopleSelector/Index.vue'; */
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'RoleIndex',
  components: {
    PeopleSelector,
  },
  setup() {
    const { t } = useI18n();
    // const router = useRouter();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            mode: 'search',
            name: 'P_SYS_ROLE_LISTVIEW', //commonParams.value?.listViewName,
          },
          method: 'post',
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props = {
              submitter: {
                isQuery: true,
              },
              // 此处更改只在dev使用，不同步tcl
              // layout: 'vertical',
              column: 2,
              // title: t('platform.common.search'),
            };
            methods?.setProps(_props, props);
          }

          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

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

    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_ROLE_LISTVIEW', //commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: 'P_SYS_ROLE_LISTVIEW', //commonParams.value?.listViewName,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
        };
      },
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 160,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        ROLE_STATUS: {
          customSlot: 'roleState',
        },
      },
    });

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getData, getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'RoleIndex',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: 'P_SYS_ROLE_MENU', // commonParams.value?.menuName,
        },
        method: 'post',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'RoleIndex',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        refreshTable();
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

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

    const refreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };

    const onReset = () => {
      search([]);
    };

    const peopleSelectorRef = ref(null);
    const newJsMethod1 = () => {
      const selectIds = gridRef.value?.getSelectRowsIds();
      if (selectIds?.length !== 1) {
        message.error('请先选择一条数据');
        return;
      }
      peopleSelectorRef.value.show(selectIds[0], '/api/system/role/saveUser');
    };

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

    return {
      t,
      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      newJsMethod1,

      // clearData,
      // model,
      refreshCurrentPage,
      refreshTable,

      gridRef,
      tableProps,
      peopleSelectorRef,
    };
  },
});
</script>
<style lang="less" scoped></style>
