<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.projectName" placeholder="请输入项目名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="8 || 24" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button v-if="$auth('tasks-add')" type="primary" icon="plus" @click="$refs.baseModal.base()">新增</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && $auth('tasks-del')">
        <a-menu slot="overlay">
          <a-popconfirm title="是否要删除所选数据？" @confirm="batchDelete()">
            <a-menu-item key="1"><a-icon type="delete" /><a>删除</a></a-menu-item>
          </a-popconfirm>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="jobId"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >

      <span slot="status" slot-scope="text">
        <a-badge :status="text | statusConstantStatus('TaskStatus')" :text="text | statusConstantText('TaskStatus')" />
      </span>

      <span slot="action" slot-scope="record">
        <template>
          <!--<a @click="handleView(record)">详情</a>
          <a-divider type="vertical" />-->
          <a v-if="$auth('tasks-edit')" @click="handleEdit(record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm v-if="$auth('tasks-run')" title="是否要执行该条任务？" @confirm="batchRun(record.jobId)">
            <a>执行</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a-popconfirm v-if="$auth('tasks-del') && record.status === 0" title="是否要暂停该条任务？" @confirm="batchPause(record.jobId)">
            <a>暂停</a>
          </a-popconfirm>
          <a-popconfirm v-if="$auth('tasks-del') && record.status === 1" title="是否要恢复该条任务？" @confirm="batchResume(record.jobId)">
            <a>恢复</a>
          </a-popconfirm>

          <a-divider type="vertical" />
          <a-popconfirm v-if="$auth('tasks-del')" title="是否要删除该条数据？" @confirm="batchDelete(record.jobId)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </span>
    </s-table>
    <base-form ref="baseModal" @ok="handleOk"/>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './modules/BaseForm'
import { getTaskPage, deleteTasks, fetchTask, runTasks, pauseTasks, resumeTasks } from '@/api/upms/task'

export default {
  name: 'TaskList',
  components: {
    STable,
    Ellipsis,
    BaseForm
  },
  data () {
    return {
      mdl: {},
      // 查询参数
      queryParam: {
      },
      // 表头

      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          customRender: (text, record, index) => {
            return `${(this.$refs.table.localPagination.current - 1) * this.$refs.table.localPagination.pageSize + index + 1}`
          }
        },
        {
          title: '名称',
          dataIndex: 'beanName',
          width: 100
        },
        {
          title: '方法名',
          dataIndex: 'methodName',
          width: 100
        },
        {
          title: '参数',
          dataIndex: 'params',
          width: 100
        },
        {
          title: 'cron表达式',
          dataIndex: 'cronExpression',
          width: 100
        },
        {
          title: '任务状态',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        parameter = {
          ...parameter,
          ...this.queryParam,
          dataScope: {
            sortBy: 'desc',
            sortName: 'update_time'
          }
        }
        // console.log(this.$refs.table.localPagination)
        return getTaskPage(Object.assign(parameter, this.queryParam))
          .then(res => {
            const rows = res.data.rows
            // key不是字符串会报错
            if (rows !== null && rows.length > 0) {
              for (let i = 0; i < rows.length; i++) {
                rows[i].jobId = rows[i].jobId + ''
              }
            }
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      menus: [],

      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  created () {
    this.tableOption()
  },
  methods: {
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: false,
                name: record.jobId
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    batchDelete (jobId) {
      let jobIds = []
      if (this.BaseTool.String.isBlank(jobId)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要删除的记录')
          return
        }
        jobIds = this.selectedRows.map(item => item.jobId)
      } else {
        jobIds = [jobId]
      }
      deleteTasks(jobIds).then(res => {
        this.$message.info('删除成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    batchRun (jobId) {
      let jobIds = []
      if (this.BaseTool.String.isBlank(jobId)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要执行的任务')
          return
        }
        jobIds = this.selectedRows.map(item => item.jobId)
      } else {
        jobIds = [jobId]
      }
      runTasks(jobIds).then(res => {
        this.$message.info('执行成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    batchPause (jobId) {
      let jobIds = []
      if (this.BaseTool.String.isBlank(jobId)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要暂停的任务')
          return
        }
        jobIds = this.selectedRows.map(item => item.jobId)
      } else {
        jobIds = [jobId]
      }
      pauseTasks(jobIds).then(res => {
        this.$message.info('暂停成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    batchResume (jobId) {
      let jobIds = []
      if (this.BaseTool.String.isBlank(jobId)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要恢复的任务')
          return
        }
        jobIds = this.selectedRows.map(item => item.jobId)
      } else {
        jobIds = [jobId]
      }
      resumeTasks(jobIds).then(res => {
        this.$message.info('恢复成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    handleEdit (record) {
      console.log(record)
      fetchTask({ jobId: record.jobId }).then(res => {
        const modal = this.$refs.baseModal
        modal.base(res.data)
      })
    },
    handleView (record) {
      fetchTask({ jobId: record.jobId }).then(res => {
        const modal = this.$refs.detailModal
        modal.base(res.data)
      })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
      }
      this.$refs.table.refresh(true)
    }
  }
}
</script>
