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

import { ref } from 'vue';

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

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

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  confirmVehicleReplacementReturn,
  deleteVehicleReplacement,
  getVehicleReplacementPage,
  submitVehicleReplacementApproval,
  withdrawVehicleReplacementApproval,
} from '#/api/asset/vehicle-replacement';
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 handleView(row: AssetVehicleReplacementApi.VehicleReplacement) {
  formModalApi.setData({ ...row, _mode: 'view' }).open();
}

/** 编辑替换车 */
function handleEdit(row: AssetVehicleReplacementApi.VehicleReplacement) {
  formModalApi.setData({ ...row, _mode: 'edit' }).open();
}

/** 删除替换车 */
async function handleDelete(row: AssetVehicleReplacementApi.VehicleReplacement) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.replacementCode]),
    duration: 0,
  });
  try {
    await deleteVehicleReplacement(row.id!);
    message.success($t('ui.actionMessage.deleteSuccess', [row.replacementCode]));
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 提交审批 */
async function handleSubmitApproval(row: AssetVehicleReplacementApi.VehicleReplacement) {
  const hideLoading = message.loading({
    content: '提交审批中...',
    duration: 0,
  });
  try {
    await submitVehicleReplacementApproval(row.id!);
    message.success('提交审批成功');
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 撤回审批 */
async function handleWithdrawApproval(row: AssetVehicleReplacementApi.VehicleReplacement) {
  await confirm('确认撤回审批吗？');
  const hideLoading = message.loading({
    content: '撤回审批中...',
    duration: 0,
  });
  try {
    await withdrawVehicleReplacementApproval(row.id!);
    message.success('撤回审批成功');
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 确认换回 */
async function handleConfirmReturn(row: AssetVehicleReplacementApi.VehicleReplacement) {
  await confirm('确认换回原车吗？');
  const hideLoading = message.loading({
    content: '确认换回中...',
    duration: 0,
  });
  try {
    await confirmVehicleReplacementReturn(row.id!);
    message.success('确认换回成功');
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: AssetVehicleReplacementApi.VehicleReplacement[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getVehicleReplacementPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<AssetVehicleReplacementApi.VehicleReplacement>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</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:vehicle-replacement:create'],
              onClick: handleCreate,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.view'),
              type: 'link',
              icon: ACTION_ICON.VIEW,
              onClick: handleView.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['asset:vehicle-replacement:update'],
              onClick: handleEdit.bind(null, row),
              ifShow: row.status === 0 || row.status === 5 || row.status === 6,
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['asset:vehicle-replacement:delete'],
              ifShow: row.status === 0,
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [
                  row.replacementCode,
                ]),
                confirm: handleDelete.bind(null, row),
              },
            },
            {
              label: '提交审批',
              type: 'link',
              icon: ACTION_ICON.CHECK,
              auth: ['asset:vehicle-replacement:update'],
              ifShow: row.status === 0 || row.status === 5 || row.status === 6,
              onClick: handleSubmitApproval.bind(null, row),
            },
            {
              label: '撤回审批',
              type: 'link',
              icon: ACTION_ICON.CLOSE,
              auth: ['asset:vehicle-replacement:update'],
              ifShow: row.status === 1,
              onClick: handleWithdrawApproval.bind(null, row),
            },
            {
              label: '确认换回',
              type: 'link',
              icon: ACTION_ICON.CHECK,
              auth: ['asset:vehicle-replacement:update'],
              ifShow: row.status === 3 && row.replacementType === 1,
              onClick: handleConfirmReturn.bind(null, row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
