<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="任务名称" prop="jobName">
        <el-input v-model="queryParams.jobName" clearable placeholder="请输入任务名称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="任务简称" prop="jobSimpleName">
        <el-input v-model="queryParams.jobSimpleName" clearable placeholder="请输入任务简称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-has-permi="['tool:job:remove']"
          type="danger"
          icon="Delete"
          plain
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-has-permi="['tool:job:export']"
          type="warning"
          icon="Download"
          plain
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-has-permi="['tool:job:query']"
          type="info"
          icon="Operation"
          plain
          @click="handleJobLog"
        >日志</el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
    </el-row>

    <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="jobName" min-width="130" :show-overflow-tooltip="true" />
      <el-table-column label="任务简称" align="center" prop="jobSimpleName" :show-overflow-tooltip="true" />
      <el-table-column label="任务组名" align="center" prop="jobGroup" :show-overflow-tooltip="true" />
      <el-table-column label="cron执行表达式" align="center" prop="cronExpression" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            active-text="正常"
            inactive-text="暂停"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-has-permi="['tool:job:remove']"
            type="danger"
            icon="Delete"
            link
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-dropdown v-has-permi="['tool:job:query']" class="dropdown" size="small" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <el-icon class="d-arrow-right">
                <d-arrow-right />
              </el-icon>
              更多
            </span>
            <template #dropdown>
              <el-dropdown-menu v-has-permi="['tool:job:query']">
                <el-dropdown-item command="handleView" icon="View">任务详细</el-dropdown-item>
                <el-dropdown-item command="handleJobLog" icon="Operation">调度日志</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNumber"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />

    <!-- 任务日志详细 -->
    <el-dialog v-model="openView" title="任务详细" width="700px" append-to-body>
      <el-form :model="form" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务简称：">{{ form.jobSimpleName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首次触发时间：">{{ form.startTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间：">{{ form.endTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次触发时间：">{{ form.previousFireTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次触发时间：">{{ form.nextFireTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{ form.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">{{ statusFormat(form) }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <crontab v-if="form.cronExpression && form.cronExpression.split(' ').length === 7" :expression="form.cronExpression" :hideComponent="['second', 'min', 'hour', 'day', 'month', 'week', 'year']" :hideButton="true" />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Job" setup>
import { listJob, getJob, delJob, changeJobStatus } from '@/api/tool/job'
import Crontab from '@/components/Crontab'

const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_job_status } = proxy.$useDict('sys_job_status')

const jobList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const openView = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNumber: 1,
    pageSize: 10,
    jobName: undefined,
    jobSimpleName: undefined,
    status: undefined
  }
})

const { queryParams, form } = toRefs(data)

/** 查询定时任务列表 */
function getList() {
  loading.value = true
  listJob(queryParams.value).then(res => {
    jobList.value = res.list
    total.value = Number(res.total)
    loading.value = false
  })
}

/** 状态字典翻译 */
function statusFormat(row, column) {
  return proxy.$selectDictLabel(sys_job_status.value, row.status)
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNumber = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.$resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.jobName)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 更多操作触发
function handleCommand(command, row) {
  switch (command) {
    case 'handleView':
      handleView(row)
      break
    case 'handleJobLog':
      handleJobLog(row)
      break
    default:
      break
  }
}

// 任务状态修改
function handleStatusChange(row) {
  const text = row.status === '0' ? '启用' : '暂停'
  proxy.$modal.confirm('确认要 "' + text + '" "' + row.jobName + '" 任务吗?').then(function() {
    return changeJobStatus(row.jobName, row.status)
  }).then(() => {
    proxy.$modal.msgSuccess(text + '成功')
  }).catch(function() {
    row.status = row.status === '0' ? '1' : '0'
  })
}

/** 任务详细信息 */
function handleView(row) {
  getJob(row.jobName).then(res => {
    form.value = res
    openView.value = true
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const jobNames = row.jobName || ids.value
  proxy.$modal.confirm('是否确认删除定时任务编号为 "' + jobNames + '" 的数据项?').then(function() {
    return delJob(jobNames)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

/** 任务日志列表查询 */
function handleJobLog(row) {
  const jobName = row.jobName || ''
  router.push('/tool/job-log/index/' + jobName)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.$download('tool/job/export', {
    ...queryParams.value
  }, `job_${new Date().getTime()}.xls`)
}

getList()
</script>

<style scoped>
.dropdown {
  line-height: inherit;
}
</style>
