<template>
  <div class="layout-no-cols">
      <el-toolbar>
        <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
        <span class="button-separator"></span>
        <el-button type="button" class="el-button el-button--default save" :loading="confirmLoading" @click="confirmScheduleClickHandler"><span><i class="fa fa-save"></i>保存</span></el-button>
      </el-toolbar>
      <div>
      <div class="detail-panel block-line-panel">
        <div class="panel-header">
          <span class="title">{{!!tmpSchedule.ID ? '修改任务':'添加任务'}}</span>
        </div>
      <el-form :model="tmpSchedule" :rules="scheduleRules" ref="scheduleForm" label-width="160px" label-suffix="：">
        <el-form-item class="select-required" label="任务类别" prop="typeCode" :verify="['NotNull']">
          <el-select v-model="tmpSchedule.typeCode" placeholder="请选择" @change="typeChangeHandler" :disabled="!!tmpSchedule.ID" class="schedule-select">
            <el-option v-for="item in scheduleTypes" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="select-required" label="选择任务" prop="sourceID" :verify="['NotNull']">
          <el-select v-model="tmpSchedule.sourceID" placeholder="请选择" :disabled="!!tmpSchedule.ID" class="schedule-select">
            <el-option v-for="item in optionalSchedule" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起始时间" prop="startTime" :disabled="tmpSchedule.typeCode==='SYSTEM'"  :verify="['NotNull']">
          <el-date-picker v-model="tmpSchedule.startTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择起始时间" :disabled="tmpSchedule.typeCode==='SYSTEM'">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="执行周期">
          <el-radio class="radio" v-model="tmpSchedule.planType" label="Period" :disabled="tmpSchedule.typeCode==='SYSTEM'">
          <span>每隔</span>
          <el-input-number v-model="tmpSchedule.period" :min="1" :disabled="tmpSchedule.typeCode==='SYSTEM'"></el-input-number>
          <el-select v-model="tmpSchedule.periodType" :disabled="tmpSchedule.typeCode==='SYSTEM'" placeholder="请选择">
            <el-option label="分钟" value="Minute"></el-option>
            <el-option label="小时" value="Hour"></el-option>
            <el-option label="日" value="Day"></el-option>
            <el-option label="月" value="Month"></el-option>
          </el-select></el-radio><br/>
          <el-radio class="radio" v-model="tmpSchedule.planType" :label="null" :disabled="tmpSchedule.typeCode==='SYSTEM'">使用Cron表达式</el-radio>
        </el-form-item>
        <el-form-item v-show="tmpSchedule.planType === null || tmpSchedule.typeCode==='SYSTEM'" prop="cronExpression">
          <el-input v-model="tmpSchedule.cronExpression" placeholder="请输入Cron表达式"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="tmpSchedule.isUsing" active-value="Y" inactive-value="N"></el-switch>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="tmpSchedule.description" placeholder="请输入备注" :disabled="tmpSchedule.typeCode==='SYSTEM'"></el-input>
        </el-form-item>
      </el-form>
      </div>
      </div>
  </div>
</template>

<style scoped>

</style>

<script>
import util from '@src/common/util.js'

export default {
  props: {
    ID: [String, Number]
  },
  data() {
    return {
      tmpSchedule: {
        ID: 0,
        typeCode: '',
        typeCodeName: '',
        sourceID: '',
        sourceIDName: '',
        startTime: '',
        nextRunTime: '',
        planType: 'Period',
        period: 1,
        periodType: 'Minute',
        cronExpression: '',
        isUsing: 'Y',
        description: ''
      },
      scheduleRules: {
        cronExpression: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (String(this.tmpSchedule.planType) === '2' && value === '') {
                callback(new Error('请输入Cron表达式!'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      confirmLoading: false,
      scheduleTypes: [],
      optionalSchedule: []
    }
  },
  methods: {
    goBack() {
      this.$router.push({path: '/platform/schedule'})
    },
    async loadScheduleTypes() {
      let res = null
      if (!this.tmpSchedule.ID) {
        res = await axios.get('/ui/schedules/types', {params: {usable: 'Y'}}).catch(e => console.log(e))
      } else {
        res = await axios.get('/ui/schedules/types').catch(e => console.log(e))
      }
      let data = res.data
      this.scheduleTypes = data.status === 1 ? data.data : this.scheduleTypes
      this.typeChangeHandler(this.tmpSchedule.typeCode)
    },

    async typeChangeHandler(typeID) {
      let optionalSchedule = []
      if (typeID === 'SYSTEM') {
        optionalSchedule.push({ID: this.tmpSchedule.ID, name: this.tmpSchedule.sourceIDName})
      }
      for (let item of this.scheduleTypes) {
        item.ID === typeID && optionalSchedule.splice(-1, 0, ...item.options)
      }
      this.optionalSchedule = [...optionalSchedule]
      this.tmpSchedule.sourceID = this.optionalSchedule.length ? this.optionalSchedule[0].ID : null
    },

    async confirmScheduleClickHandler() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['scheduleForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        this.confirmLoading = false
        return
      }

      let res = null
      try {
        if (!this.tmpSchedule.ID) {
          res = await axios.post('/ui/schedules', this.tmpSchedule)
        } else {
          res = await axios.put(`/ui/schedules/${this.tmpSchedule.ID}`, this.tmpSchedule)
        }
      } catch (e) {
        this.confirmLoading = false
        return
      }
      this.confirmLoading = false
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.goBack()
      }
    },

    computePeriod() {
      var expr = this.tmpSchedule.cronExpression
      var arr = expr.split(' ')
      if (arr[1].indexOf('/') > 0) {
        this.tmpSchedule.periodType = 'Minute'
        this.tmpSchedule.period = arr[1].substring(arr[1].indexOf('/') + 1)
      }
      if (arr[2].indexOf('/') > 0) {
        this.tmpSchedule.periodType = 'Hour'
        this.tmpSchedule.period = arr[2].substring(arr[2].indexOf('/') + 1)
      }
      if (arr[3].indexOf('/') > 0) {
        this.tmpSchedule.periodType = 'Day'
        this.tmpSchedule.period = arr[3].substring(arr[3].indexOf('/') + 1)
      }
      if (arr[4].indexOf('/') > 0) {
        this.tmpSchedule.periodType = 'Month'
        this.tmpSchedule.period = arr[4].substring(arr[4].indexOf('/') + 1)
      }
      if (arr[5].indexOf('/') > 0) {
        this.tmpSchedule.periodType = 'Year'
        this.tmpSchedule.period = arr[5].substring(arr[5].indexOf('/') + 1)
      }
    },

    async init() {
      if (this.ID && this.ID !== 'new') {
        let res = await axios.get(`/ui/schedules/${this.ID}`)
        if (res.data.status !== 1) {
          util.showResponseMessage(res.data)
          return
        }
        this.tmpSchedule = res.data.data
        if (this.tmpSchedule.typeCode === 'SYSTEM') {
          this.tmpSchedule.startTime = '1970-01-01 00:00:00'
        }
        Vue.set(this.tmpSchedule, 'period', this.tmpSchedule.period || 1)
        Vue.set(this.tmpSchedule, 'periodType', this.tmpSchedule.periodType || 'Minute')
        if (this.tmpSchedule.planType === 'Period') {
          this.computePeriod()
        }
        this.typeChangeHandler(this.tmpSchedule.typeCode)
      }
    }
  },
  async created() {
    this.loadScheduleTypes()
    await this.init()
  }
}
</script>

<style scoped>
.schedule-select {
  width: auto;
}
.el-radio-group label,
.el-form-item__content label,
.el-checkbox-group label {
  padding: 0 5px 0 0;
}
</style>
