<template>
  <div class="main-content main-content-padding" id="DBConfigguration">
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        id="DBConfigguration-queryForm"
        ref="formRef"
        name="use"
        v-bind="props"
        :submitter="{
          isQuery: true,
          searchConfig: {
            resetText: t('platform.common.reset'),
            submitText: t('queryConfiguration.common.search'),
          },
        }"
        @finish="onFinish"
        @reset="onReset"
      />
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-pro-table
        id="DBConfigguration-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :showExport="false"
        :animateRows="false"
        :show-size="false"
        :title="t('queryConfiguration.dbconfigguration.tableTitle')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        :scroll="{
          extra: 24,
          y: true,
        }"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group id="DBConfigguration-buttonGroup" v-bind="menuProps" ref="menuRef" />
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            id="DBConfigguration-buttonGroup-inline"
            v-bind="menuPropsTable"
            ref="menuRefTable"
          />
        </template>
      </h-b-pro-table>
    </h-card>

    <map-edit-modal
      ref="mapEditModalRef"
      :maskClosable="false"
      @refreshTable="RefreshTable"
    ></map-edit-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, watchEffect, ref, createVNode, computed } from 'vue';
import { useProTable, 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, Icon } from '@crami/ui';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
import NewIndex from './NewIndex.vue';
import { useI18n } from '@crami/locale';
import mapEditModal from '../components/mapEditModal.vue';

export default defineComponent({
  name: 'DBConfigguration',
  components: {
    mapEditModal,
  },

  setup() {
    // 多语言
    const { t } = useI18n();
    const mapEditModalRef = ref();
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'ICPX_INDEX_DB_QUERY_LISTVIEW',
        menuName: 'ICPX_INDEX_DB_QUERY_MENU',
      };
    });
    const [formRef, props, methods] = useForm(
      {
        configApi: {
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form_view',
            mode: 'search',
            name: commonParams.value?.listViewName,
          },
          method: 'post',
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
              },
              column: 1,
            };
            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

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

    const [gridRef, tableProps, tableMethods] = useProTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: commonApi().system.getGetOnePageGridDataList.url,
        // url: 'index/queryConfig/page',
        method: commonApi().system.getGetOnePageGridDataList.method,
        studioParams: {
          ...commonApi().system.getGetOnePageGridDataList.params,
          viewName: 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('queryConfiguration.common.operate'),
        width: 180,
        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, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'DBConfigguration',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 2,
      pageName: 'DBConfigguration',
      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);
        }
      }
    };
    // 打开名称映射弹窗
    const mappingEdit = () => {
      const row = gridRef.value?.getSelectedRows();
      mapEditModalRef.value.showModal(row[0] || {}, {
        optionsApiUrl: 'index/queryConfig/getMapping',
        saveApiUrl: 'index/queryConfig/update',
      });
    };

    // 添加配置
    const newQuery = (row?: any) => {
      let addRowOptions = {
        title: t('queryConfiguration.common.dbmodalTitle'),
        content: NewIndex,
        componentProps: {
          rows: row ? [row] : gridRef.value?.getSelectedRows(),
        },
        width: '40%',
        onOk: saveOnOK,
      };
      HModal.page(addRowOptions);
    };

    const saveOnOK = (page, resolve) => {
      saveData(page, resolve);
    };

    // 保存数据
    const saveData = async (page, resolve) => {
      const radioValue = page.radioValue;
      // 校验失败时会返回false，成功返回表单对象
      if (radioValue) {
        const result = await useHttp({
          url: '/index/queryConfig/add',
          method: 'post',
          params: {
            data: radioValue,
            companyId: commonParams.value?.companyId,
            userId: commonParams.value.user_id,
            lang: commonParams.value?.lang,
            connect: commonParams.value?.connect,
            timeZone: commonParams.value?.TIME_ZONE,
          },
        });
        if (result.code == 200) {
          message.success(result.msg);
          RefreshTable();
          resolve();
        } else {
          message.error(result.msg);
        }
      } else {
        message.warning(t('queryConfiguration.common.selectTip'));
      }
    };

    // 删除配置
    const deleteIndex = async () => {
      const selectData = tableMethods.getSelectRows();
      HModal.confirm({
        width: '450px',
        title: t('queryConfiguration.common.deleteTitle'),
        class: 'self-warning-modal',
        closable: true,
        icon: createVNode(Icon, {
          name: 'icp-exclamation-circle-filled',
          size: 24,
          style: {
            float: 'left',
            marginRight: '8px',
          },
        }),
        content: t('queryConfiguration.common.deleteMsg'),
        onOk() {
          deleteApi(selectData[0].EID);
        },
      });
    };
    const deleteApi = async (idStr: string) => {
      const res = await useHttp({
        url: '/api/index/indexConfig/delete',
        method: 'post',
        params: {
          EIDStr: idStr,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (res.code == 200) {
        message.success(res.msg);
        RefreshTable();
      } else {
        message.error(res.msg);
      }
    };

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

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

    return {
      t,
      onFinish,
      onReset,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      RefreshTable,
      deleteIndex,
      // newIndex,
      newQuery,
      mappingEdit,
      // rebuildIndex,
      gridRef,
      tableProps,
      mapEditModalRef,
    };
  },
});
</script>
<style lang="less" scoped>
//删除弹窗图标样式
.tenant-confirm-delete {
  .ant-modal-confirm-body img {
    float: left;
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}
.rebuildIndex .ant-modal-confirm-body .ant-modal-confirm-content,
.deleteIndex .ant-modal-confirm-body .ant-modal-confirm-content {
  padding-left: 0 !important;
}
</style>
