<template>
  <PageWrapper>
    <a-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
    </a-card>
    <a-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :row-selection="{ onChange: onSelectionChange }"
      >
        <template #tableTitle>
          <a-space>
            <a-button type="primary" @click="handleAdd" v-perm="['sys:job:add']">
              <template #icon>
                <PlusOutlined />
              </template>
              添加任务
            </a-button>
            <a-button
              type="danger"
              @click="handleDelete()"
              :disabled="!selectionData.length"
              v-perm="['sys:job:batchDelete']"
            >
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-switch v-model:checked="record.realStatus" @change="handelSetStatus(record)" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="primary"
                @click="handelChangeStatus(record)"
                v-perm="['sys:job:resume']"
                v-if="record.status == 0 || record.status == 2"
              >
                <template #icon><FieldTimeOutlined /></template>
                启动
              </a-button>
              <a-button
                type="primary"
                @click="handelChangeStatus(record)"
                v-perm="['sys:job:pause']"
                v-if="record.status == 1"
              >
                <template #icon><FieldTimeOutlined /></template>
                暂停
              </a-button>
              <a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:job:update']">
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <a-button
                type="primary"
                danger
                @click="handleDelete(record.id)"
                v-perm="['sys:job:delete']"
              >
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
              <a-dropdown>
                <a-button class="ant-dropdown-link" @click.prevent>
                  更多<DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item>
                      <a href="javascript:;" @click="handleJobLog(record.id)">调度日志</a>
                    </a-menu-item>
                    <a-menu-item v-if="record.status == 2">
                      <a href="javascript:;" @click="handelRunOnce(record.id)">执行一次</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </BasicTable>
    </a-card>

    <editDialog
      v-if="editVisible"
      :jobId="jobId"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
    <jobLog v-if="editLogVisible" :jobId="jobId" v-model:visible="editLogVisible" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, nextTick, defineAsyncComponent } from 'vue';
  import { schemas } from './querySchemas';
  import { useForm } from '@/components/Form/index';
  import { TableAction } from '@/components/Table';
  import {
    getJobList,
    jobDelete,
    jobBatchDelete,
    getJobRunOnce,
    setJobStatus,
    getJobPause,
    getJobResume,
  } from '@/api/monitor/job';
  import { columns } from './columns';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    FieldTimeOutlined,
    DownOutlined,
  } from '@ant-design/icons-vue';
  import { Modal, message } from 'ant-design-vue';
  import { useRouter } from 'vue-router';

  /**
   * 导入组件
   */
  const editDialog = defineAsyncComponent(() => import('./edit.vue'));
  const jobLog = defineAsyncComponent(() => import('./log/index.vue'));

  /**
   * 定义参数变量
   */
  const router = useRouter();
  const jobId = ref(0);
  const editVisible = ref(false);
  const editLogVisible = ref(false);
  const selectionData = ref([]);
  const tableRef = ref();

  /**
   * 定义查询参数
   */
  const formParams = reactive({
    jobName: '',
    status: '',
  });

  /**
   * 加载数据列表
   * @param res 参数
   */
  const loadDataTable = async (res: any) => {
    const result = await getJobList({ ...formParams, ...res });
    result.records.map((item) => {
      if (item.status == 0) {
        item.realStatus = false;
      } else {
        item.realStatus = true;
      }
    });
    return result;
  };

  /**
   * 刷新数据列表
   * @param noRefresh 参数
   */
  function reloadTable(noRefresh = '') {
    tableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  /**
   * 注册
   */
  const [register, {}] = useForm({
    rowProps: { gutter: [16, 0] },
    colProps: {
      xs: 24,
      sm: 24,
      md: 12,
      lg: 8,
      xl: 6,
    },
    labelCol: { span: 6, offset: 0 },
    schemas,
  });

  /**
   * 执行提交表单
   */
  function handleSubmit(values) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行重置
   */
  function handleReset() {
    for (const key in formParams) {
      formParams[key] = '';
    }
    reloadTable();
  }

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    jobId.value = 0;
    await nextTick();
    editVisible.value = true;
  };

  /**
   * 执行设置状态
   */
  const handelSetStatus = async (row) => {
    await setJobStatus({ id: row.id, status: row.realStatus ? 1 : 0 });
    message.success('设置成功');
    reloadTable('noRefresh');
  };

  /**
   * 执行编辑
   * @param id 参数
   */
  const handleEdit = async (id) => {
    jobId.value = id;
    await nextTick();
    editVisible.value = true;
  };

  /**
   * 执行状态发生变化
   * @param record 参数
   */
  const handelChangeStatus = async (record) => {
    Modal.confirm({
      title: '提示',
      content: `确定要${record.status == 1 ? '暂停' : '启动'}`,
      onOk: async () => {
        record.status == 1 ? await getJobPause(record.id) : await getJobResume(record.id);
        reloadTable('noRefresh');
      },
    });
  };

  /**
   * 执行一次
   */
  const handelRunOnce = async (id) => {
    Modal.confirm({
      title: '提示',
      content: '确定要执行一次？',
      onOk: async () => {
        await getJobRunOnce(id);
        message.success('执行成功');
      },
    });
  };

  /**
   * 执行删除
   * @param id 参数
   */
  async function handleDelete(id) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除？',
      onOk: async () => {
        id ? await jobDelete(id) : await jobBatchDelete(selectionData.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }

  /**
   * 执行查看调度日志
   * @param id 参数
   */
  const handleJobLog = (id) => {
    // router.push({path:'/monitorJob/log'})
    editLogVisible.value = true;
    jobId.value = id;
  };

  /**
   * 选项发生变化
   * @param value 参数
   */
  function onSelectionChange(value) {
    selectionData.value = value;
  }
</script>

<style lang="scss" scoped></style>
