<template>
  <div>
    <n-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :autoScrollX="true"
      >
        <template #tableTitle>
          <n-space>
            <n-button type="primary" @click="handleAdd" v-perm="['sys:job:add']">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>

            <n-button
              type="error"
              @click="handleDelete"
              :disabled="!rowKeys.length"
              v-perm="['sys:job:batchDelete']"
            >
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <editDialog
      ref="createModalRef"
      :jobId="jobId"
      v-if="editVisible"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
    <jobLog v-if="editLogVisible" :jobId="jobId" v-model:visible="editLogVisible" />
  </div>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref, unref } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import {
    getJobList,
    jobDelete,
    jobBatchDelete,
    getJobRunOnce,
    setJobStatus,
    getJobPause,
    getJobResume,
  } from '@/api/monitor/job';
  import { columns } from './columns';
  import { PlusOutlined, DeleteOutlined, FormOutlined, FieldTimeOutlined } from '@vicons/antd';
  import CreateModal from './CreateModal.vue';
  import editDialog from './edit.vue';
  import jobLog from './log/index.vue';
  import { basicModal, useModal } from '@/components/Modal';
  import { schemas } from './querySchemas';
  import { renderIcon } from '@/utils';

  const message = useMessage();
  const dialog = useDialog();
  const basicTableRef = ref();
  const createModalRef = ref();
  const editVisible = ref(false);
  const editLogVisible = ref(false);
  const jobId = ref(0);
  const rowKeys = ref([]);
  const exportLoading = ref(false);

  const showModal = ref(false);
  const formParams = reactive({
    jobName: '',
    status: '',
  });

  const actionColumn = reactive({
    width: 350,
    title: '操作',
    align: 'center',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '启动',
            type: 'success',
            icon: renderIcon(FieldTimeOutlined),
            onClick: handelChangeStatus.bind(null, record),
            auth: ['sys:job:resume'],
            ifShow: () => {
              return record.status == 0 || record.status == 2;
            },
          },
          {
            label: '暂停',
            type: 'warning',
            icon: renderIcon(FieldTimeOutlined),
            onClick: handelChangeStatus.bind(null, record),
            auth: ['sys:job:pause'],
            ifShow: () => {
              return record.status == 1;
            },
          },
          {
            label: '编辑',
            icon: renderIcon(FormOutlined),
            type: 'info',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:job:update'],
          },
          {
            label: '删除',
            icon: renderIcon(DeleteOutlined),
            type: 'error',
            onClick: handleDelete.bind(null, record),
            auth: ['sys:job:delete'],
          },
        ],
        dropDownActions: [
          {
            label: '执行一次',
            key: 'runOnce',
            auth: ['sys:job:runOnce'],
            ifShow: () => {
              return record.status == 2;
            },
          },
          {
            label: '调度日志',
            key: 'jobLog',
            auth: ['sys:job:jobLog'],
          },
        ],
        select: (key) => {
          if (key == 'runOnce') {
            handelRunOnce(record);
          } else if (key == 'jobLog') {
            handleJobLog(record);
          }
        },
      });
    },
  });

  function addTable() {
    showModal.value = true;
  }

  const loadDataTable = async (res) => {
    rowKeys.value = [];
    const result = await getJobList({ ...formParams, ...res });
    return result;
  };

  function onCheckedRow(keys) {
    rowKeys.value = keys;
  }

  function reloadTable(noRefresh = '') {
    basicTableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  function handleSubmit(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 110,
    schemas,
  });

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    jobId.value = 0;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };
  /**
   * 执行编辑
   */
  async function handleEdit(record: Recordable) {
    jobId.value = record.id;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  }
  /**
   * 执行变更状态
   * @param record 参数
   */
  const handelChangeStatus = async (record) => {
    dialog.warning({
      title: '提示',
      content: `确定要${record.status == 1 ? '暂停' : '启动'}`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        record.status == 1 ? await getJobPause(record.id) : await getJobResume(record.id);
        reloadTable('noRefresh');
      },
    });
  };
  /**
   * 执行一次
   */
  const handelRunOnce = async (record) => {
    dialog.warning({
      title: '提示',
      content: '确定要执行一次？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await getJobRunOnce(record.id);
        message('执行成功');
      },
    });
  };
  /**
   * 执行查看日志
   * @param record 参数
   */
  const handleJobLog = (record) => {
    console.log(record);
    // router.push({path:'/monitorJob/log'})
    editLogVisible.value = true;
    jobId.value = record.id;
  };
  /**
   * 执行删除
   * @param id 参数
   */
  async function handleDelete(record) {
    dialog.warning({
      title: '提示',
      content: '确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        record.id ? await jobDelete(record.id) : await jobBatchDelete(rowKeys.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }
</script>

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