<script setup lang="tsx">
import { ref } from 'vue';
import { type DropdownOption, NButton, NDropdown, NPopconfirm, NSwitch } from 'naive-ui';
import { useRouterPush } from '@/hooks/common/router';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useDownLoadFile } from '@/hooks/common/download';
import { $t } from '@/locales';
import { getDicts } from '@/service/api/system/dict';
import { useAppStore } from '@/store/modules/app';
import type { ModelCallback } from '@/hooks/common/form';
import { addJob, changeJobStatus, delJob, getJob, listJob, runJob, updateJob } from '@/service/api/monitor/job';
import JobSearch from '@/views/monitor/job/modules/job-search.vue';
import JobOperateModel from '@/views/monitor/job/modules/job-operate-model.vue';
import JobOperateView from '@/views/monitor/job/modules/job-operate-view.vue';

const appStore = useAppStore();
const { loading: exportLoading, downLoadExcel } = useDownLoadFile();
const { routerPushByKey } = useRouterPush();

const statusOptions = ref<Api.SystemManage.DictInfo[]>([]);
const jobGroupOptions = [
  { label: '默认', value: '1' },
  { label: '系统', value: '2' }
];
const misfirePolicyOptions = [
  { label: '立即执行', value: '1' },
  { label: '执行一次', value: '2' },
  { label: '放弃执行', value: '3' }
];
const optionsDropdown: DropdownOption[] = [
  { key: 'runOne', label: '执行一次' },
  { key: 'lookView', label: '任务详细' },
  { key: 'lookLog', label: '调度日志' }
];
const drawerVisibleView = ref<boolean>(false);
getDicts('sys_job_status').then(response => {
  if (!response.error) {
    statusOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: listJob,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: null,
    jobGroup: null,
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'jobId',
      title: '任务编号',
      width: 150,
      align: 'center'
    },
    {
      key: 'jobName',
      title: '任务名称',
      minWidth: 120,
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'jobGroup',
      title: '任务组名',
      minWidth: 120,
      align: 'center',
      render: row => {
        if (row.jobGroup === null) return null;
        return jobGroupOptions.find(item => item.value === row.jobGroup)?.label || '/';
      }
    },
    {
      key: 'invokeTarget',
      title: '调用目标字符串',
      minWidth: 200,
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'cronExpression',
      title: 'cron执行表达式',
      minWidth: 160,
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }
        return (
          <NSwitch
            v-model:value={row.status}
            checked-value="0"
            unchecked-value="1"
            onUpdate:value={() => handleStatusChange(row)}
          />
        );
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          {!row.admin && (
            <>
              <NButton type="primary" ghost size="small" onClick={() => edit(row.jobId)}>
                {$t('common.edit')}
              </NButton>
              <NPopconfirm onPositiveClick={() => handleDelete(row.jobId)}>
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton type="error" ghost size="small">
                      {$t('common.delete')}
                    </NButton>
                  )
                }}
              </NPopconfirm>
              <NDropdown trigger="hover" options={optionsDropdown} onSelect={key => handleDropdownSelect(key, row)}>
                <NButton type="warning" ghost size="small">
                  更多
                </NButton>
              </NDropdown>
            </>
          )}
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

// 用户状态修改
function handleStatusChange(row: Api.SystemManage.Job) {
  const text = row.status === '0' ? '启用' : '停用';
  window.$dialog?.warning({
    title: '提示',
    content: `确定要${text}"${row.jobName}"任务吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      return changeJobStatus(row.jobId, row.status).then(res => {
        if (!res.error) {
          window.$message?.success(`${text}成功`);
        } else {
          row.status = row.status === '0' ? '1' : '0';
        }
      });
    },
    onNegativeClick: () => {
      row.status = row.status === '0' ? '1' : '0';
    },
    onClose: () => {
      row.status = row.status === '0' ? '1' : '0';
    },
    onEsc: () => {
      row.status = row.status === '0' ? '1' : '0';
    }
  });
}

// 点击更多
function handleDropdownSelect(key: string, row: Api.SystemManage.Job) {
  if (key === 'runOne') {
    window.$dialog?.warning({
      title: '提示',
      content: `确认要立即执行一次"${row.jobName}"任务吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        return runJob(row.jobId, row.jobGroup).then(res => {
          if (!res.error) {
            window.$message?.success(`执行成功`);
          }
        });
      }
    });
  } else if (key === 'lookView') {
    getJob(row.jobId).then(response => {
      if (!response.error) {
        editingData.value = response.data as Api.SystemManage.Job;
        drawerVisibleView.value = true;
      }
    });
  } else if (key === 'lookLog') {
    lookLog(row);
  }
}

// 单个删除
function handleDelete(id: Api.SystemManage.Job['jobId']) {
  delJob([id]).then(res => {
    if (!res.error) {
      onDeleted();
    }
  });
}

// 批量删除
function handleBatchDelete() {
  delJob(checkedRowKeys.value).then(res => {
    if (!res.error) {
      onBatchDeleted();
    }
  });
}

// 编辑
async function edit(id: Api.SystemManage.Job['jobId']) {
  getJob(id).then(res => {
    if (!res.error) {
      editingData.value = res.data;
      handleEdit();
    }
  });
}

// 提交
function handleSubmit(callback: (params: ModelCallback<Api.SystemManage.Job>) => void) {
  callback({
    add: addJob,
    edit: updateJob,
    getData
  });
}

// 导出
function handleExport() {
  downLoadExcel('/monitor/job/export', searchParams);
}

function lookLog(row: Api.SystemManage.Job | null = null) {
  const jobId = row?.jobId || 0;
  routerPushByKey('monitor_job_job-log', { query: { jobId: jobId.toString() } });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <JobSearch
      v-model:model="searchParams"
      :status-options="statusOptions"
      :job-group-options="jobGroupOptions"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard title="参数列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #middle>
            <NButton :loading="exportLoading" type="success" ghost size="small" @click="handleExport">
              <template #icon>
                <SvgIcon icon="mdi:file-export-outline"></SvgIcon>
              </template>
              导出
            </NButton>
            <NButton type="info" ghost size="small" @click="lookLog()">
              <template #icon>
                <SvgIcon icon="ep:operation"></SvgIcon>
              </template>
              日志
            </NButton>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="(row: Api.SystemManage.Job) => row.jobId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <JobOperateModel
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :status-options="statusOptions"
        :job-group-options="jobGroupOptions"
        :misfire-policy-options="misfirePolicyOptions"
        @submit="handleSubmit"
      />
      <JobOperateView
        v-model:visible="drawerVisibleView"
        :row-data="editingData"
        :status-options="statusOptions"
        :job-group-options="jobGroupOptions"
        :misfire-policy-options="misfirePolicyOptions"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
