<template>
  <div class="main-content main-content-padding" id="TenantManagement">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="TenantManagement-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        id="TenantManagement-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="true"
        :showExport="false"
        :animateRows="false"
        :show-size="false"
        :title="t('tenant.tenantManagement.tenantTitle')"
        :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="TenantManagement-buttonGroup" v-bind="menuProps" ref="menuRef" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            id="TenantManagement-buttonGroup-inline"
            v-bind="menuPropsTable"
            ref="menuRefTable"
          />
        </template>
        <template #auditState="{ record }">
          <template v-if="record.STATUS == '1'">
            <h-badge status="success" :text="record.AUDITSTATE" />
          </template>
          <template v-else-if="record.STATUS == '-1'">
            <h-badge status="error" :text="record.AUDITSTATE" />
          </template>
          <template v-else>
            <h-badge color="#3979F9" :text="record.AUDITSTATE" />
          </template>
        </template>
      </h-b-table>
    </h-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, watchEffect, computed, createVNode, onMounted } from 'vue';
import { useTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { message, HModal, Icon } from '@crami/ui';
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';
import { getInfo, ICP_CONFIG, registerComponents } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; 
import { registerComponents } from '@/utils/componentUtils';
*/
import { useRouter } from 'vue-router';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */

export default defineComponent({
  name: 'TenantManagement',

  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_COMPANY_LISTVIEW', // commonParams.value?.listViewName,
          },
          method: 'post',
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                // actionButtonGroupPosition: 'top',
              },
              // 此处更改只在dev使用，不同步tcl
              // layout: 'vertical',
              column: 2,
              // labelCol: { span: 20 }, //标签
              // wrapperCol: { span: 20 },
              //   initialValue: {这里设置查询条件初始值},
              // title: '查询',
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    onMounted(() => {
      // 引入components文件夹下的vue文件
      const modules = import.meta.glob('./components/*.vue');
      registerComponents(modules);
    });

    // const onFinish = data => {
    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_COMPANY_LISTVIEW', //commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: 'P_SYS_COMPANY_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('tenant.common.operate'),
        width: 160,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        AUDITSTATE: {
          customSlot: 'auditState',
        },
      },
    });

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    // const [menuRef, menuProps, { getData, getRowMenu }] = useButtonGroup({
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'TenantManagement',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          type: 'menuv2',
          name: 'P_SYS_COMPANY_MENU', // commonParams.value?.menuName,
        },
        method: 'post',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'TenantManagement',
      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 || undefined == event.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };

    function getResultInArr(arr, status) {
      let flag = true;
      for (let i = 0; i < arr.length; i++) {
        if (status != arr[i].STATUS) {
          return (flag = false);
        }
      }
      return flag;
    }

    const DeleteTeant = () => {
      const datas = tableMethods.getSelectedDatas();
      if (datas.length === 0) {
        message.warning(t('tenant.tenantManagement.deleteWarn'));
        return;
      }
      let text = '"' + datas[0].ENAME + '"';
      if (datas.length > 1) {
        text = '';
      }
      HModal.confirm({
        closable: true,
        width: '448px',
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        class: 'tenant-confirm-delete',
        title: t('tenant.tenantManagement.deleteTitle'),
        content: t('tenant.tenantManagement.deleteContent', { text: text }),
        onOk() {
          return new Promise((resolve, reject) => {
            let result = getResultInArr(datas, '-1');
            if (!result) {
              message.warning(t('tenant.tenantManagement.deleteOkWarn'));
              reject();
              return;
            }
            let delArr = [];
            datas.forEach(element => {
              delArr.push(element.EID);
            });
            submitEvent({ eidstr: delArr });
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };

    const submitEvent = async (params: any) => {
      await useHttp({
        url: '/api/system/tenant/delete',
        method: 'post',
        params: params,
      });
      refreshTable();
      message.success(t('tenant.common.operateOk'));
    };

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

    const pushAuthonrization = event => {
      router.push({ name: 'TenantAuthorization', params: { EID: event.EID } });
    };
    const refreshCurrentPage = () => {
      const params = formRef.value?.getFilterData();
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, false);
    };
    const refreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };
    const onReset = () => {
      search([]);
    };
    return {
      t,
      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      pushAuthonrization,

      // clearData,
      // model,
      refreshCurrentPage,
      refreshTable,
      DeleteTeant,
      // newJsFun,

      gridRef,
      tableProps,
    };
  },
});
</script>
<style lang="less" scoped>
//删除弹窗图标样式
.tenant-confirm-delete {
  .ant-modal-confirm-body img {
    float: left;
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}
</style>
