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

import { ref } from 'vue';

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

import { message, Tabs } from 'ant-design-vue';
import { useRouter } from 'vue-router';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  completeDeliveryOrder,
  deleteDeliveryOrder,
  getDeliveryOrderPage,
} from '#/api/asset/delivery-order';
import { createReturnOrderFromDelivery } from '#/api/asset/return-order';
import { $t } from '#/locales';

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

const router = useRouter();

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

const activeTab = ref('pending');

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

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

function handleEdit(row: AssetDeliveryOrderApi.DeliveryOrder) {
  formModalApi.setData(row).open();
}

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

async function handleComplete(row: AssetDeliveryOrderApi.DeliveryOrder) {
  await confirm('确认完成交车？完成后将更新任务车辆状态。');
  await completeDeliveryOrder(row.id!);
  message.success('交车已完成');
  handleRefresh();
}

// 还车：从交车单创建还车单
async function handleReturn(row: AssetDeliveryOrderApi.DeliveryOrder) {
  await confirm('确认为该交车单创建还车单？');
  const vehicleIds = (row.vehicles || []).map((v: any) => v.vehicleId).filter(Boolean);
  if (vehicleIds.length === 0) {
    message.warning('该交车单没有关联车辆');
    return;
  }
  await createReturnOrderFromDelivery(row.id!, vehicleIds);
  message.success('还车单已创建');
}

// 替换车：跳转到替换车新增页面，带上参数
function handleReplacement(row: AssetDeliveryOrderApi.DeliveryOrder) {
  router.push({
    path: '/asset/vehicle-replacement',
    query: {
      contractId: String(row.contractId || ''),
      deliveryOrderId: String(row.id || ''),
    },
  });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: usePendingColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getDeliveryOrderPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            status: activeTab.value === 'history' ? 1 : 0,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<AssetDeliveryOrderApi.DeliveryOrder>,
});

function handleTabChange(key: string) {
  activeTab.value = key;
  const columns =
    key === 'history' ? useHistoryColumns() : usePendingColumns();
  gridApi.grid?.reloadColumn(columns as any);
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <Tabs :active-key="activeTab" @update:active-key="handleTabChange">
      <Tabs.TabPane key="pending" tab="待处理" />
      <Tabs.TabPane key="history" tab="历史记录" />
    </Tabs>
    <Grid :table-title="activeTab === 'history' ? '历史记录' : '待处理'">
      <template #toolbar-tools>
        <TableAction
          v-if="activeTab === 'pending'"
          :actions="[
            {
              label: '交车',
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['asset:delivery-order:create'],
              onClick: handleCreate,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction
          v-if="activeTab === 'pending'"
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['asset:delivery-order:query'],
              onClick: () => message.info('查看功能开发中'),
            },
            {
              label: '交车',
              type: 'link',
              auth: ['asset:delivery-order:create'],
              onClick: () => handleCreate(),
            },
          ]"
        />
        <TableAction
          v-else
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['asset:delivery-order:query'],
              onClick: () => handleEdit(row),
            },
            {
              label: '还车',
              type: 'link',
              auth: ['asset:return-order:create'],
              onClick: () => handleReturn(row),
            },
            {
              label: '替换车',
              type: 'link',
              auth: ['asset:vehicle-replacement:create'],
              onClick: () => handleReplacement(row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
