<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EnergyHydrogenRecordApi } from '#/api/energy/hydrogen-record';

import { ref } from 'vue';

import { Page } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { Tag, message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  batchMatch,
  deleteHydrogenRecord,
  exportHydrogenRecord,
  getHydrogenRecordPage,
} from '#/api/energy/hydrogen-record';
import { $t } from '#/locales';

import {
  MATCH_STATUS_OPTIONS,
  SOURCE_TYPE_OPTIONS,
  useGridColumns,
  useGridFormSchema,
} from './data';
import ImportModal from './modules/import-modal.vue';

const importModalRef = ref<InstanceType<typeof ImportModal>>();

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 打开导入弹窗 */
function handleImport() {
  importModalRef.value?.open();
}

/** 导出 */
async function handleExport() {
  const formValues = await gridApi.formApi?.getValues();
  const blob = await exportHydrogenRecord(formValues ?? {});
  downloadFileFromBlobPart({ fileName: '加氢记录.xlsx', source: blob });
}

/** 批量匹配 */
async function handleBatchMatch() {
  const hideLoading = message.loading({ content: '正在匹配...', duration: 0 });
  try {
    const result = await batchMatch();
    message.success(
      `匹配完成：成功 ${result.successCount} 条，失败 ${result.failCount} 条`,
    );
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 删除记录 */
async function handleDelete(row: EnergyHydrogenRecordApi.Record) {
  await deleteHydrogenRecord(row.id!);
  message.success($t('ui.actionMessage.operationSuccess'));
  handleRefresh();
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getHydrogenRecordPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<EnergyHydrogenRecordApi.Record>,
});
</script>

<template>
  <Page auto-content-height>
    <ImportModal ref="importModalRef" @success="handleRefresh" />
    <Grid table-title="加氢记录列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: 'Excel导入',
              type: 'primary',
              icon: ACTION_ICON.UPLOAD,
              auth: ['energy:hydrogen-record:import'],
              onClick: handleImport,
            },
            {
              label: $t('ui.actionTitle.export'),
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['energy:hydrogen-record:export'],
              onClick: handleExport,
            },
            {
              label: '重新匹配',
              icon: ACTION_ICON.REFRESH,
              auth: ['energy:hydrogen-record:batch-match'],
              onClick: handleBatchMatch,
            },
          ]"
        />
      </template>
      <template #sourceType="{ row }">
        <Tag
          v-if="row.sourceType != null"
          :color="
            SOURCE_TYPE_OPTIONS.find((o) => o.value === row.sourceType)?.color
          "
        >
          {{
            SOURCE_TYPE_OPTIONS.find((o) => o.value === row.sourceType)
              ?.label ?? row.sourceType
          }}
        </Tag>
        <span v-else>—</span>
      </template>
      <template #matchStatus="{ row }">
        <Tag
          v-if="row.matchStatus != null"
          :color="
            MATCH_STATUS_OPTIONS.find((o) => o.value === row.matchStatus)?.color
          "
        >
          {{
            MATCH_STATUS_OPTIONS.find((o) => o.value === row.matchStatus)
              ?.label ?? row.matchStatus
          }}
        </Tag>
        <span v-else>—</span>
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['energy:hydrogen-record:update'],
              onClick: () => {},
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['energy:hydrogen-record:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.plateNumber]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
