<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm } from 'naive-ui';
import { cleanJobLog, delJobLog, listJobLog } from '@/service/api/monitor/jobLog';
import { useRouterPush } from '@/hooks/common/router';
import { useTabStore } from '@/store/modules/tab';
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 JobLogSearch from '@/views/monitor/job/job-log/modules/job-log-search.vue';
import JobLogOperateView from '@/views/monitor/job/job-log/modules/job-log-operate-view.vue';

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

const statusOptions = ref<Api.SystemManage.DictInfo[]>([]);
const jobGroupOptions = [
  { label: '默认', value: '1' },
  { label: '系统', value: '2' }
];
getDicts('sys_common_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: listJobLog,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: null,
    jobGroup: null,
    status: null,
    params: []
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'jobLogId',
      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: 'jobMessage',
      title: '日志信息',
      minWidth: 160,
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'status',
      title: '执行状态',
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }
        return statusOptions.value.find(item => item.dictValue === row.status)?.dictLabel;
      }
    },
    {
      key: 'createTime',
      title: '执行时间',
      width: 160,
      align: 'center'
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => handleView(row)}>
            详细
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.jobLogId)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { checkedRowKeys, drawerVisible, editingData, onDeleted, onBatchDeleted } = useTableOperate(
  data,
  getData
);

// 编辑
async function handleView(row: Api.SystemManage.JobLog) {
  editingData.value = row;
  drawerVisible.value = true;
}

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

// 清空
function handleClean() {
  cleanJobLog().then(res => {
    if (!res.error) {
      window.$message?.success('清空成功');
      getData();
    }
  });
}

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

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

function lookLog() {
  tabStore.removeActiveTab();
  routerPushByKey('monitor_job');
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <JobLogSearch
      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"
          :show-add-btn="false"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #middle>
            <NPopconfirm @positive-click="handleClean">
              <template #trigger>
                <NButton size="small" ghost type="error">
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  清空
                </NButton>
              </template>
              是否确认清空所有调度日志数据项？
            </NPopconfirm>
            <NButton :loading="exportLoading" type="success" ghost size="small" @click="handleExport">
              <template #icon>
                <SvgIcon icon="mdi:file-export-outline"></SvgIcon>
              </template>
              导出
            </NButton>
            <NButton type="warning" ghost size="small" @click="lookLog">
              <template #icon>
                <SvgIcon icon="ep:close"></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.JobLog) => row.jobLogId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <JobLogOperateView
        v-model:visible="drawerVisible"
        :row-data="editingData"
        :status-options="statusOptions"
        :job-group-options="jobGroupOptions"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
