<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EmployeeFlowApi } from '#/api/hr/employeeFlow';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';
import { getVxePopupContainer } from '@vben/utils';

import { Button, message, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { apiDelete, apiExport, apiPage } from '#/api/hr/employeeFlow';
import { cancelProcessApply } from '#/api/workflow/instance/index';
import { commonDownloadExcel } from '#/utils/file/download';

import { applyModal, flowInfoModal } from '../components';
import { querySchema, useColumns } from './data';
import Form from './form.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const [ApplyModal, applyModalApi] = useVbenModal({
  connectedComponent: applyModal,
});
const [FlowInfoModal, flowInfoModalApi] = useVbenModal({
  connectedComponent: flowInfoModal,
});
const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: {
    columns: useColumns(),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues = {}) => {
          return await apiPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
  } as VxeTableGridOptions,
  gridEvents: {
    cellClick: ({ row, column }) => {
      // 草稿状态 不做处理
      // 操作列 不做处理
      if (row.status === 'draft' || column.field === 'action') {
        return;
      }
      // 查看详情
      handleInfo(row);
    },
  },
});

function onRefresh() {
  gridApi.query();
}
function onEdit(row: EmployeeFlowApi.EmployeeFlow) {
  formDrawerApi.setData(row).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}
function onDelete(row: EmployeeFlowApi.EmployeeFlow) {
  const hideLoading = message.loading({
    content: `正在删除${row.applyCode}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  apiDelete(row.id || 0)
    .then(() => {
      message.success({
        content: `${row.applyCode}删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}
function handleDownloadExcel() {
  commonDownloadExcel(apiExport, '人事审批列表', gridApi.formApi.form.values);
}

async function handleRevoke(row: Required<EmployeeFlowApi.EmployeeFlow>) {
  await cancelProcessApply({
    businessId: row.id,
    message: '申请人撤销流程！',
  });
  await gridApi.query();
}

async function handleCompleteOrCancel() {
  formDrawerApi.close();
  gridApi.query();
}

function handleInfo(row: Required<EmployeeFlowApi.EmployeeFlow>) {
  flowInfoModalApi.setData({ businessId: row.id });
  flowInfoModalApi.open();
}
</script>
<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <Grid table-title="人事审批列表">
      <template #toolbar-tools>
        <Space>
          <Button
            v-access:code="['employee:flow:export']"
            @click="handleDownloadExcel"
          >
            导出
          </Button>
          <Button
            v-access:code="['employee:flow:add']"
            type="primary"
            @click="onCreate"
          >
            <Plus class="size-5" />
            新增
          </Button>
        </Space>
      </template>
      <template #action="{ row }">
        <Button
          size="small"
          type="link"
          :disabled="!['draft', 'cancel', 'back'].includes(row.status)"
          v-access:code="['employee:flow:edit']"
          @click.stop="onEdit(row)"
        >
          修改
        </Button>
        <Popconfirm
          :get-popup-container="getVxePopupContainer"
          placement="left"
          title="确认撤销？"
          :disabled="!['waiting'].includes(row.status)"
          @confirm.stop="handleRevoke(row)"
          @cancel.stop=""
        >
          <Button
            size="small"
            type="link"
            :disabled="!['waiting'].includes(row.status)"
            v-access:code="['employee:flow:edit']"
            @click.stop=""
          >
            撤销
          </Button>
        </Popconfirm>
        <Popconfirm
          :get-popup-container="getVxePopupContainer"
          placement="left"
          title="确认删除？"
          :disabled="!['draft', 'cancel', 'back'].includes(row.status)"
          @confirm.stop="onDelete(row)"
          @cancel.stop=""
        >
          <Button
            size="small"
            type="link"
            :disabled="!['draft', 'cancel', 'back'].includes(row.status)"
            danger
            v-access:code="['employee:flow:remove']"
            @click.stop=""
          >
            删除
          </Button>
        </Popconfirm>
      </template>
    </Grid>
    <FlowInfoModal />
    <ApplyModal
      @complete="handleCompleteOrCancel"
      @cancel="handleCompleteOrCancel"
    />
  </Page>
</template>
