<template>
  <div class="page-view">
    <app-filter ref="app-filter" :model="filters" class="bg-white px-15 border-radius-5" label-width="90px"
                @query="onQuery" @reset="onReset">
      <app-filter-item :span="5" label="任务名称">
        <el-input v-model="filters.jobName" clearable placeholder="请输入"
                  @keyup.enter.native="$refs['app-filter'].query" />
      </app-filter-item>
    </app-filter>

    <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
      <div class="mb-11 bg-white">
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="addTable"> 新增</el-button>
      </div>
      <app-table
        ref="table"
        :column="columns"
        :pagination="pagination"
        :table-data="tableData"
        :table-loading="tableLoading"
        :total="total"
        row-key="id"
        @pagination-change="onPaginationChange"
        @row-dblclick="editTable"
      >
        <template #jobStatus="scope">
          <template v-if="scope.row['jobType'] === 1">
            <el-tag v-if="scope.row['jobStatus'] === 'NONE'" type="danger">停止</el-tag>
            <el-tag v-if="scope.row['jobStatus'] === 'NORMAL'" type="success">运行</el-tag>
            <el-tag v-if="scope.row['jobStatus'] === 'PAUSED'" type="warning">暂停</el-tag>
          </template>
          <template v-else>
            <span>-</span>
          </template>
        </template>
        <template #jobType="scope">
          <el-tag>{{ scope.row['jobType'] === 1 ? '定时任务' : '非定时任务' }}</el-tag>
        </template>
      </app-table>
    </div>
    <shell-dialog v-model="dialogVisible" :data="dialogdData" :mode="3" :title="dialogTitle" @confirm="onConfirm" />
    <logDialog v-model="logVisible" :data="logData" :title="logTitle"></logDialog>
  </div>
</template>
<script>
import tableMixin from '@/mixins/table.js' // 列表mixins
import API from '@/api/business/schedulerTasks.js'
import shellDialog from './components/shellDialog.vue'
import logDialog from './components/logDialog.vue'

export default {
  name: 'shellTask',
  components: {shellDialog, logDialog},
  mixins: [tableMixin],
  data() {
    const TABLE_CONFIG = {
      // 列表表头
      columns: [
        {label: '任务名称', prop: 'jobName', minWidth: '150'},
        {label: '数据资源表', prop: 'dataResourcesName', minWidth: '150'},
        {label: '作业类别', prop: 'jobType', width: '150', dataType: 'slot', slot: 'jobType', align: 'center'},
        {label: '运行状态', prop: 'jobStatus', width: '200', dataType: 'slot', slot: 'jobStatus', align: 'center'},
        {
          dataType: 'option',
          label: '操作',
          width: '260px',
          fixed: 'right',
          operation: [
            {
              name: '任务日志',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-s-order',
              color: '#409eff',
              plain: true,
              clickFun: (row) => {
                this.log(row)
              }
            },
            {
              name: '停止',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-s-order',
              color: 'red',
              plain: true,
              showHide: (row) => {
                return row.jobStatus === 'NORMAL' && row.jobType === 1
              },
              clickFun: (row) => {
                this.stop(row)
              }
            },
            {
              name: '启动任务',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-s-order',
              color: '#67c23a',
              plain: true,
              showHide: (row) => {
                return (row.jobStatus !== 'NORMAL' && row.jobType === 1) || row.jobType === 2
              },
              clickFun: (row) => {
                this.run(row)
              }
            },

            {
              name: '立即执行',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-thumb',
              color: '#67c23a',
              plain: true,
              showHide: (row) => {
                return row.jobStatus !== 'NORMAL' && row.jobType === 1
              },
              clickFun: (row) => {
                this.runOnce(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-delete',
              color: 'red',
              plain: true,
              showHide: (row) => {
                return (row.jobStatus !== 'NORMAL' && row.jobType === 1) || row.jobType === 2
              },
              clickFun: (row) => {
                this.delete(row)
              }
            }
          ]
        }
      ]
    }

    const DIALOG_CONFIG = {
      logVisible: false,
      logData: {},
      logTitle: '',
      dialogVisible: false,
      dialogTitle: '新增',
      dialogdData: {},
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 'jobTaskMode',
          relation: 'AND',
          value: 3
        },
        {
          operation: 'EQUAL',
          property: 'jobTaskType',
          relation: 'AND',
          value: 4
        }
      ]
    }

    return {
      ...TABLE_CONFIG,
      ...DIALOG_CONFIG
    }
  },
  computed: {
    // 配置列表接口方法：只有配置了该计算属性 才会执行 table mixins中的getData方法
    dataMethod() {
      return API.querySchedulerJob
    }
  },
  methods: {
    addTable() {
      this.dialogTitle = '新增shell采集任务'
      this.dialogdData = null
      this.dialogVisible = true
    },
    editTable(row) {
      this.dialogTitle = `编辑 - ${row.jobName}`
      this.dialogdData = row
      this.dialogVisible = true
    },
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'jobTaskMode', 3)
      this.setFilterValue(this.queryParams, this.defaultFilter, 'jobTaskType', 4)
    },
    onConfirm() {
      this.getData()
    },
    log(row) {
      this.logTitle = `任务日志：${row.jobName}`
      this.logData = row
      this.logVisible = true
    },
    async runOnce(row) {
      this.$confirm(`此操作将立即执行任务（${row.jobName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const param = new FormData()
          param.append('id', row.id)
          try {
            const {state} = await API.executeOnce(param)
            if (state) {
              this.getData()
              this.$message.success('任务执行成功！')
            }
          } catch (err) {
            this.$message.warning(err || '任务执行失败！')
          }
        })
        .catch(() => {
        })
    },
    async run(row) {
      this.$confirm(`此操作将启动任务（${row.jobName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const param = new FormData()
          param.append('id', row.id)
          try {
            const {state} = await API.executeStart(param)
            if (state) {
              this.getData()
              this.$message.success('任务启动成功！')
            }
          } catch (err) {
            this.$message.warning(err || '任务启动失败！')
          }
        })
        .catch(() => {
        })
    },
    async stop(row) {
      this.$confirm(`此操作将停止任务（${row.jobName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const param = new FormData()
          param.append('id', row.id)
          try {
            const {state} = await API.executeStop(param)
            if (state) {
              this.getData()
              this.$message.success('任务停止成功！')
            }
          } catch (err) {
            this.$message.warning(err || '任务停止失败！')
          }
        })
        .catch(() => {
        })
    },
    delete(row) {
      this.$confirm(`此操作将删除任务（${row.jobName}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const {state, message} = await API.deleteSchedulerJob(row.id)
            if (state) {
              this.getData()
              this.$message.success('删除任务成功！')
            }
          } catch (err) {
            this.$message.warning(err || '删除任务失败！')
          }
        })
        .catch(() => {
        })
    }
  }
}
</script>
<style lang="scss" scoped></style>
