<template>
  <div class="main-content main-content-padding" id="UserIndex">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="UserIndex-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="UserIndex-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :showExport="false"
        :animateRows="false"
        :show-size="false"
        :title="t('userManagement.userList.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="UserIndex-bottomGroup" v-bind="menuProps" ref="menuRef" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            id="UserIndex-buttonGroup-inline"
            v-bind="menuPropsTable"
            ref="menuRefTable"
          />
        </template>
      </h-b-table>
    </h-card>
    <transfer-ownership ref="transferOwnershipRef" @transferShipSuccess="refreshCurrentPage" />
    <transfer-process ref="transferProcessRef" @transferProcessSuccess="refreshCurrentPage" />
  </div>
</template>

<script lang="ts">
import { defineComponent, watchEffect, computed, getCurrentInstance, ref } from 'vue';
import { useTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { message, HModal } from '@crami/ui';
// import { useRouter } from 'vue-router';

import TransferOwnership from './TransferOwnerShip.vue';
import TransferProcess from './TransferProcess.vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';
import { getInfo, ICP_CONFIG, handleCommonInstance } from '@remote/icpx-platform/utils';
/* 
import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import { handleCommonInstance } from '@/utils/componentUtils'; */

export default defineComponent({
  name: 'UserIndex',
  components: { TransferOwnership, TransferProcess },

  setup() {
    const { t } = useI18n();
    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_USER_LISTVIEW', //commonParams.value?.listViewName,
          },
          method: 'post',
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props = {
              submitter: {
                isQuery: true,
              },
              // 此处更改只在dev使用，不同步tcl
              // layout: 'vertical',
              column: 2,
              // labelCol: { span: 20 }, //标签
              // wrapperCol: { span: 20 },
              //   initialValue: {这里设置查询条件初始值},
              // 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_USER_LISTVIEW', //commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: 'P_SYS_USER_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,
          filter: (params.filter || []).concat({
            andOrFlag: 'AND',
            field: 'USER_TYPE',
            operation: '!=',
            value: '0',
          }),
        };
      },
      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: 'UserIndex',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: 'P_SYS_USER_MENU', // commonParams.value?.menuName,
        },
        method: 'post',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'UserIndex',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, false);
    };
    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');
      load(rowData);
    });

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

    const instance = getCurrentInstance();
    function buttonClick(params) {
      console.log(params);
      const tempForm = instance.appContext.config.globalProperties.$createModel.proxy;
      const update = props => {
        const schemas = [
          {
            dataIndex: 'ORG_IDS',
            fieldProps: {
              onChange: () => {
                tempForm.formMethods.setData({ DEPT_IDS: '' });
                tempForm.formMethods.setData({ GROUP_IDS: '' });
                tempForm.formMethods.setData({ ROLE_IDS: '' });
                tempForm.formMethods.setData({ POST_IDS: '' });
              },
            },
          },
          {
            dataIndex: 'DEPT_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  // url: '/api/system/model/getGetTreeChildDataList',
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
              };
            },
          },
          {
            dataIndex: 'GROUP_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  // url: '/api/system/model/getGetTreeChildDataList',
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
              };
            },
          },
          {
            dataIndex: 'ROLE_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  // url: '/api/system/model/getGetTreeChildDataList',
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
              };
            },
          },
          {
            dataIndex: 'POST_IDS',
            dynamicParams: () => {
              return {
                treeDataApi: {
                  // url: '/api/system/model/getGetTreeChildDataList',
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(tempForm.formMethods.getData().ORG_IDS),
                  },
                },
                treeChildrenDataApi: {
                  studioParams: {
                    ORGID: tempForm.formMethods.getData().ORG_IDS,
                    TENANTID: getTenant(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);
      // }, 10);
    }
    handleCommonInstance(buttonClick);

    const getTenant = (orgs: string) => {
      const orgStr = orgs
        .split(';')
        .filter(item => {
          return item.indexOf('P_SYS_COMPANY') != -1;
        })
        .join(';');

      return orgStr ? orgStr : '';
    };

    const transferOwnershipRef: any = ref('');
    const transferOwnership = (data = {}) => {
      const selectData = gridRef.value?.getSelectedDatas()[0] || {};
      transferOwnershipRef.value?.show({ ...selectData, ...data });
    };

    const transferProcessRef: any = ref('');
    const processTransfer = (data = {}) => {
      const selectData = gridRef.value?.getSelectedDatas()[0] || {};
      transferProcessRef.value?.show({ ...selectData, ...data });
    };

    return {
      t,
      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      processTransfer,
      transferProcessRef,
      refreshCurrentPage,
      refreshTable,
      gridRef,
      tableProps,
      transferOwnership,
      transferOwnershipRef,
    };
  },
});
</script>
<style lang="less" scoped></style>
