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

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 {
  exportHydrogenDetail,
  getHydrogenDetailPage,
} from '#/api/energy/hydrogen-detail';
import { $t } from '#/locales';

import {
  AUDIT_STATUS_OPTIONS,
  DEDUCTION_STATUS_OPTIONS,
  SETTLEMENT_STATUS_OPTIONS,
  useGridColumns,
  useGridFormSchema,
} from './data';
import AuditModal from './modules/audit-modal.vue';

const auditModalRef = ref<InstanceType<typeof AuditModal>>();
const checkedRecords = ref<EnergyHydrogenDetailApi.Detail[]>([]);

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

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

/** 批量审核 */
function handleBatchAudit() {
  const selected = checkedRecords.value.filter((r) => r.auditStatus === 0);
  if (selected.length === 0) {
    message.warning('请选择待审核记录');
    return;
  }
  auditModalRef.value?.open(selected);
}

/** 单条审核 */
function handleAudit(row: EnergyHydrogenDetailApi.Detail) {
  auditModalRef.value?.open([row]);
}

/** 编辑（占位） */
function handleEdit(_row: EnergyHydrogenDetailApi.Detail) {
  // TODO: open edit modal
}

/** 查看（占位） */
function handleView(_row: EnergyHydrogenDetailApi.Detail) {
  // TODO: open view modal
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    checkboxConfig: {
      reserve: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getHydrogenDetailPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
    onCheckboxChange: ({ records }) => {
      checkedRecords.value = records;
    },
    onCheckboxAll: ({ records }) => {
      checkedRecords.value = records;
    },
  } as VxeTableGridOptions<EnergyHydrogenDetailApi.Detail>,
});
</script>

<template>
  <Page auto-content-height>
    <AuditModal ref="auditModalRef" @success="handleRefresh" />
    <Grid table-title="加氢明细列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: '批量审核',
              type: 'primary',
              icon: ACTION_ICON.AUDIT,
              disabled: checkedRecords.length === 0,
              auth: ['energy:hydrogen-detail:update'],
              onClick: handleBatchAudit,
            },
            {
              label: $t('ui.actionTitle.export'),
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['energy:hydrogen-detail:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>

      <template #auditStatus="{ row }">
        <Tag
          v-if="row.auditStatus != null"
          :color="
            AUDIT_STATUS_OPTIONS.find((o) => o.value === row.auditStatus)?.color
          "
        >
          {{
            AUDIT_STATUS_OPTIONS.find((o) => o.value === row.auditStatus)
              ?.label ?? row.auditStatus
          }}
        </Tag>
        <span v-else>—</span>
      </template>

      <template #deductionStatus="{ row }">
        <Tag
          v-if="row.deductionStatus != null"
          :color="
            DEDUCTION_STATUS_OPTIONS.find(
              (o) => o.value === row.deductionStatus,
            )?.color
          "
        >
          {{
            DEDUCTION_STATUS_OPTIONS.find(
              (o) => o.value === row.deductionStatus,
            )?.label ?? row.deductionStatus
          }}
        </Tag>
        <span v-else>—</span>
      </template>

      <template #settlementStatus="{ row }">
        <Tag
          v-if="row.settlementStatus != null"
          :color="
            SETTLEMENT_STATUS_OPTIONS.find(
              (o) => o.value === row.settlementStatus,
            )?.color
          "
        >
          {{
            SETTLEMENT_STATUS_OPTIONS.find(
              (o) => o.value === row.settlementStatus,
            )?.label ?? row.settlementStatus
          }}
        </Tag>
        <span v-else>—</span>
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '审核',
              type: 'link',
              icon: ACTION_ICON.AUDIT,
              show: row.auditStatus === 0,
              auth: ['energy:hydrogen-detail:update'],
              onClick: () => handleAudit(row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              show: row.auditStatus === 0 || row.auditStatus === 2,
              auth: ['energy:hydrogen-detail:update'],
              onClick: () => handleEdit(row),
            },
            {
              label: $t('common.view'),
              type: 'link',
              icon: ACTION_ICON.VIEW,
              show: row.auditStatus === 1,
              onClick: () => handleView(row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
