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

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

import { ref } from 'vue';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { apiExport, apiPage } from '#/api/hr/contractExpirationReminder';
import { employeeDeptTreeSelect } 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 employeeDetailDrawer from '../employeeInfo/employee-detail-drawer.vue';
import applyRenewalContractModel from './apply-renewal_contract-model.vue';
import { querySchema, useColumns } from './data';
// import Form from './form.vue';

// 左边部门用
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: [
    [
      'contractStartDate',
      ['params[contractStartBeginTime]', 'params[contractStartEndTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
    [
      'contractEndDate',
      ['params[contractEndBeginTime]', 'params[contractEndEndTime]'],
      ['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 [EmployeeDetailDrawer, employeeDetailDrawerApi] = useVbenDrawer({
  connectedComponent: employeeDetailDrawer,
});
const [ApplyRenewalContractModel, applyRenewalContractModelApi] = useVbenModal({
  connectedComponent: applyRenewalContractModel,
});

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<ContractExpirationReminderApi.ContractExpirationReminder>) {
//   switch (code) {
//     case 'delete': {
//       onDelete(row);
//       break;
//     }
//     case 'edit': {
//       onEdit(row);
//       break;
//     }
//     default: {
//       break;
//     }
//   }
// }

// function onRefresh() {
//   gridApi.query();
// }
function onEdit(row: ContractExpirationReminderApi.ContractExpirationReminder) {
  employeeDetailDrawerApi.setData({ id: row.id }).open();
}
function onApplyRenewalContract(
  row: ContractExpirationReminderApi.ContractExpirationReminder,
) {
  applyRenewalContractModelApi
    .setData({
      id: row.id,
      name: row.name,
      deptName: `${row.plate} / ${row.firstLevelDepartment} / ${
        row.secondLevelDepartment
      } / ${row.thirdLevelDepartment}`,
    })
    .open();
}
// function onCreate() {
//   formDrawerApi.setData({}).open();
// }
// function onDelete(row: ContractExpirationReminderApi.ContractExpirationReminder) {
//   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 handleDownloadExcel() {
  commonDownloadExcel(
    apiExport,
    '员工合同续签提醒',
    gridApi.formApi.form.values,
  );
}
</script>
<template>
  <Page auto-content-height content-class="flex gap-[8px] w-full">
    <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
            v-access:code="['employee:contractExpiration:export']"
            @click="handleDownloadExcel"
          >
            <template #icon>
              <ExportOutlined />
            </template>
            导出
          </Button>
          <!-- <Button
            v-access:code="['employee:contractExpirationReminder:add']"
            type="primary"
            @click="onCreate"
          >
            <Plus class="size-5" />
            新增
          </Button> -->
        </Space>
      </template>
      <template #action="{ row }">
        <!-- 租户管理员不可修改admin角色 防止误操作 -->
        <!-- 超级管理员可通过租户切换来操作租户管理员角色 -->
        <!--  -->
        <!-- <template
          v-if="!row.superAdmin && (row.roleKey !== 'admin' || isSuperAdmin)"
        > -->
        <Space>
          <GhostButton
            v-access:code="['employee:contractExpiration:query']"
            @click.stop="onEdit(row)"
          >
            查看
          </GhostButton>
          <GhostButton
            danger
            v-access:code="['employee:info:contractRenewal']"
            @click.stop="onApplyRenewalContract(row)"
          >
            申请合同续约
          </GhostButton>
        </Space>
        <!-- </template> -->
      </template>
    </Grid>
    <ApplyRenewalContractModel />
  </Page>
</template>
