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

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

import { ref, shallowRef } from 'vue';

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

import { ExportOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { Button, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { employeeDeptTreeSelect } from '#/api/hr/employeeInfo';
import { apiExport, apiPage } from '#/api/hr/partTimeInfo';
import { GhostButton } from '#/components/global/button';
import { commonDownloadExcel } from '#/utils/file/download';
import DeptTree from '#/views/auth/user/deptTree.vue';

import { applyModal } from '../../workflow/components';
import applyEntryModel from '../employeeInfo/apply-entry-model.vue';
import applyResignModel from '../employeeInfo/apply-resign-model.vue';
import applyTransferModel from '../employeeInfo/apply-transfer-model.vue';
import employeeDetailDrawer from '../employeeInfo/employee-detail-drawer.vue';
import { querySchema, useColumns } from './data';
import Form from './form.vue';
import partTimeEmployeeImportModal from './partTime-employee-import-modal.vue';

/**
 * 导入
 */
const [PartTimeEmployeeImportModal, partTimeEmployeeImportModalApi] =
  useVbenModal({
    connectedComponent: partTimeEmployeeImportModal,
  });
function handleImport() {
  partTimeEmployeeImportModalApi.open();
}

const [ApplyModal, applyModalApi] = useVbenModal({
  connectedComponent: applyModal,
});
const [ApplyEntryModel, applyEntryModelApi] = useVbenModal({
  connectedComponent: applyEntryModel,
});
const [ApplyTransferModel, applyTransferModelApi] = useVbenModal({
  connectedComponent: applyTransferModel,
});
const [ApplyResignModel, applyResignModelApi] = useVbenModal({
  connectedComponent: applyResignModel,
});
const modalApi = shallowRef<ExtendedModalApi | null>(null);

// 左边部门用
const selectDeptId = ref<number[]>([]);
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  collapsed: true,
  schema: querySchema,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  handleReset: async () => {
    selectDeptId.value = [];

    const { formApi, reload } = gridApi;
    await formApi.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
};

const [EmployeeDetailDrawer, employeeDetailDrawerApi] = useVbenDrawer({
  connectedComponent: employeeDetailDrawer,
});

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 = {}) => {
          // 部门树选择处理
          if (selectDeptId.value.length === 1) {
            formValues.belongDeptId = selectDeptId.value[0];
          } else {
            Reflect.deleteProperty(formValues, 'belongDeptId');
          }
          return await apiPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
  } as VxeTableGridOptions,
});

// function onActionClick({
//   code,
//   row,
// }: OnActionClickParams<PartTimeInfoApi.PartTimeInfo>) {
//   switch (code) {
//     case 'delete': {
//       onDelete(row);
//       break;
//     }
//     case 'edit': {
//       onEdit(row);
//       break;
//     }
//     default: {
//       break;
//     }
//   }
// }

function onRefresh() {
  gridApi.query();
}
function onShowDetail(row: PartTimeInfoApi.PartTimeInfo) {
  employeeDetailDrawerApi.setData({ id: row.id, partTimeFlag: true }).open();
}
function onEdit(row: PartTimeInfoApi.PartTimeInfo) {
  formDrawerApi.setData(row).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}
// function onDelete(row: PartTimeInfoApi.PartTimeInfo) {
//   const hideLoading = message.loading({
//     content: `正在删除${row.name}...`,
//     duration: 0,
//     key: 'action_process_msg',
//   });
//   apiDelete(row.id || 0)
//     .then(() => {
//       message.success({
//         content: `${row.name}删除成功`,
//         key: 'action_process_msg',
//       });
//       onRefresh();
//     })
//     .catch(() => {
//       hideLoading();
//     });
// }
function onEntryApply(row: PartTimeInfoApi.PartTimeInfo) {
  modalApi.value = applyEntryModelApi;
  applyEntryModelApi
    .setData({
      employeeId: row.id,
      name: row.name,
      deptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
      applyModalApi,
    })
    .open();
}

function onResign(row: PartTimeInfoApi.PartTimeInfo) {
  modalApi.value = applyResignModelApi;
  applyResignModelApi
    .setData({
      employeeId: row.id,
      name: row.name,
      deptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
      applyModalApi,
    })
    .open();
}

function onTransfer(row: PartTimeInfoApi.PartTimeInfo) {
  modalApi.value = applyTransferModelApi;
  applyTransferModelApi
    .setData({
      employeeId: row.id,
      name: row.name,
      oldDeptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
      applyModalApi,
    })
    .open();
}

async function handleCompleteOrCancel() {
  if (modalApi.value) {
    modalApi.value.close();
  }
  gridApi.query();
}
function handleDownloadExcel() {
  commonDownloadExcel(apiExport, '兼职员工信息', gridApi.formApi.form.values);
}
</script>
<template>
  <Page auto-content-height content-class="flex gap-[8px] w-full">
    <EmployeeDetailDrawer />
    <FormDrawer @success="onRefresh" />
    <DeptTree
      v-model:select-dept-id="selectDeptId"
      :api="employeeDeptTreeSelect"
      class="w-[260px]"
      @reload="() => gridApi.reload()"
      @select="() => gridApi.reload()"
    />
    <Grid class="flex-1 overflow-hidden" table-title="兼职员工信息列表">
      <template #toolbar-tools>
        <Space>
          <Button
            type="primary"
            ghost
            v-access:code="['employee:partTimeInfo:export']"
            @click="handleDownloadExcel"
          >
            <template #icon>
              <ExportOutlined />
            </template>
            导出
          </Button>
          <Button
            v-access:code="['employee:partTimeInfo:import']"
            @click="handleImport"
          >
            <template #icon>
              <UploadOutlined />
            </template>
            导入
          </Button>
          <Button
            v-access:code="['employee:partTimeInfo:add']"
            type="primary"
            @click="onCreate"
          >
            <Plus class="size-5" />
            新增兼职
          </Button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <GhostButton
            v-access:code="['employee:partTimeInfo:query']"
            @click.stop="onShowDetail(row)"
          >
            查看
          </GhostButton>
          <GhostButton
            v-access:code="['employee:partTimeInfo:edit']"
            @click.stop="onEdit(row)"
          >
            编辑
          </GhostButton>
          <GhostButton
            v-if="[0].includes(row.status)"
            v-access:code="['employee:info:add']"
            @click.stop="onEntryApply(row)"
          >
            申请入职
          </GhostButton>
          <GhostButton
            v-if="[1, 2].includes(row.status)"
            v-access:code="['employee:info:edit']"
            @click.stop="onTransfer(row)"
          >
            申请调配
          </GhostButton>
          <GhostButton
            danger
            v-if="[1, 2].includes(row.status)"
            v-access:code="['employee:info:resign']"
            @click.stop="onResign(row)"
          >
            申请离职
          </GhostButton>
        </Space>
      </template>
    </Grid>
    <PartTimeEmployeeImportModal @reload="onRefresh" />
    <ApplyEntryModel />
    <ApplyTransferModel />
    <ApplyResignModel />
    <ApplyModal
      @complete="handleCompleteOrCancel"
      @cancel="handleCompleteOrCancel"
    />
  </Page>
</template>
