<template>
  <div>
    <el-container style="margin-left: 10px;">
      <el-header style="padding: 0px;display:flex;justify-content:space-between;align-items: center">
        <div style="display: inline">
          <el-input
            v-if="false"
            v-model="keywords"
            placeholder="通过任务名搜索任务,记得回车哦..."
            clearable
            style="width: 300px;margin: 0px;padding: 0px;"
            size="mini"
            prefix-icon="el-icon-search"
            @change="keywordsChange"
            @keyup.enter.native="searchEmp"
          />
          <el-select v-model="jType" placeholder="请选择任务类型" style="width: 300px;margin: 0px;padding: 0px;">
            <el-option label="" value=""/>
            <el-option
              v-for="item in jobtype"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="searchEmp">搜索
          </el-button>
          <el-button
            type="primary"
            style="margin-left: 5px;display: inline"
            size="mini"
            icon="el-icon-plus"
            @click="showAddEmpView"
          >
            添加定时任务
          </el-button>
          <el-button
            slot="reference"
            type="primary"
            size="mini"
            style="margin-left: 5px"
            icon="el-icon-download"
            @click="dataDownload"
          >导出数据
          </el-button>
          <el-button
            :disabled="multipleSelection.length==0"
            style="margin-left: 5px;margin-right: 20px;display: inline"
            type="danger"
            size="mini"
            @click="deleteManyEmps"
          >批量删除
          </el-button>

          <el-button
            type="primary"
            size="mini"
            style="margin-left: 5px;display: inline"
            icon="el-icon-refresh-right"
            :loading="btnLonding"
            @click="initJob"
          >
            初始化定时任务信息
          </el-button>

        </div>
      </el-header>
      <el-main style="padding-left: 0px;padding-top: 0px">
        <div>
          <el-table
            v-loading="tableLoading"
            :data="emps"
            height="450px"
            border
            stripe
            size="mini"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              header-align="center"
            />
            <el-table-column
              :show-overflow-tooltip="true"
              :formatter="jobNameFormat"
              prop="executeClass"
              header-align="center"
              label="任务名称"
            />
            <el-table-column
              :show-overflow-tooltip="true"
              header-align="center"
              width="180"
              prop="cronExpression"
              label="cron时间表达式或轮询时间"
            />
            <el-table-column
              :formatter="jobTypeFormat"
              header-align="center"
              prop="jobType"
              label="任务类型"
            />
            <el-table-column
              :formatter="dateFormat"
              prop="startTime"
              header-align="center"
              width="180"
              label="任务开始时间"
            />
            <el-table-column
              :formatter="dateFormat"
              prop="laetFireTime"
              header-align="center"
              width="180"
              label="最后执行时间"
            />
            <el-table-column
              :show-overflow-tooltip="true"
              width="280"
              header-align="center"
              prop="description"
              label="任务描述"
            />
            <el-table-column
              sortable
              width="120"
              prop="jobState"
              header-align="center"
              label="任务状态"
            />
            <el-table-column
              fixed="right"
              header-align="center"
              width="240"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  v-show="scope.row.jobState === '暂停'"
                  type="success"
                  style="padding: 3px 4px 3px 4px;margin: 2px"
                  size="mini"
                  icon="el-icon-success"
                  @click="jobstate(scope.row)"
                >启用
                </el-button>
                <el-button
                  v-show="scope.row.jobState !== '暂停'"
                  type="warning"
                  style="padding: 3px 4px 3px 4px;margin: 2px"
                  size="mini"
                  icon="el-icon-error"
                  @click="jobstate(scope.row)"
                >停用
                </el-button>
                <el-button
                  style="padding: 3px 4px 3px 4px;margin: 2px"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditEmpView(scope.row)"
                >编辑
                </el-button>
                <el-button
                  type="danger"
                  style="padding: 3px 4px 3px 4px;margin: 2px"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteEmp(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: space-between;margin: 2px;float: right">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="totalCount"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="currentChange"
            />
          </div>
        </div>
      </el-main>
    </el-container>
    <el-form ref="addEmpForm" :model="emp" :rules="rules" style="margin: 0px;padding: 0px;" label-width="150px">
      <div style="text-align: left">
        <el-dialog
          :title="dialogTitle"
          :close-on-click-modal="false"
          :visible.sync="dialogVisible"
          style="padding: 0px;"
          width="600px"
          @close="cancelEidt"
        >
          <!-- <el-form-item label="任务Code" prop="jobName" >
            <el-input v-model="emp.jobName" :disabled="emp.id != ''" placeholder="请输入用户名" />
          </el-form-item> -->
          <el-form-item label="任务类型" prop="jobType">
            <el-select v-model="emp.jobType" placeholder="请选择任务类型" style="width: 100%" @change="getClass">
              <el-option
                v-for="item in jobtype"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="执行类" prop="executeClass">
            <el-select v-model="emp.executeClass" placeholder="请选择执行类" style="width: 100%">
              <el-option
                v-for="item in this.jobclass"
                :key="item.jobClassPath"
                :label="item.jobClassName"
                :value="item.jobClassPath"
              >
                <span style="float: left">{{ item.jobClassName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobClassPath }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="emp.startTime"
              style="width: 100%"
              value-format="timestamp"
              type="datetime"
              placeholder="选择日期时间"
              default-time="12:00:00"
            />
          </el-form-item>
          <el-form-item label="任务描述" prop="description">
            <el-input v-model="emp.description" style="width: 100%" placeholder="请输入任务描述"/>
          </el-form-item>
          <el-form-item label="表达式/时间（秒）" prop="cronExpression">
            <el-input v-model="emp.cronExpression" style="width: 100%" placeholder="请输入任务表达式或者轮询时间"/>
          </el-form-item>
          <el-form-item label="任务状态" prop="jobState">
            <el-select v-model="emp.jobState" placeholder="请选择状态" style="width: 100%">
              <el-option
                v-for="item in status"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="cancelEidt">取 消</el-button>
            <el-button size="mini" type="primary" @click="addEmp('addEmpForm')">保 存</el-button>
          </span>
        </el-dialog>
      </div>
    </el-form>
  </div>
</template>
<script>
    export default {
        data() {
            return {
                emps: [],
                keywords: '',
                jType: '',
                dialogTitle: '',
                multipleSelection: [],
                depTextColor: '#c0c4cc',
                totalCount: -1,
                currentPage: 1,
                pageSize: 10,
                dialogVisible: false,
                tableLoading: false,
                emp: {
                    id: '',
                    jobName: '',
                    jobState: '',
                    executeClass: '',
                    description: '',
                    cronExpression: '',
                    jobType: '',
                    startTime: ''
                },
                rules: {
                    jobName: [{required: true, message: '必填:任务名', trigger: 'blur'}],
                    jobState: [{required: true, message: '必填:任务状态', trigger: 'blur'}],
                    executeClass: [{required: true, message: '必填:执行类', trigger: 'blur'}],
                    description: [{required: true, message: '必填:描述', trigger: 'blur'}],
                    cronExpression: [{required: true, message: '必填:表达式/轮询时间', trigger: 'blur'}],
                    jobType: [{required: true, message: '必填:任务类型', trigger: 'blur'}],
                    startTime: [{required: true, message: '必填:开始时间', trigger: 'blur'}]
                },
                status: ['正常', '暂停'],
                jobtype: [{label: '数据生成', value: 'dataCreate'}, {label: '文件解析', value: 'filejx'}, {
                    label: '文件生成',
                    value: 'fileCreate'
                }, {label: '其他', value: 'other'}],
                jobclass: [],
                jobAllclass: []
            }
        },
        mounted: function () {
            this.loadEmps()
            this.getAllClass()
        },
        methods: {
            // 任务启用
            jobstate(row) {
                this.emp = row
                this.emp.id = row.id
                this.emp.jobName = row.jobName
                this.emp.jobState = row.jobState
                this.emp.executeClass = row.executeClass
                this.emp.description = row.description
                this.emp.cronExpression = row.cronExpression
                this.emp.jobType = row.jobType
                this.emp.startTime = row.startTime
                if (row.jobState === '正常') {
                    this.emp.jobState = '暂停'
                } else {
                    this.emp.jobState = '正常'
                }
                this.tableLoading = true
                this.$axios.put('/quartzs', this.emp).then(resp => {
                    this.tableLoading = false
                    this.emptyEmpData()
                    this.loadEmps()
                    this.$message.error(resp.data.msg)
                })
            },
            // 根据类型获取class
            getClass(jt) {
                this.$axios.get('/initJobClasses/jobType/' + jt).then(resp => {
                    this.tableLoading = false
                    if (resp && resp.code === 0) {
                        var data = resp.data
                        this.jobclass = data.list
                    }
                })
            },
            // 根据类型获取class
            getAllClass() {
                this.$axios.get('/initJobClasses/getAllJobClass').then(resp => {
                    this.tableLoading = false
                    if (resp && resp.code === 0) {
                        var data = resp.data
                        this.jobAllclass = data.list
                    }
                })
            },
            // 任务名格式化方法
            jobNameFormat(row, column, cellValue, index) {
                for (let i = 0; i < this.jobAllclass.length; i++) {
                    if (this.jobAllclass[i].jobClassPath === cellValue) {
                        return this.jobAllclass[i].jobClassName
                    }
                }
            },
            // 任务类型格式化
            jobTypeFormat(row, column, cellValue, index) {
                for (let i = 0; i < this.jobtype.length; i++) {
                    if (this.jobtype[i].value === cellValue) {
                        return this.jobtype[i].label
                    }
                }
            },
            // 时间格式化
            dateFormat(row, column) {
                const date = row[column.property]
                if (date === undefined) {
                    return '未执行'
                }
                if (date === null) {
                    return '未执行'
                }
                return this.$moment(date).format('YYYY-MM-DD HH:mm:ss')// 使用moment插件进行日期格式化
            },
            cancelSearch() {
                this.emptyEmpData()
                this.loadEmps()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            deleteManyEmps() {
                this.$confirm('此操作将删除[' + this.multipleSelection.length + ']条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var ids = ''
                    for (var i = 0; i < this.multipleSelection.length; i++) {
                        ids += this.multipleSelection[i].id + ','
                    }
                    this.doDelete(ids)
                }).catch(() => {
                })
            },
            deleteEmp(row) {
                this.$confirm('此操作将永久删除[' + row.jobName + '], 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.doDelete(row.id)
                }).catch(() => {
                })
            },
            doDelete(ids) {
                this.tableLoading = true
                var _this = this
                this.$axios.delete('/quartzs/delete/' + ids).then(resp => {
                    _this.tableLoading = false
                    if (resp && resp.code === 0) {
                        _this.loadEmps()
                    }
                })
            },
            keywordsChange(val) {
                if (val === '') {
                    this.loadEmps()
                }
            },
            searchEmp() {
                this.loadEmps()
            },
            currentChange(currentChange) {
                this.currentPage = currentChange
                this.loadEmps()
            },
            handleSizeChange(handleSizeChange) {
                this.pageSize = handleSizeChange
                this.loadEmps()
            },
            loadEmps() {
                this.tableLoading = true
                let kw = this.keywords
                let jt = this.jType
                if (kw === '') {
                    kw = '1'
                }
                if (jt === '') {
                    jt = '1'
                }
                this.$axios.get('/quartzs/' + this.currentPage + '/' + this.pageSize + '/' + kw + '/' + jt).then(resp => {
                    this.tableLoading = false
                    if (resp && resp.code === 0) {
                        var data = resp.data
                        this.emps = data.emps
                        this.totalCount = data.count
                    }
                })
            },
            addEmp: function (formName) {
                var _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.emp.id) {
                            // 更新
                            this.tableLoading = true
                            this.$axios.put('/quartzs', this.emp).then(resp => {
                                _this.tableLoading = false
                                _this.dialogVisible = false
                                _this.emptyEmpData()
                                _this.loadEmps()
                                if (resp.data.status === 500) {
                                    _this.$message.error(resp.data.msg)
                                } else {
                                    _this.$message.success(resp.data.msg)
                                }
                            })
                        } else {
                            // 添加
                            this.emp.jobName = this.emp.executeClass.substring(this.emp.executeClass.lastIndexOf('.') + 1, this.emp.executeClass.length)
                            this.tableLoading = true
                            this.$axios.post('/quartzs', this.emp).then(resp => {
                                _this.tableLoading = false
                                _this.dialogVisible = false
                                _this.emptyEmpData()
                                _this.loadEmps()
                            })
                        }
                    } else {
                        return false
                    }
                })
            },
            cancelEidt() {
                this.dialogVisible = false
                this.emptyEmpData()
                this.loadEmps()
            },
            showEditEmpView(row) {
                this.dialogTitle = '编辑定时任务'
                this.emp = row
                this.emp.id = row.id
                this.emp.jobName = row.jobName
                this.emp.jobState = row.jobState
                this.emp.executeClass = row.executeClass
                this.emp.description = row.description
                this.emp.cronExpression = row.cronExpression
                this.emp.jobType = row.jobType
                this.emp.startTime = row.startTime
                this.getClass(row.jobType)
                this.dialogVisible = true
            },
            showAddEmpView() {
                this.dialogTitle = '添加定时任务'
                this.dialogVisible = true
            },
            emptyEmpData() {
                this.emp = {
                    id: '',
                    jobName: '',
                    jobState: '',
                    executeClass: '',
                    description: '',
                    cronExpression: '',
                    jobType: '',
                    startTime: ''
                }
                this.jobclass = []
            },
            dataDownload() {
                try {
                    const formData = new FormData()
                    formData.append('jobName', this.keywords)
                    formData.append('jobType', this.jType)
                    this.$axios.post('/api/quartz/dataDownload', formData, {
                        responseType: 'blob'// 用于解决中文乱码
                    }).then((response) => {
                        this.$message.success('导出成功')
                    })
                } catch (ex) {
                    console.log(ex)
                }
            },
          initJob(){

            this.$confirm('初始化后修改过的数据将被清空，确认初始化吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.btnLonding = true
              this.$axios.get('initJobClasses/initJob').then(resp => {
                this.btnLonding = false
                this.$message.success('初始化成功！')
                this.loadEmps()
                this.getAllClass()
              }).catch((error) => {
                this.btnLonding = false
                this.$message.error("初始化失败，请检查sql文件是否存在！")
              })
            })

          }
        }
    }
</script>
<style>
  .el-dialog__body {
    padding-top: 0px;
    padding-bottom: 0px;
  }

  .slide-fade-enter-active {
    transition: all .8s ease;
  }

  .slide-fade-leave-active {
    transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }

  .slide-fade-enter, .slide-fade-leave-to {
    transform: translateX(10px);
    opacity: 0;
  }
</style>
