<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <Authority value="api:yt:schedule:post">
          <a-button type="primary" @click="handleCreateOrEdit(null)"> 新增 </a-button>
        </Authority>
        <Authority value="api:yt:schedule:get">
          <a-button type="primary"> 导出 </a-button>
        </Authority>
        <Authority value="api:yt:schedule:delete">
          <Popconfirm
            title="您确定要批量删除数据"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDeleteOrBatchDelete(null)"
          >
            <a-button type="primary" color="error" :disabled="hasBatchDelete"> 批量删除 </a-button>
          </Popconfirm>
        </Authority>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              icon: 'clarity:note-edit-line',
              auth: 'api:yt:schedule:update',
              onClick: handleCreateOrEdit.bind(null, record),
              ifShow: record.status === 0 && EJobGroup.REPORT !== record.jobGroup,
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              auth: 'api:yt:schedule:delete',
              ifShow: record.status === 0,
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDeleteOrBatchDelete.bind(null, record),
              },
            },
            {
              label: '查看',
              icon: 'ant-design:eye-outlined',
              onClick: handleViewDetail.bind(null, record),
              ifShow: record.status === 1,
            },
          ]"
          :dropDownActions="[
            {
              label: '执行一次',
              icon: 'ant-design:caret-right-filled',
              popConfirm: {
                title: '确认要立即执行一次' + '“' + record.jobName + '”' + '任务吗？',
                confirm: handleRunOne.bind(null, record),
              },
            },
            {
              label: '任务详细',
              icon: 'ant-design:eye-outlined',
              onClick: handleTaskDetailModal.bind(null, record),
            },
            {
              label: '调度日志',
              icon: 'ant-design:insert-row-below-outlined',
              onClick: handleSchedulingLogFunc.bind(null, record),
            },
          ]"
        />
      </template>
      <template #status="{ record }">
        <Switch
          :disabled="disabledSwitch"
          :checked="record.status === 1"
          :loading="record.pendingStatus"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          @change="(checked: boolean) => statusChange(checked, record)"
        />
      </template>
    </BasicTable>
    <ScheduledDrawer @register="registerDrawer" @success="handleSuccess" />
    <TaskDetailPreviewModal @register="registerModalTaskDetail" />
    <SchedueLog @register="registerModalSchedueLog" />
  </div>
</template>
<script setup lang="ts">
  import { nextTick, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { columnSchedue, searchSchedueFormSchema } from './config.form.data';
  import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
  import {
    deleteSchedueManage,
    scheduePage,
    putSchedueByidAndStatusManage,
    postRunSchedueConfigManage,
  } from '/@/api/schedue/schedueManager';
  import { Popconfirm, Switch } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import TaskDetailPreviewModal from './TaskDetailPreviewModal.vue';
  import SchedueLog from './SchedueLog.vue';
  import ScheduledDrawer from './ScheduledDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { Authority } from '/@/components/Authority';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { EJobGroup } from './config.data';

  const disabledSwitch = ref(false);
  const { createMessage } = useMessage();
  const [registerTable, { setProps, reload, setSelectedRowKeys }] = useTable({
    title: '定时任务列表',
    api: scheduePage,
    columns: columnSchedue,
    showIndexColumn: false,
    clickToRowSelect: false,
    useSearchForm: true,
    ellipsis: true,
    showTableSetting: true,
    bordered: true,
    formConfig: {
      labelWidth: 120,
      schemas: searchSchedueFormSchema,
      fieldMapToTime: [['sendTime', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm:ss']],
    },
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
  });
  // 刷新
  const handleSuccess = () => {
    reload();
  };
  const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
    useBatchDelete(deleteSchedueManage, handleSuccess, setProps);
  selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
    // Demo:status为1的选择框禁用
    if (record.status === 1) {
      return { disabled: true };
    } else {
      return { disabled: false };
    }
  };

  nextTick(() => {
    setProps(selectionOptions);
  });
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerModalTaskDetail, { openModal: openModalTaskDetail }] = useModal();
  const [registerModalSchedueLog, { openModal: openModalSchedueLog }] = useModal();
  const handleSchedulingLogFunc = (record: Recordable) => {
    openModalSchedueLog(true, {
      isUpdate: 2,
      record,
    });
  };
  const handleTaskDetailModal = (record: Recordable) => {
    openModalTaskDetail(true, {
      isUpdate: true,
      record,
    });
  };
  // 新增或编辑
  const handleCreateOrEdit = (record: Recordable | null) => {
    if (record) {
      openDrawer(true, {
        isUpdate: true,
        record,
        isView: true,
      });
    } else {
      openDrawer(true, {
        isUpdate: false,
        isView: true,
      });
    }
  };

  const statusChange = async (checked, record) => {
    try {
      setProps({
        loading: true,
      });
      setSelectedRowKeys([]);
      resetSelectedRowKeys();
      disabledSwitch.value = true;
      const newStatus = checked ? 1 : 0;
      const res = await putSchedueByidAndStatusManage(record.id, newStatus);
      if (res && newStatus) {
        createMessage.success(`启用成功`);
      } else {
        createMessage.success('禁用成功');
      }
    } finally {
      setTimeout(() => {
        setProps({
          loading: false,
        });
        disabledSwitch.value = false;
      }, 500);
      reload();
    }
  };
  const handleRunOne = async (record: Recordable) => {
    const res = await postRunSchedueConfigManage(record.id);
    if (res?.code === 200) {
      createMessage.success(`执行一次任务"${record.jobName}"成功`);
    }
  };
  const handleViewDetail = (record: Recordable) => {
    if (record) {
      openDrawer(true, {
        isUpdate: true,
        record,
        isView: false,
      });
    }
  };
</script>
<style lang="less" scoped></style>
