<template>
  <div class="main-content" id="UserMember">
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
        id="UserMember-queryForm"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="UserMember-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :show-size="false"
        :showExport="false"
        :animateRows="false"
        :title="t('userGroup.memberList.title')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        :scroll="{ y: true, extra: 24 }"
        :height="500"
        ref="gridRef"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="UserMember-buttonGroup" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="UserMember-buttonGroup-inline"
          />
        </template>
        <template #userState="{ 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="addMemberSuccess" />
  </div>
</template>
<script lang="ts">
import { useTable, useButtonGroup, useForm } from '@crami/bui-platform';
import { computed, defineComponent, watchEffect, inject, watch, ref } from 'vue';
import type { Ref } from 'vue';
import { message } from '@crami/ui';
import { getInfo, ICP_CONFIG, usePageParams, usePageData } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import { usePageParams, usePageData } from '@/utils/usePageData'; */
import type { ITreeNode } from '@crami/ui-types';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';
import PeopleSelector from '@remote/icpx-platform/PeopleSelector';
/* import PeopleSelector from '@/views/platform/components/PeopleSelector/Index.vue'; */

export default defineComponent({
  name: 'UserMember',
  components: {
    PeopleSelector,
  },
  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 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_MEMBER_LISTVIEW', //commonParams.value?.listView,
            },
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props = {
              submitter: {
                isQuery: true,
              },
              column: 2,
              //此处更改只在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_MEMBER_LISTVIEW', // commonParams.value?.listView,
          },
        },
        dataType: 'json',
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/system/group/getUserPageList',
        //'/api/system/model/getGetOnePageGridDataList',
        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,
          paraList: JSON.stringify({ parentId: [commonParams.value?.value1] }),
          showUnder: commonParams.value?.checked,
          filter: (params.filter || []).concat({
            andOrFlag: 'AND',
            field: 'USER_TYPE',
            operation: '!=',
            value: '0',
          }),
        };
      },
      columnExtra: {
        USER_SYS_STATUS: {
          customSlot: 'userState',
        },
      },
      operation: {
        dataIndex: 'action',
        title: t('platform.common.operate'),
        width: 110,
        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: 'UserMember',
      menuName: 'P_SYS_DEPT_MEMBER_MENU', //commonParams.value.menuName,
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
        dataType: 'json',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'UserMember',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const newJsFun = (event: any) => {
      if (event.result.code == 200) {
        message.success(event.result.msg);
        refreshTable();
        //HModal.destoryAll();
      } else {
        if (undefined == event) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

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

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

    // 打开成员管理弹窗
    const peopleSelectorRef = ref(null);
    const newJsMethod1 = () => {
      peopleSelectorRef.value.show(commonParams.value.value1, '/api/system/dept/saveUser');
    };

    // 成员管理添加成功
    const addMemberSuccess = () => {
      emit('refreshNode');
      refreshTable();
    };

    return {
      t,
      onReset,
      newJsMethod1,
      onFinish,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      refreshTable,
      gridRef,
      tableProps,
      addMemberSuccess,
      peopleSelectorRef,
    };
  },
});
</script>
<style lang="less" scoped></style>
