<template>
  <div class="main-content main-content-padding" id="OrganizationPage">
    <h-card class="margin-bottoms list-query-forms">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        @finish="onFinish"
        @reset="onReset"
        id="OrganizationPage-queryForm"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-table
        v-bind="tableProps"
        rowKey="EID"
        :pagination="false"
        :needRowIndex="false"
        :show-size="false"
        :title="t('orgManage.tableTitle')"
        :showExport="false"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        :expandIcon="expandIconFun"
        ref="gridRef"
        id="OrganizationPage-queryTable"
        :height="500"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="OrganizationPage-buttonGroup" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="OrganizationPage-buttonGroup-inline"
            :checkPermisson="false"
          />
        </template>
      </h-b-table>
    </h-card>
  </div>
</template>

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

export default defineComponent({
  name: 'OrganizationPage',
  setup() {
    console.log(ICP_CONFIG);
    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_ORG_LISTVIEW', //commonParams.value?.listViewName,
            },
          },
          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 },
              // title: '查询',
              //   initialValue: {这里设置查询条件初始值},
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const onFinish = data => {
      // 处理data数据
      console.log(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: commonParams.value?.listViewName,
            viewName: 'P_SYS_ORG_LISTVIEW',
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/system/org/getOrgListTree',
        method: 'post',
        studioParams: {
          // viewName: commonParams.value?.listViewName,
          viewName: 'P_SYS_ORG_LISTVIEW',
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: 'P_SYS_COMPANY_155f6a331e804b69a6fc47e6273699fc', //commonParams.value?.companyId,
          objectType: '',
        },
      },
      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',
      },
    });

    const search = (params: any) => {
      const allParam = {
        filter: params,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'default',
      pageName: 'OrganizationPage',
      checkPermission: false,
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: 'P_SYS_ORG_MENU', //commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      checkPermission: false,
      pageName: 'OrganizationPage',
      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');
      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);
    };

    // 控制展开icon
    const expandIconFun = _props => {
      if (_props.record.children.length > 0) {
        if (_props.expanded) {
          return createVNode('span', { key: 'hoteam-arrow-up' }, [
            createVNode(Icon, {
              name: 'hoteam-arrow-up',
              style: { marginRight: '8px' },
              size: 16,
              onClick: e => _props.onExpand(_props.record, e),
            }),
          ]);
        } else {
          return createVNode('span', { key: 'hoteam-arrow-down' }, [
            createVNode(Icon, {
              name: 'hoteam-arrow-down',
              style: { marginRight: '8px' },
              size: 16,
              onClick: e => _props.onExpand(_props.record, e),
            }),
          ]);
        }
      } else {
        return createVNode('span', { style: { marginLeft: '24px' } }, '');
      }
    };

    const PARENT_ID: any = ref('');
    watch(
      () => tableMethods.getSelectedDatas(),
      () => {
        const selectData = tableMethods.getSelectedDatas();
        if (selectData && selectData.length == 1) {
          PARENT_ID.value = {
            label: selectData[0].ename,
            value: selectData[0].eid,
          };
        } else {
          PARENT_ID.value = '';
        }
      },
    );

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

      // clearData,
      // model,

      refreshTable,
      refreshCurrentPage,
      // newJsFun,

      gridRef,
      tableProps,
      onReset,
      expandIconFun,
      PARENT_ID,
    };
  },
});
</script>

<style scoped lang="less"></style>
