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

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { JobLog } from '#/api/monitor/job/model';
import type { DictOption } from '#/store/dict';

import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  cleanJobLog,
  deleteJobLog,
  exportJobLog,
  listJobLog,
} from '#/api/monitor/job/joblog';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { querySchema, tableColumns } from './config-data';
import JobLogDrawerComp from './joblog-drawer.vue';

const [JobLogDrawer, jobLogDrawerApi] = useVbenDrawer({
  connectedComponent: JobLogDrawerComp,
});

const formOptions: VbenFormProps = {
  schema: querySchema(),
  wrapperClass: 'grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const route = useRoute();
const jobName = route.query.jobName || '';
const jobGroup = route.query.jobGroup || '';
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  // 配置表格右上角全屏、刷新
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await listJobLog({
          ...formValues,
          jobName,
          jobGroup,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 批量删除岗位
async function removeOperLog() {
  const checkData = basicTableApi.grid.getCheckboxRecords();
  const jobLogIds = checkData.map((item: JobLog) => item.jobLogId);
  if (jobLogIds.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${jobLogIds.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteJobLog(jobLogIds);
    await basicTableApi.reload();
  });
}
// 导出操作日志
async function exportOperLogata() {
  await commonDownloadExcel(
    exportJobLog,
    '调度日志数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
// 清空操作日志
function cleanAll() {
  ElMessageBox.confirm(`确定要清空所有调度日志数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await cleanJobLog();
    await basicTableApi.reload();
  });
}
// 日志详情
function handleViewer(jobLog: JobLog) {
  jobLogDrawerApi.setData<JobLog>(jobLog).open();
}
// 获取状态字典值
const dictRef = ref<DictOption[]>([]);
// 获取操作类型
const jobGroupRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictRef.value = await getDictOptions(DictEnum.SYS_COMMON_STATUS);
  jobGroupRef.value = await getDictOptions(DictEnum.SYS_JOB_GROUP);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="调度日志列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton @click="exportOperLogata"> 导出 </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="removeOperLog"
          >
            删除
          </ElButton>
          <ElButton type="danger" @click="cleanAll"> 清空 </ElButton>
        </ElSpace>
      </template>
      <template #jobGroup="{ row }">
        <DictTag :value="row.jobGroup" :dicts="jobGroupRef" />
      </template>
      <template #status="{ row }">
        <DictTag :value="row.status" :dicts="dictRef" />
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleViewer(row)"
          >
            详情
          </ElButton>
        </ElSpace>
      </template>
    </BasicTable>
    <JobLogDrawer />
  </Page>
</template>
