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

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

import { ref } from 'vue';

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

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

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

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

/**
 * 导入
 */
const [EmployeeImportModal, employeeImportModalApi] = useVbenModal({
  connectedComponent: employeeImportModal,
});
function handleImport() {
  employeeImportModalApi.open();
}

const [ApplyEntryModel, applyEntryModelApi] = useVbenModal({
  connectedComponent: applyEntryModel,
});
const [ApplyTransferModel, applyTransferModelApi] = useVbenModal({
  connectedComponent: applyTransferModel,
});
const [ApplyResignModel, applyResignModelApi] = useVbenModal({
  connectedComponent: applyResignModel,
});

// 左边部门用
const selectDeptId = ref<number[]>([]);
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',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'entryDate',
      ['params[entryBeginTime]', 'params[entryEndTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
  handleReset: async () => {
    selectDeptId.value = [];

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

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

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 onRefresh() {
  gridApi.query();
}
function onEdit(row: EmployeeInfoApi.Employee) {
  // formDrawerApi.setData({ id: row.id }).open();
  employeeDetailDrawerApi.setData({ id: row.id }).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}
function onEntryApply(row: EmployeeInfoApi.Employee) {
  applyEntryModelApi
    .setData({
      id: row.id,
      name: row.name,
      deptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
    })
    .open();
}

function onResign(row: EmployeeInfoApi.Employee) {
  applyResignModelApi
    .setData({
      id: row.id,
      name: row.name,
      deptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
    })
    .open();
}

function onTransfer(row: EmployeeInfoApi.Employee) {
  applyTransferModelApi
    .setData({
      id: row.id,
      name: row.name,
      oldDeptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
    })
    .open();
}
function handleDownloadExcel(row: EmployeeInfoApi.Employee) {
  commonDownloadExcel(apiExport, '员工信息', row.id);
}
function handleDownloadEmployeeList() {
  commonDownloadExcel(
    exportEmployeeList,
    '员工信息',
    gridApi.formApi.form.values,
  );
}
</script>
<template>
  <Page auto-content-height content-class="flex gap-[8px] w-full">
    <FormDrawer @success="onRefresh" />
    <EmployeeDetailDrawer />
    <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:info:export']"
            @click.stop="handleDownloadEmployeeList"
          >
            <template #icon>
              <ExportOutlined />
            </template>
            导出
          </Button>
          <Button
            v-access:code="['employee:info:import']"
            @click="handleImport"
          >
            <template #icon>
              <UploadOutlined />
            </template>
            导入
          </Button>
          <Button
            v-access:code="['employee:info:add']"
            type="primary"
            @click="onCreate"
          >
            <PlusOutlined />
            入职
          </Button>
        </Space>
      </template>
      <template #action="{ row }">
        <!-- 租户管理员不可修改admin角色 防止误操作 -->
        <!-- 超级管理员可通过租户切换来操作租户管理员角色 -->
        <!--  -->
        <!-- <template
          v-if="!row.superAdmin && (row.roleKey !== 'admin' || isSuperAdmin)"
        > -->
        <Space>
          <GhostButton
            v-access:code="['employee:info:export']"
            @click.stop="handleDownloadExcel(row)"
          >
            导出简历
          </GhostButton>
          <GhostButton
            v-access:code="['employee:info:edit']"
            @click.stop="onEdit(row)"
          >
            查看
          </GhostButton>
          <GhostButton
            v-access:code="['employee:info:add']"
            @click.stop="onEntryApply(row)"
          >
            申请入职
          </GhostButton>
          <GhostButton
            v-access:code="['employee:info:edit']"
            @click.stop="onTransfer(row)"
          >
            申请调配
          </GhostButton>
          <GhostButton
            danger
            v-access:code="['employee:info:resign']"
            @click.stop="onResign(row)"
          >
            申请离职
          </GhostButton>
        </Space>
        <!-- </template> -->
      </template>
    </Grid>
    <EmployeeImportModal @reload="onRefresh" />
    <ApplyEntryModel @reload="onRefresh" />
    <ApplyTransferModel @reload="onRefresh" />
    <ApplyResignModel @reload="onRefresh" />
  </Page>
</template>
