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

import { ref } from 'vue';
import { useRouter } from 'vue-router';

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 {
  deleteBill,
  exportBill,
  getBillPage,
} from '#/api/energy/bill';
import { $t } from '#/locales';

import {
  BILL_AUDIT_STATUS_OPTIONS,
  BILL_STATUS_OPTIONS,
  COOPERATION_TYPE_OPTIONS,
  PAYMENT_STATUS_OPTIONS,
  useGridColumns,
  useGridFormSchema,
} from './data';
import GenerateModal from './modules/generate-modal.vue';

const router = useRouter();
const generateModalRef = ref<InstanceType<typeof GenerateModal>>();

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

/** 导出 */
async function handleExport() {
  const formValues = await gridApi.formApi?.getValues();
  const blob = await exportBill(formValues ?? {});
  downloadFileFromBlobPart({ fileName: '能源账单.xlsx', source: blob });
}

/** 生成账单 */
function handleGenerate() {
  generateModalRef.value?.open('single');
}

/** 批量生成 */
function handleBatchGenerate() {
  generateModalRef.value?.open('batch');
}

/** 跳转详情 */
function handleView(row: EnergyBillApi.Bill) {
  router.push({ name: 'EnergyBillDetail', params: { id: row.id } });
}

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

/** 删除 */
async function handleDelete(row: EnergyBillApi.Bill) {
  try {
    await deleteBill(row.id!);
    message.success('删除成功');
    handleRefresh();
  } catch (e: any) {
    message.error(e.message || '删除失败');
  }
}

/** 审核跳转详情 */
function handleAudit(row: EnergyBillApi.Bill) {
  router.push({ name: 'EnergyBillDetail', params: { id: row.id } });
}

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

<template>
  <Page auto-content-height>
    <GenerateModal ref="generateModalRef" @success="handleRefresh" />
    <Grid table-title="能源账单列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: '生成账单',
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['energy:bill:create'],
              onClick: handleGenerate,
            },
            {
              label: '批量生成',
              icon: ACTION_ICON.ADD,
              auth: ['energy:bill:create'],
              onClick: handleBatchGenerate,
            },
            {
              label: $t('ui.actionTitle.export'),
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['energy:bill:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>

      <!-- 账单编号 - router-link -->
      <template #billCode="{ row }">
        <router-link
          :to="{ name: 'EnergyBillDetail', params: { id: row.id } }"
          class="text-blue-500 hover:underline"
        >
          {{ row.billCode }}
        </router-link>
      </template>

      <!-- 合作模式 -->
      <template #cooperationType="{ row }">
        <Tag
          v-if="row.cooperationType != null"
          :color="
            COOPERATION_TYPE_OPTIONS.find(
              (o) => o.value === row.cooperationType,
            )?.color
          "
        >
          {{
            COOPERATION_TYPE_OPTIONS.find(
              (o) => o.value === row.cooperationType,
            )?.label ?? row.cooperationType
          }}
        </Tag>
        <span v-else>—</span>
      </template>

      <!-- 调整金额 - 负数红色 -->
      <template #adjustmentAmount="{ row }">
        <span :class="{ 'text-red-500': (row.adjustmentAmount ?? 0) < 0 }">
          {{ row.adjustmentAmount ?? '—' }}
        </span>
      </template>

      <!-- 实收金额 - 加粗 -->
      <template #actualAmount="{ row }">
        <span class="font-bold">{{ row.actualAmount ?? '—' }}</span>
      </template>

      <!-- 账单状态 -->
      <template #status="{ row }">
        <Tag
          v-if="row.status != null"
          :color="
            BILL_STATUS_OPTIONS.find((o) => o.value === row.status)?.color
          "
        >
          {{
            BILL_STATUS_OPTIONS.find((o) => o.value === row.status)?.label ??
            row.status
          }}
        </Tag>
        <span v-else>—</span>
      </template>

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

      <!-- 付款状态 -->
      <template #paymentStatus="{ row }">
        <Tag
          v-if="row.paymentStatus != null"
          :color="
            PAYMENT_STATUS_OPTIONS.find((o) => o.value === row.paymentStatus)
              ?.color
          "
        >
          {{
            PAYMENT_STATUS_OPTIONS.find((o) => o.value === row.paymentStatus)
              ?.label ?? row.paymentStatus
          }}
        </Tag>
        <span v-else>—</span>
      </template>

      <!-- 操作列 -->
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              onClick: () => handleView(row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              show: row.status === 0,
              auth: ['energy:bill:update'],
              onClick: () => handleEdit(row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              show: row.status === 0,
              auth: ['energy:bill:delete'],
              onClick: () => handleDelete(row),
            },
            {
              label: '审核',
              type: 'link',
              icon: ACTION_ICON.AUDIT,
              show: row.status === 1 && row.auditStatus === 0,
              auth: ['energy:bill:audit'],
              onClick: () => handleAudit(row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
