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

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

import { shallowRef } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
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 applyRenewalContractModel from '../../hr/contractExpirationReminder/apply-renewal-contract-model.vue';
import applyEntryModel from '../../hr/employeeInfo/apply-entry-model.vue';
import applyResignModel from '../../hr/employeeInfo/apply-resign-model.vue';
import applyTransferModel from '../../hr/employeeInfo/apply-transfer-model.vue';
import applyRegularModel from '../../hr/regularReminder/apply-regular-model.vue';
import { applyModal, flowInfoModal } from '../components';
import { querySchema, useColumns } from './data';
import { useRouteIdEdit } from './hook';

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 modalApi = shallowRef<ExtendedModalApi | null>(null);

const [ApplyModal, applyModalApi] = useVbenModal({
  connectedComponent: applyModal,
});
const [FlowInfoModal, flowInfoModalApi] = useVbenModal({
  connectedComponent: flowInfoModal,
});
const [ApplyEntryModel, applyEntryModelApi] = useVbenModal({
  connectedComponent: applyEntryModel,
});
const [ApplyResignModel, applyResignModelApi] = useVbenModal({
  connectedComponent: applyResignModel,
});
const [ApplyTransferModel, applyTransferModelApi] = useVbenModal({
  connectedComponent: applyTransferModel,
});
const [ApplyRegularModel, applyRegularModelApi] = useVbenModal({
  connectedComponent: applyRegularModel,
});
const [ApplyRenewalContractModel, applyRenewalContractModelApi] = useVbenModal({
  connectedComponent: applyRenewalContractModel,
});
// 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);
    },
  },
});

useRouteIdEdit((id, flowCode) => {
  // 打开编辑
  if (id && flowCode) {
    let flowType = '1';
    switch (flowCode) {
      case 'hrEntryFlow': {
        flowType = '1';
        break;
      }
      case 'hrRegularizationFlow': {
        flowType = '4';
        break;
      }
      case 'hrRenewalContractFlow': {
        flowType = '5';
        break;
      }
      case 'hrResignFlow': {
        flowType = '2';
        break;
      }
      case 'hrTransferFlow': {
        flowType = '3';
        break;
      }
      default: {
        break;
      }
    }
    // 打开编辑
    onEdit({ flowType, id: Number(id) });
  }
});

function onRefresh() {
  gridApi.query();
}
function onEdit(row: EmployeeFlowApi.EmployeeFlow) {
  // formDrawerApi.setData(row).open();
  switch (row.flowType) {
    case '1': {
      modalApi.value = applyEntryModelApi;
      applyEntryModelApi.setData({ id: row.id, applyModalApi }).open();
      break;
    }
    case '2': {
      modalApi.value = applyResignModelApi;
      applyResignModelApi.setData({ id: row.id, applyModalApi }).open();
      break;
    }
    case '3': {
      modalApi.value = applyTransferModelApi;
      applyTransferModelApi.setData({ id: row.id, applyModalApi }).open();
      break;
    }
    case '4': {
      modalApi.value = applyRegularModelApi;
      applyRegularModelApi.setData({ id: row.id, applyModalApi }).open();
      break;
    }
    case '5': {
      modalApi.value = applyRenewalContractModelApi;
      applyRenewalContractModelApi
        .setData({ id: row.id, applyModalApi })
        .open();
      break;
    }
    // No default
  }
}

// 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() {
  if (modalApi.value) {
    modalApi.value.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"
    />
    <ApplyEntryModel @reload="onRefresh" />
    <ApplyResignModel @reload="onRefresh" />
    <ApplyTransferModel @reload="onRefresh" />
    <ApplyRegularModel @reload="onRefresh" />
    <ApplyRenewalContractModel @reload="onRefresh" />
  </Page>
</template>
