<template>
  <a-card class="settlement" :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="20">
          <a-col :md="6" :sm="24">
            <a-form-item style="margin-bottom: 0;">
              <a-input v-model.trim="queryParam.name" placeholder="定时器名称" allowClear/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="btns">
      <a-button @click="addJob()" type="primary" icon="plus-circle">添加JOB</a-button>
      <a-button @click="startJob()" type="default" icon="play-circle">启动</a-button>
      <a-button @click="stopJob()" type="default" icon="stop">停止</a-button>
    </div>

    <s-table
      ref="table"
      size="small"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :bordered="true"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
    >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="editJob(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="deleteRow(record)">删除</a>
          <a-divider type="vertical" />
          <a @click="syncJob(record)">立即运行一次</a>
        </template>
      </span>
      <span slot="isEnable" slot-scope="text, record">
        {{ record.isEnable ? '启用' : '禁用' }}
      </span>
      <div slot="status" slot-scope="text, record">
        <span v-if="record.status === 'STAT'" style="color:green">运行中</span>
        <span v-if="record.status !== 'STAT'" style="color:red">已停止</span>
      </div>
    </s-table>

    <a-modal
      title="添加JOB"
      v-model="visible"
      :footer="null"
      :maskClosable="false"
      @cancel="handleCancel"
    >
      <a-form
        @submit="handleSubmit"
        :form="form"
      >
        <a-form-item
          label="JOB名称"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 17 }"
        >
          <a-input v-decorator="['formData.name',{initialValue: formData.name,rules:[{ required: true, message: '请输入JOB名称' }]}]"/>
        </a-form-item>
        <a-form-item
          label="JOB分组"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 17 }"
        >
          <a-input v-decorator="['formData.group',{initialValue: formData.group,rules:[{ required: true, message: '请输入JOB分组称' }]}]"/>
        </a-form-item>
        <a-form-item
          label="JOB业务类名"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 17 }"
        >
          <a-input v-decorator="['formData.className',{initialValue: formData.className,rules:[{ required: true, message: '请输入JOB业务类名' }]}]"/>
        </a-form-item>
        <a-form-item
          label="CRON表达式"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 17 }"
        >
          <a-input @click="openCronModal" v-model="formData.cron" @change="setCorn">
            <a-icon slot="prefix" type="schedule" title="corn控件"/>
            <a-icon v-if="formData.cron" slot="suffix" type="close-circle" @click="formData.cron=''" title="清空"/>
          </a-input>
          <JCronModal ref="innerVueCron" :data="formData.cron" @ok="setCorn"></JCronModal>
        </a-form-item>
        <a-form-item
          label="是否启用"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 17 }"
        >
          <a-switch checkedChildren="启用" unCheckedChildren="禁用" v-decorator="['formData.isEnable', { initialValue: formData.isEnable, valuePropName: 'checked' }]" />
          <!-- <a-switch checkedChildren="启用" unCheckedChildren="禁用" :checked="formData.isEnable" @change="changeStatus"/> -->
        </a-form-item>

        <div class="jobBtns">
          <a-button key="back" @click="handleCancel">取消</a-button>
          <a-button htmlType="submit" :loading="loading" type="primary">
            确定
          </a-button>
        </div>

      </a-form>
    </a-modal>

  </a-card>
</template>

<script>
import { STable } from '@/components'
import { listJob, pauseJob, resumeJob, delJob, callJob, addJob } from '@/api/job.js'
import JCronModal from '@/components/Cron/JCronModal'

export default {
  name: 'Jobs',
  components: {
    STable,
    JCronModal
  },
  data () {
    return {
      showCron: false,
      // 查询参数
      queryParam: {
        name: ''
      },
      selectedRowKeys: [],
      visible: false,
      loading: false,
      formLayout: 'horizontal',
      formData: {},
      formBackData: {
        name: '',
        group: '',
        className: '',
        cron: '',
        isEnable: false
      },
      form: this.$form.createForm(this),
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'no',
          width: '70px',
          align: 'center'
        },
        {
          title: 'JOB名称',
          dataIndex: 'name',
          width: '150px',
          align: 'center'
        },
        {
          title: 'JOB状态',
          dataIndex: 'status',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: 'JOB分组',
          dataIndex: 'group',
          width: '150px',
          align: 'center'
        },
        {
          title: 'JOB业务类名',
          dataIndex: 'className',
          width: '200px',
          align: 'center'
        },
        {
          title: 'CRON表达式',
          dataIndex: 'cron',
          width: '150px',
          align: 'center'
        },
        {
          title: '是否启用',
          dataIndex: 'isEnable',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'isEnable' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '250px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return listJob(Object.assign(parameter, this.queryParam)).then(res => {
          const data = res.data
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
            data.list[i].isEnable = data.list[i].isEnable + '' === '1'
          }
          return data
        })
      }
    }
  },
  created () {

  },
  methods: {
    // 打开cron 表达式弹框
    openCronModal () {
      this.$refs.innerVueCron.show()
    },
    setCorn (data) {
      console.log('cron data', data)
      // this.formData.cron = data
      this.$set(this.formData, 'cron', data)
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          // 保存数据
          let params = Object.assign(this.formData, values.formData)
          params = Object.assign({}, params)
          params.isEnable = params.isEnable ? 1 : 0
          params.id = this.formData.id

          if (params.cron == '' || params.cron.length == 0) {
            this.$message.warning('请输入CRON表达式')
            return
          }

          this.loading = true
          addJob(params).then(res => {
            console.log(res)
            if (res.status + '' === '200') {
              this.$message.success(params.id ? '修改成功' : '保存成功')
              this.visible = false
              this.$refs.table.refresh(true)
            } else {
              // this.$message.warning(res.message)
            }
            this.loading = false
          })
        }
      })
    },
    // 编辑
    editJob (record) {
      this.visible = true
      this.formData = Object.assign({}, {
        id: record.id,
        name: record.name,
        group: record.group,
        className: record.className,
        cron: record.cron,
        isEnable: record.isEnable
      })
    },
    /**
     * 删除选中的job
     * @param params
     */
    deleteRow (record) {
      const that = this
      const h = this.$createElement
      this.$confirm({
        title: '提示',
        content: h('div', {
          style: {
            textAlign: 'center'
          }
        }, [
          h('div', '删除后，数据将无法恢复。'),
          h('div', '确认删除吗？')
        ]),
        onOk () {
          delJob({ id: record.id }).then(res => {
            if (res.status === '200') {
              that.$message.success('删除成功')
              that.$refs.table.refresh()
            }
          })
        }
      })
    },
    /**
     * 立即执行一次
     * @param params
     */
    syncJob (record) {
      const that = this
      const h = this.$createElement
      this.$confirm({
        title: '提示',
        content: h('div', {
          style: {
            textAlign: 'center'
          }
        }, [
          h('div', '是否立即执行一次定时器。')
        ]),
        onOk () {
          callJob({ id: record.id }).then(res => {
            if (res.status === '200') {
              that.$message.success('执行成功')
              that.$refs.table.refresh()
            }
          })
        }
      })
    },
    handleCancel (e) {
      this.visible = false
      this.loading = false
      this.formData = Object.assign({}, this.formBackData)
      this.form.resetFields()
    },
    addJob () {
      this.formData = Object.assign({}, this.formBackData)
      this.form.resetFields()
      this.visible = true
    },
    /**
     * 批量启动
     */
    startJob () {
      const _this = this
      const checkIds = this.selectedRowKeys
      if (checkIds.length) {
        // 调用后台启动方法
        resumeJob({
          ids: checkIds
        }).then(res => {
          if (res.status === '200') {
            _this.$message.success('操作成功')
          } else {
            _this.$message.info(res.message)
          }
          _this.$refs.table.refresh()
        })
      } else {
        this.$message.info('请选择需要启动的服务')
      }
    },
    /**
     * 批量停止
     */
    stopJob () {
      const _this = this
      const h = this.$createElement
      const checkIds = this.selectedRowKeys
      if (checkIds.length) {
        this.$confirm({
          title: '提示',
          content: h('div', {
            style: {
              textAlign: 'center'
            }
          }, [
            h('div', '您确定停止所选的服务吗？')
          ]),
          onOk () {
            pauseJob({
              'ids': checkIds
            }).then(res => {
              if (res.status === '200') {
                _this.$message.success('操作成功')
              } else {
                _this.$message.info(res.message)
              }
              _this.$refs.table.refresh()
            })
          }
        })
      } else {
        this.$message.info('请选择需要停止的服务')
      }
    },
    /**
     * 获取选中的列表
     * @returns {Array}
     */
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    }
  }
}
</script>
<style>
  .jobBtns{
    text-align: center;
    padding-top: 20px;
  }
  .jobBtns button{
    margin: 0 10px;
  }
  .ant-modal-footer{
    text-align: center;
  }
  .ant-modal-body .ant-form-item{
    margin-bottom: 10px;
  }
  .btns{
    padding-bottom: 15px;
  }
  .btns button{
    margin-right: 15px;
  }
  .ant-table-thead > tr > th, .ant-table-tbody > tr > td{
    word-break: break-all;
  }
</style>
