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

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

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

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  changeStatus,
  deleteJob,
  exportJob,
  jobRun,
  listJob,
} from '#/api/monitor/job/job';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { columns, querySchema } from './config-data';
import JobDrawerComp from './job-drawer.vue';

const [JobDrawer, jobDrawerApi] = useVbenDrawer({
  connectedComponent: JobDrawerComp,
});
// 添加打开侧拉
function openDrawer() {
  jobDrawerApi.setData({ isUpdate: false }).open();
}
// 编辑侧拉打开
function handleEdit(job: Job) {
  jobDrawerApi.setData({ ...job, isUpdate: true }).open();
}
const formOptions: VbenFormProps = {
  commonConfig: {
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await listJob({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 删除多个定时任务
function deleteJobs() {
  // 获取全部选中的数据
  const checkRecords = BasicTableApi.grid.getCheckboxRecords();
  // 数据转换只要jobId
  const ids = checkRecords.map((item: Job) => item.jobId);
  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除定时任务
    await deleteJob(ids!);
    // 重置查询
    await BasicTableApi.reload();
  });
}
// 单个删除
async function confirmEvent(job: Job) {
  // 删除定时任务
  await deleteJob([job.jobId]);
  // 重置查询
  await BasicTableApi.reload();
}
// 运行一次job
async function jobRunHandle(job: Job) {
  // 调用运行一次接口
  await jobRun(job.jobGroup, job.jobId);
  // 重置查询
  await BasicTableApi.reload();
}
// 修改定时任务状态
function roleStatusChange(job: Job) {
  ElMessageBox.confirm(
    `确定要${job.status === '0' ? '启用' : '停用'}${job.jobName}?`,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      await changeStatus(job.jobId, job.status);
    })
    .catch(() => {
      job.status = job.status === '0' ? '1' : '0';
    });
}
// 查看定时任务
function viewHandle(job: Job) {
  jobDrawerApi.setData({ ...job, isView: true }).open();
}
// 导出定时任务
async function exportRoles() {
  await commonDownloadExcel(
    exportJob,
    '定时任务数据',
    BasicTableApi.formApi.form.values,
  );
}
// 跳转调度日志页面
const router = useRouter();
function jobLogHandle(job?: Job) {
  if (job) {
    router.push({
      name: 'JobLog',
      query: { jobName: job.jobName, jobGroup: job.jobGroup },
    });
  } else {
    router.push('/monitor/job-log');
  }
}
// 获取字典值
const dictRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictRef.value = await getDictOptions(DictEnum.SYS_JOB_GROUP);
});
const { hasAccessByCodes } = useAccess();
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="定时任务">
      <template #jobGroup="{ row }">
        <template v-for="item in dictRef" :key="item">
          <span v-if="item.value === row.jobGroup"> {{ item.label }} </span>
        </template>
      </template>
      <template #status="{ row }">
        <ElSwitch
          v-model="row.status"
          inline-prompt
          active-text="正常"
          inactive-text="暂停"
          active-value="0"
          inactive-value="1"
          style="--el-switch-off-color: #ff4949"
          @change="roleStatusChange(row)"
          :disabled="!hasAccessByCodes(['monitor:job:edit'])"
        />
      </template>
      <template #toolbar-tools>
        <ElSpace>
          <ElButton @click="exportRoles" v-access:code="['monitor:job:export']">
            导出
          </ElButton>
          <ElButton
            type="warning"
            @click="jobLogHandle"
            v-access:code="['monitor:job:query']"
          >
            日志
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(BasicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteJobs"
            v-access:code="['monitor:job:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['monitor:job:add']"
          >
            {{ $t('pages.common.add') }}
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace v-if="row.roleId !== 1">
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['monitor:job:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['monitor:job:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
          <ElDropdown>
            <ElButton
              type="primary"
              size="small"
              link
              v-access:code="['monitor:job:changeStatus', 'monitor:job:query']"
            >
              更多
            </ElButton>
            <template #dropdown>
              <ElDropdownMenu>
                <span v-access:code="['monitor:job:changeStatus']">
                  <ElDropdownItem @click="jobRunHandle(row)">
                    执行一次
                  </ElDropdownItem>
                </span>
                <span v-access:code="['monitor:job:query']">
                  <ElDropdownItem @click="viewHandle(row)">
                    任务详情
                  </ElDropdownItem>
                </span>
                <span v-access:code="['monitor:job:query']">
                  <ElDropdownItem @click="jobLogHandle(row)">
                    调度日志
                  </ElDropdownItem>
                </span>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </ElSpace>
      </template>
    </BasicTable>
    <JobDrawer @reload="BasicTableApi.reload()" />
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
