<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button icon="el-icon-plus" type="primary" @click="handleAdd">
          添加
        </el-button>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="tableData"
      :element-loading-text="elementLoadingText"
      :height="height"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      @expand-change="expandChange"
    >
      >

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">

            <el-form-item label="下次执行时间:">
              <span>{{ props.row.nextFireTime }}</span>
            </el-form-item>
            <el-form-item label="最后执行时间:">
              <span>{{ props.row.laetFireTime }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="序号" width="95">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="name" label="任务名称" />
      <el-table-column show-overflow-tooltip prop="jobName" label="任务标识" />
      <el-table-column show-overflow-tooltip prop="jobState" label="任务状态" />
      <el-table-column
        :formatter="formatQuartz"
        show-overflow-tooltip
        prop="executeClass"
        label="执行类"
      />
      <el-table-column
        show-overflow-tooltip
        prop="cronExpression"
        label="cronb表达式"
      />
      <el-table-column show-overflow-tooltip label="操作" width="180px">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">
            <el-tag type="success">编辑</el-tag>
          </el-button>
          <el-button type="text" @click="handleDelete(row)">
            <el-tag type="danger">删除</el-tag>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="page.currentPage"
      :layout="layout"
      :page-size="page.pageSize"
      :total="page.total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="执行类" prop="executeClass">
          <el-select
            v-model="form.executeClass"
            :disabled="isEdit"
            style="width: 100%"
            placeholder="请选择"
            @change="selectExecuteClassChange($event)"
          >
            <el-option
              v-for="item in this.quartzBaseAll"
              :key="item.executeClass"
              :label="item.name"
              :value="item.executeClass"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ item.type }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="cron" prop="cronExpression">
          <el-popover v-model="cronPopover">
            <cron
              i18n="cn"
              @change="changeCron"
              @close="cronPopover = false"
            ></cron>
            <el-input
              slot="reference"
              v-model="form.cronExpression"
              style="margin-top: -50%"
              placeholder="请输入定时策略"
              @click="cronPopover = true"
            ></el-input>
          </el-popover>
        </el-form-item>

        <el-form-item label="任务标识" prop="jobName">
          <el-input
            v-model.trim="form.jobName"
            autocomplete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>

        <el-form-item label="任务名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="任务操作" prop="operate">
          <el-select v-model="form.operate" placeholder="请选择">
            <el-option
              v-for="item in operates"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model.trim="form.startTime"
            value-format="timestamp"
            type="datetime"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    addObj,
    putObj,
    delObj,
    getJobName,
    getJobTime,
  } from '@/api/quartz'
  import {getQuartzBaseAll} from '@/api/quartzBase'

  import { cron } from 'vue-cron'
  export default {
    name: 'QuartzInfo',
    components: { cron },
    data() {
      const validateJobName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入任务标识'))
        }
        getJobName(this.form.jobName, value).then((response) => {
          if (this.dialogType === 'edit') callback()
          let result = response.data
          if (result !== null) {
            callback(new Error('任务标识存在'))
          } else {
            callback()
          }
        })
      }
      return {
        isEdit: false,
        cronPopover: false,
        cron: '',
        quartzBaseAll: [],
        dialogFormVisible: false,
        dialogType: '',
        title: '',
        tableData: [],
        operates: [
          { label: '启动', value: 'start' },
          { label: '停止', value: 'stop' },
          { label: '重载', value: 'restart' },
        ],

        form: {
          executeClass: null,
          jobName: null,
          cronExpression: null,
        },
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        elementLoadingText: '正在加载...',
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条
        },
        rules: {
          name: [{ required: true, trigger: 'blur', message: '请输入名称' }],

          executeClass: [
            { required: true, trigger: 'blur', message: '请输入执行类' },
          ],

          jobName: [
            { required: true, trigger: 'change', validator: validateJobName },
          ],

          cronExpression: [
            { required: true, trigger: 'blur', message: '请输入时间表达式' },
          ],

          startTime: [
            { required: true, trigger: 'blur', message: '请输入开始时间' },
          ],
        },
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.getQuartzBaseAll()
    },
    methods: {
      expandChange(row, expandedRows) {
        getJobTime(row.jobName).then((response) => {
          row.nextFireTime = response.data.nextFireTime
          row.laetFireTime = response.data.previousFireTime
        })
      },
      changeCron(v) {
        this.form.cronExpression = v
      },
      getQuartzBaseAll(){
        getQuartzBaseAll()
          .then((response) => {
            this.quartzBaseAll = response.data
            this.fetchData()
            this.listLoading = false
          })
          .catch(() => {
            this.listLoading = false
          })
      },


      selectExecuteClassChange(value) {
        const selectedItem = this.quartzBaseAll.find((item) => {
          return item.executeClass === value
        })
        this.form.jobName =  selectedItem.code
      },
      async fetchData() {
        this.listLoading = true
        fetchList(
          Object.assign(
            {
              current: this.page.currentPage,
              size: this.page.pageSize,
            },
          )
        )
          .then((response) => {
            this.tableData = response.data.records
            this.page.total = response.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.listLoading = false
          })
      },

      handleSizeChange(val) {
        this.page.pageSize = val
        this.page.currentPage = 1
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.page.currentPage = val
        this.fetchData()
      },

      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.$emit('fetch-data')
      },
      handleAdd() {
        this.isEdit = false
        this.form = {}
        this.title = '新增'
        this.dialogType = 'add'
        this.dialogFormVisible = true
      },
      handleEdit(row) {
        this.isEdit = true
        var newObj = JSON.parse(JSON.stringify(row))
        this.form = newObj
        this.form.operate = 'restart'
        this.title = '修改'
        this.dialogType = 'edit'
        this.dialogFormVisible = true
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          await delObj(row.id)
          this.$baseMessage('删除成功', 'success')
          this.fetchData()
        })
      },
      saveOrUpdate() {
        this.form.nextFireTime = null
        this.form.laetFireTime = null
        if (this.dialogType == 'add') {
          this.save()
        } else {
          this.update()
        }
      },
      save() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.listLoading = true
            addObj(this.form)
              .then((response) => {
                this.dialogFormVisible = false
                this.fetchData()
                this.listLoading = false
              })
              .catch(() => {
                this.listLoading = false
              })
          } else {
            return false
          }
        })
      },
      update() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.listLoading = true
            putObj(this.form)
              .then((response) => {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                })
                this.dialogFormVisible = false
                this.fetchData()
                this.listLoading = false
              })
              .catch(() => {
                this.$message({
                  message: '修改失败',
                  type: 'warning',
                })
                this.listLoading = false
              })
          } else {
            return false
          }
        })
      },

      formatQuartz(row, column){
        const selectedItem = this.quartzBaseAll.find((item) => {
          return item.executeClass === row.executeClass
        })
        return selectedItem.name
      }


    },
  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
