<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.job_name"
          clearable
          size="mini"
          :placeholder="$t('Timing.msg.select_msg')"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <!-- 任务日志 -->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          icon="el-icon-tickets"
          @click="doLog"
        >{{ $t('Timing.DB.log') }}
        </el-button>
      </crudOperation>
      <Log ref="log" />
    </div>
    <!--Form表单-->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      append-to-body
      width="730px"
    >
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="mini" label-width="100px">
        <el-form-item label="任务名称" prop="job_name">
          <el-input v-model="form.job_name" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="Bean名称" prop="bean_name">
          <el-input v-model="form.bean_name" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="执行方法" prop="method_name">
          <el-input v-model="form.method_name" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cron_expression">
          <!--          <el-input v-model="form.cron_expression" style="width: 220px;" />-->
          <el-input v-model="form.cron_expression" placeholder="请输入CRON 表达式" style="width: 220px;">
            <template slot="append">
              <el-button type="primary" @click="handleShowCron">
                生成表达式
                <i class="el-icon-time el-icon--right" />
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="子任务ID">
          <el-input v-model="form.sub_task" placeholder="多个用逗号隔开，按顺序执行" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="任务负责人" prop="person_in_charge">
          <el-input v-model="form.person_in_charge" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="告警邮箱" prop="email">
          <el-input v-model="form.email" placeholder="多个邮箱用逗号隔开" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="失败后暂停">
          <el-radio-group v-model="form.pause_after_failure" style="width: 220px">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-radio-group v-model="form.is_pause" style="width: 220px">
            <el-radio :label="false">启用</el-radio>
            <el-radio :label="true">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="参数内容">
          <el-input v-model="form.params" style="width: 556px;" rows="4" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column show-overflow-tooltip prop="job_id" :label="$t('Timing.DB.job_id')" />
      <el-table-column show-overflow-tooltip prop="job_name" :label="$t('Timing.DB.job_name')" />
      <el-table-column show-overflow-tooltip prop="bean_name" :label="$t('Timing.DB.bean_name')" />
      <el-table-column show-overflow-tooltip prop="method_name" :label="$t('Timing.DB.method_name')" />
      <el-table-column show-overflow-tooltip prop="params" :label="$t('Timing.DB.params')" />
      <el-table-column
        show-overflow-tooltip
        prop="cron_expression"
        :label="$t('Timing.DB.cron_expression')"
        min-width="100"
        show-tooltip-when-overflow
      />
      <el-table-column show-overflow-tooltip prop="is_pause" width="90px" :label="$t('Timing.DB.is_pause')">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_pause ? 'warning' : 'success'">{{
            scope.row.is_pause ? '已暂停' : '运行中'
          }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="description" width="150px" :label="$t('Timing.DB.description')" />
      <el-table-column show-overflow-tooltip prop="create_time" width="136px" :label="$t('Timing.DB.create_time')">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-permission="['admin','timing:edit','timing:del']"
        :label="$t('common.Operate')"
        width="170px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['admin','timing:edit']"
            size="mini"
            style="margin-right: 3px;"
            type="text"
            @click="crud.toEdit(scope.row)"
          >{{ $t('Timing.DB.edit') }}
          </el-button>
          <el-button
            v-permission="['admin','timing:edit']"
            style="margin-left: -2px"
            type="text"
            size="mini"
            @click="execute(scope.row.job_id)"
          >{{ $t('Timing.DB.execute') }}
          </el-button>
          <el-button
            v-permission="['admin','timing:edit']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="updateStatus(scope.row.job_id,scope.row.is_pause ? $t('Timing.DB.restore')   $t('Timing.DB.suspend'))"
          >
            {{ scope.row.is_pause ? $t('Timing.DB.restore') : $t('Timing.DB.suspend') }}
          </el-button>
          <el-popover
            :ref="scope.row.job_id"
            v-permission="['admin','timing:del']"
            placement="top"
            width="200"
          >
            {{ $t('Timing.msg.delete_msg') }}
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[scope.row.job_id].doClose()">{{ $t('common.Cancel') }}</el-button>
              <el-button :loading="delLoading" type="primary" size="mini" @click="delMethod(scope.row.job_id)">{{ $t('common.determine') }}
              </el-button>
            </div>
            <el-button slot="reference" type="text" size="mini">{{ $t('common.Cancel') }}</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body class="scrollbar" destroy-on-close>
      <crontab :expression="expression" @hide="openCron=false" @fill="crontabFill" />
    </el-dialog>
  </div>
</template>

<script>
import crudJob from '@/views/system/timing/timing'
import Log from './log'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import Crontab from './components/crontab'

const defaultForm = {
  job_id: null,
  bean_name: null,
  cron_expression: null,
  is_pause: false,
  job_name: null,
  method_name: null,
  params: null,
  description: null,
  person_in_charge: null,
  email: null,
  sub_task: null,
  pause_after_failure: true
}
export default {
  name: 'Timing',
  components: { Log, pagination, crudOperation, rrOperation, Crontab },
  cruds() {
    return CRUD({ title: '定时任务', idField: 'job_id', url: 'api/jobs', crudMethod: { ...crudJob }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      delLoading: false,
      permission: {
        add: ['admin', 'timing:add'],
        edit: ['admin', 'timing:edit'],
        del: ['admin', 'timing:del']
      },
      rules: {
        job_name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入任务描述', trigger: 'blur' }
        ],
        bean_name: [
          { required: true, message: '请输入Bean名称', trigger: 'blur' }
        ],
        method_name: [
          { required: true, message: '请输入方法名称', trigger: 'blur' }
        ],
        cron_expression: [
          { required: true, message: '请输入Cron表达式', trigger: 'blur' }
        ],
        person_in_charge: [
          { required: true, message: '请输入负责人名称', trigger: 'blur' }
        ]
      },
      // 是否显示Cron表达式弹出层
      openCron: false,
      // 传入的表达式
      expression: ''
    }
  },
  methods: {
    // 执行
    execute(id) {
      crudJob.execution(id).then(res => {
        this.crud.notify('执行成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 改变状态
    updateStatus(id, status) {
      if (status === '恢复') {
        this.updateParams(id)
      }
      crudJob.updateIsPause(id).then(res => {
        this.crud.toQuery()
        this.crud.notify(status + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    updateParams(id) {
      console.log(id)
    },
    delMethod(id) {
      this.delLoading = true
      crudJob.del([id]).then(() => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.crud.dleChangePage(1)
        this.crud.delSuccessNotify()
        this.crud.toQuery()
      }).catch(() => {
        this.delLoading = false
        this.$refs[id].doClose()
      })
    },
    // 显示日志
    doLog() {
      this.$refs.log.dialog = true
      this.$refs.log.doInit()
    },
    checkboxT(row, rowIndex) {
      return row.job_id !== 1
    },
    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.cron_expression
      this.openCron = true
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cron_expression = value
    }
  }
}
</script>
