<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AssetReturnOrderApi } from '#/api/asset/return-order';

import { ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';

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

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  completeReturnOrderInspection,
  deleteReturnOrder,
  getReturnOrderPage,
  settleReturnOrder,
  submitReturnOrderApproval,
  withdrawReturnOrderApproval,
} from '#/api/asset/return-order';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

function handleRefresh() {
  gridApi.query();
}

function handleCreate() {
  formModalApi.setData(null).open();
}

function handleEdit(row: AssetReturnOrderApi.ReturnOrder) {
  formModalApi.setData(row).open();
}

async function handleDelete(row: AssetReturnOrderApi.ReturnOrder) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.orderCode]),
    duration: 0,
  });
  try {
    await deleteReturnOrder(row.id!);
    message.success($t('ui.actionMessage.deleteSuccess', [row.orderCode]));
    handleRefresh();
  } finally {
    hideLoading();
  }
}

async function handleCompleteInspection(row: AssetReturnOrderApi.ReturnOrder) {
  await confirm('确认验车完成？完成后状态将变更为验车完成。');
  await completeReturnOrderInspection(row.id!);
  message.success('验车已完成');
  handleRefresh();
}

async function handleSettle(row: AssetReturnOrderApi.ReturnOrder) {
  await confirm('确认结算还车单？结算后不可修改。');
  await settleReturnOrder(row.id!);
  message.success('还车单已结算');
  handleRefresh();
}

async function handleSubmitApproval(row: AssetReturnOrderApi.ReturnOrder) {
  await confirm('确认提交审批？');
  await submitReturnOrderApproval(row.id!);
  message.success('已提交审批');
  handleRefresh();
}

async function handleWithdrawApproval(row: AssetReturnOrderApi.ReturnOrder) {
  await confirm('确认撤回审批？');
  await withdrawReturnOrderApproval(row.id!);
  message.success('已撤回审批');
  handleRefresh();
}

/** 根据状态动态生成操作菜单 */
function getRowActions(row: AssetReturnOrderApi.ReturnOrder) {
  const actions: any[] = [];

  // 查看 - 始终可见
  actions.push({
    auth: ['asset:return-order:query'],
    icon: ACTION_ICON.VIEW,
    label: '查看',
    onClick: () => message.info('查看功能开发中'),
    type: 'link',
  });

  // 待验车 → 可编辑
  if (row.status === 0) {
    actions.push({
      auth: ['asset:return-order:update'],
      icon: ACTION_ICON.EDIT,
      label: $t('common.edit'),
      onClick: () => handleEdit(row),
      type: 'link',
    });
  }

  // 待验车 → 完成验车
  if (row.status === 0) {
    actions.push({
      auth: ['asset:return-order:update'],
      label: '完成验车',
      onClick: () => handleCompleteInspection(row),
      type: 'link',
    });
  }

  // 验车完成 → 提交审批
  if (row.status === 1 && row.approvalStatus !== 1) {
    actions.push({
      auth: ['asset:return-order:update'],
      label: '提交审批',
      onClick: () => handleSubmitApproval(row),
      type: 'link',
    });
  }

  // 审批中 → 撤回
  if (row.approvalStatus === 1) {
    actions.push({
      auth: ['asset:return-order:update'],
      label: '撤回审批',
      onClick: () => handleWithdrawApproval(row),
      type: 'link',
    });
  }

  // 验车完成 → 结算
  if (row.status === 1) {
    actions.push({
      auth: ['asset:return-order:update'],
      label: '结算',
      onClick: () => handleSettle(row),
      type: 'link',
    });
  }

  // 待验车 → 可删除
  if (row.status === 0) {
    actions.push({
      auth: ['asset:return-order:delete'],
      danger: true,
      icon: ACTION_ICON.DELETE,
      label: $t('common.delete'),
      popConfirm: {
        confirm: () => handleDelete(row),
        title: $t('ui.actionMessage.deleteConfirm', [row.orderCode]),
      },
      type: 'link',
    });
  }

  return actions;
}

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

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <Grid table-title="还车管理">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['还车单']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['asset:return-order:create'],
              onClick: handleCreate,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction :actions="getRowActions(row)" />
      </template>
    </Grid>
  </Page>
</template>
