<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="searchQueryFormRef" :model="searchQueryFormEntity" :label-position="labelPosition"
                   label-width="158px" style="max-width: 100%" status-icon>
            <div style="display: flex;justify-content: space-between;">
              <el-row>
                <el-form-item label="任务名">
                  <el-input v-model="searchQueryFormEntity.jobName" @keyup.enter="search()" clearable/>
                </el-form-item>
                <el-form-item label="定时器类型">
                  <el-select-v2 style="width: 196px;" v-model="searchQueryFormEntity.timerType" placeholder="定时器类型"
                                :options="addAllOptionOfOptions(timerTypeOptions)"
                                @change="search()"></el-select-v2>
                </el-form-item>
                <el-form-item label="任务状态">
                  <el-select-v2 style="width: 196px;" v-model="searchQueryFormEntity.jobStatus" placeholder="任务状态"
                                :options="addAllOptionOfOptions(jobStatusOptions)"
                                @change="search()"></el-select-v2>
                </el-form-item>
                <el-form-item label="任务类">
                  <el-input v-model="searchQueryFormEntity.jobClass" @keyup.enter="search()" clearable/>
                </el-form-item>
              </el-row>
              <div style="align-content: center;">
                <el-row>
                  <el-button type="primary" class="btn-search" @click="search()">查询</el-button>
                  <el-button type="warning" class="btn-search" @click="clearQuery()">清除输入</el-button>
                </el-row>
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="tableData" stripe border v-loading="tableLoading" class="table-class"
                    :max-height="maxHeight" highlight-current-row @row-click="getCurrentRow"
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                    @sort-change="handleSortChange">
            <el-table-column width="65px" fixed="left">
              <template v-slot="scope">
                <el-radio :label="scope.row.jobName" v-model="jobName">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="jobName" label="任务名" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="jobClass" label="任务类" min-width="200px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="timerType" label="定时器类型" min-width="120px" :formatter="timerTypeFormat"
                             sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="jobStatus" label="任务状态" :formatter="jobStatusFormat"
                             min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column label="定时规则" min-width="150px" sortable="custom"
                             show-overflow-tooltip>
              <template v-slot="scope">
                {{ getTimerRule(scope.row) }}
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <el-pagination v-model:current-page="baseTableQuery.currentPage"
                         v-model:page-size="baseTableQuery.pageSize" :page-sizes="[10, 25, 50]" :small="false"
                         :disabled="false" :background="false" :default-page-size="10" @size-change="search"
                         @current-change="search" layout="total, sizes, prev, pager, next, jumper"
                         :total="baseTableQuery.total"/>
        </div>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import store from '@/store'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {timeFormatter} from '@/utils/formatter.js'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from 'vue'
import {ElMessage} from 'element-plus'
import {genTableRequest, addAllOptionOfOptions} from '@/utils/generator.js'
import {labelPosition} from '@/constant/form.js'
import {getJobsByPage} from "@/api/job";
import {timerTypeOptions, jobStatusOptions} from "@/constant/options";

/**
 * 常量定义
 */
const STAND_ID = store.getters.getStandId
const USER_NAME = store.getters.getUserName
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let tableData = ref([])
let baseTableQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  sortBy: new Map([['jobName', true]]),// 按照任务名顺序排序
  standId: STAND_ID,
  userName: USER_NAME
})
let searchQueryFormEntity = reactive({
  jobName: '',
  jobClass: '',
  cronExpression: '',
  timer: null,
  timerType: -99,
  jobStatus: -99
})
let searchQueryFormRef = ref()
let jobName = ''
/**
 * 系统方法
 */
onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', resizeHeight)
    search()
  })
})
onBeforeUnmount(() => {
  nextTick(() => {
    window.removeEventListener('resize', resizeHeight)
  })
})
const resizeHeight = () => {
  maxHeight.value = window.innerHeight * 0.55
}
/**
 * 自定义方法
 */
// 查询
const search = () => {
  tableLoading.value = true
  let request = genTableRequest(baseTableQuery)
  // 设定查询参数
  request.jobName = searchQueryFormEntity.jobName.trim() || null
  request.jobClass = searchQueryFormEntity.jobClass.trim() || null
  request.cronExpression = searchQueryFormEntity.cronExpression.trim() || null
  request.timer = searchQueryFormEntity.timer
  request.timerType = searchQueryFormEntity.timerType === -99 ? null : searchQueryFormEntity.timerType
  request.jobStatus = searchQueryFormEntity.jobStatus === -99 ? null : searchQueryFormEntity.jobStatus
  getJobsByPage(request).then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        tableData.value = data.lists
        baseTableQuery.total = data.total
      } else {
        tableData.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询数据异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}
const clearQuery = () => {
  searchQueryFormEntity.jobName = ''
  searchQueryFormEntity.jobClass = ''
  searchQueryFormEntity.cronExpression = ''
  searchQueryFormEntity.timer = null
  searchQueryFormEntity.timerType = -99
  searchQueryFormEntity.jobStatus = -99
}
const handleSortChange = (data) => {
  if (baseTableQuery.sortBy.has(data.prop)) {
    baseTableQuery.sortBy.delete(data.prop)
  }
  baseTableQuery.sortBy.set(data.prop, data.order.toLowerCase() === 'ascending')
  search()
}
const getCurrentRow = (row) => {
  jobName = row.jobName
}
const timeFormat = (row, column, cellValue, index) => {
  return timeFormatter(cellValue)
}
const timerTypeFormat = (row, column, cellValue, index) => {
  const option = timerTypeOptions.find(item => item.value === cellValue)
  return option ? option.label : cellValue
}
const jobStatusFormat = (row, column, cellValue, index) => {
  return cellValue === 1 ? '生效' : '不生效'
}
const getTimerRule = (row) => {
  if (row.timerType === 2) {
    // Cron表达式
    return row.cronExpression || '-'
  } else if (row.timerType === 1) {
    // 普通定时器，显示毫秒数
    return row.timer ? `${row.timer}ms` : '-'
  }
  return '-'
}
</script>
<style scoped>
.content {
  display: flex;
  width: 100%;
}

.work-area {
  width: 100%;
  /* padding: 5px; */
}

.search-area {
  margin: auto;
  min-height: fit-content;
  max-height: 40%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.table-area {
  margin: auto;
  min-height: fit-content;
  max-height: 60%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.el-form-item {
  margin: 5px 5px 5px 5px;
}

.el-form-item .el-input {
  width: 196px;
}

.el-form-item .el-input-number {
  width: 196px;
}

.el-form-item .el-select-v2 {
  width: 196px;
}

.table-class {
  margin: 5px 5px 5px 5px;
  width: inherit;
}

.el-pagination {
  padding-left: 5px;
}

.btn-search {
  height: 30px;
  width: 80px;
  margin: auto 5px 5px auto;
  color: black;
}
</style>