<template>
  <div class="fullheight single-padding">
    <el-page-header
      @back="goBack"
      content="模型任务"
      style="margin-bottom:20px;"
    >
    </el-page-header>
    <div style="width:100%;height:calc(100% - 44px);">
      <ht-table
        @load="loadData"
        @row-dblclick="row => showDialog(row.id)"
        :data="data"
        :pageResult="pageResult"
        :selection="true"
        :selectable="false"
        quick-search-props="taskName"
        :default-sorter="[{direction: 'ASC', property: 'taskName'}]"
        :show-export="false"
        :show-custom-column="false"
        ref="htTable"
      >
        <template v-slot:toolbar>
          <el-button
            :disabled="data.length >= 1"
            size="small"
            @click="showDialog()"
            icon="el-icon-plus"
            type="primary"
            >添加</el-button
          >
        </template>
        <template>
          <ht-table-column
            prop="actuatorName"
            label="任务执行器"
            :show-overflow-tooltip="true"
          >
          </ht-table-column>
          <ht-table-column
            prop="taskName"
            label="任务名称"
            :show-overflow-tooltip="true"
          >
          </ht-table-column>
          <ht-table-column
            prop="taskRate"
            label="任务调用频率"
            :show-overflow-tooltip="true"
          >
            <template v-slot="{row}">
              <div v-if="row.taskRateUnit == 'm'">
                {{ row.taskRate + '分钟' }}
              </div>
              <div v-if="row.taskRateUnit == 'h'">
                {{ row.taskRate + '小时' }}
              </div>
              <div v-if="row.taskRateUnit == 'd'">
                {{ row.taskRate + '天' }}
              </div>
              <div v-if="row.taskRateUnit == 'w'">
                {{ row.taskRate + '周' }}
              </div>
              <div v-if="row.taskRateUnit == 'M'">
                {{ row.taskRate + '月' }}
              </div>
              <div v-if="row.taskRateUnit == 'Y'">
                {{ row.taskRate + '年' }}
              </div>
            </template>
          </ht-table-column>
          <ht-table-column
            prop="taskStatus"
            label="任务运行状态"
            :show-overflow-tooltip="true"
          >
            <template v-slot="{row}">
              <el-tag
                type="danger"
                v-if="row.taskStatus == 'NONE' || row.taskStatus == ''"
                >停止</el-tag
              >
              <el-tag v-if="row.taskStatus == 'NORMAL'">启动</el-tag>
              <el-tag type="warning" v-if="row.taskStatus == 'PAUSED'"
                >暂停</el-tag
              >
            </template>
          </ht-table-column>
          <ht-table-column
            label="操作"
            width="145"
            :show-overflow-htoolitp="true"
          >
            <template v-slot="{row}">
              <el-dropdown
                size="mini"
                split-button
                @command="handleCommand"
                @click="
                  handleCommand({
                    id: row.id,
                    ename: 'delete',
                    code: row.modelId
                  })
                "
              >
                <span
                  :command="{
                    id: row.id,
                    ename: 'delete',
                    code: row.modelId
                  }"
                >
                  <i class="el-icon-delete"></i>删除
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    icon="el-icon-video-pause"
                    v-if="row.taskStatus == 'NORMAL'"
                    :command="{
                      id: row.id,
                      ename: 'NONE'
                    }"
                    >停止</el-dropdown-item
                  >

                  <el-dropdown-item
                    icon="el-icon-video-play"
                    v-if="
                      row.taskStatus == 'NONE' ||
                        row.taskStatus == 'PAUSED' ||
                        row.taskStatus == ''
                    "
                    :command="{
                      id: row.id,
                      ename: 'NORMAL'
                    }"
                    >启动</el-dropdown-item
                  >
                  <el-dropdown-item
                    icon="el-icon-search"
                    :command="{
                      row: row,
                      ename: 'ModelLog'
                    }"
                    >日志查询</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </ht-table-column>
        </template>
      </ht-table>
    </div>
    <common-dialog
      width="800px"
      title="模型任务信息"
      class="sp-manager__dialog"
      :visible="dialogVisible"
      :before-close="beforeCloseDialog"
      destroy-on-close
    >
      <el-form v-form data-vv-scope="modelTaskForm">
        <ht-form-item label="任务执行器" label-width="120px">
          <ht-select
            style="width:500px"
            v-model="modelTaskInfo.taskActuator"
            :options="taskList"
            validate="required"
            placeholder="请选择任务执行器"
          />
        </ht-form-item>
        <ht-form-item label="任务名称" label-width="120px">
          <ht-input
            style="width:500px"
            v-model="modelTaskInfo.taskName"
            validate="required"
            placeholder="请输入任务名称"
          />
        </ht-form-item>
        <el-row>
          <el-col :span="9.5">
            <ht-form-item label="任务调用频率" label-width="120px">
              <ht-input
                v-model="modelTaskInfo.taskRate"
                type="number"
                :min="0"
                validate="required"
              />
            </ht-form-item>
          </el-col>
          <el-col :span="6">
            <ht-form-item label-width="0" style="padding-left:5px">
              <ht-select
                style="width: 85px"
                v-model="modelTaskInfo.taskRateUnit"
                :options="[
                  {key: 'm', value: '分钟'},
                  {key: 'h', value: '小时'},
                  {key: 'd', value: '天'},
                  {key: 'w', value: '周'},
                  {key: 'M', value: '月'},
                  {key: 'Y', value: '年'}
                ]"
                validate="required"
              ></ht-select>
            </ht-form-item>
          </el-col>
        </el-row>
        <ht-form-item label="任务说明" label-width="120px">
          <ht-input
            type="textarea"
            style="width:500px"
            v-model="modelTaskInfo.taskMemo"
          ></ht-input>
        </ht-form-item>
      </el-form>
      <div slot="footer" style="text-align: center">
        <ht-submit-button
          url="${cssc}/biz/model/modelTask/v1/"
          :model="modelTaskInfo"
          :request-method="saveMethod"
          scope-name="modelTaskForm"
          @after-save-data="afterSaveData"
          >保存</ht-submit-button
        >
        <el-button @click="beforeCloseDialog">取消</el-button>
      </div>
    </common-dialog>
  </div>
</template>
<script>
import req from '@/request.js'
export default {
  name: 'model-task',
  data() {
    return {
      taskList: [],
      dialogVisible: false,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      modelTaskInfo: {
        modelId: this.$route.params.id,
        taskRateUnit: 'm'
      },
      saveMethod: 'POST'
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
    this.initTaskList()
  },
  methods: {
    //初始化执行器下拉列表
    initTaskList() {
      this.$http
        .post('${cssc}/biz/model/modelActuator/v1/onlineList')
        .then(res => {
          let data = []
          res.data.forEach(item => {
            let obj = {
              key: item.id,
              value: item.actuatorName
            }
            data.push(obj)
          })
          // console.log(data)
          this.taskList = data
        })
    },
    //操作下拉选择
    handleCommand(command) {
      const headersUrlencoded = {
        'Content-type': 'application/x-www-form-urlencoded'
      }
      if (command.ename == 'delete') {
        //删除
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(() => {
            this.$http
              .remove('${cssc}/biz/model/modelTask/v1/' + command.id)
              .then(res => {
                if (res.data.state) {
                  this.$message({
                    type: 'success',
                    message: '删除成功'
                  })
                  this.$refs.htTable.load()
                }
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      } else if (command.ename == 'NORMAL') {
        //启动
        this.$confirm('是否启动运行状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(() => {
            req
              .request({
                url: '${cssc}/biz/model/modelTask/v1/startUpJob',
                params: {id: command.id},
                headers: headersUrlencoded,
                method: 'POST'
              })
              .then(res => {
                if (res.data.state) {
                  this.$message({
                    type: 'success',
                    message: res.data.message
                  })
                  this.$refs.htTable.load()
                }
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      } else if (command.ename == 'NONE') {
        //停止
        this.$confirm('是否停止运行状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(() => {
            req
              .request({
                url: '${cssc}/biz/model/modelTask/v1/stopJob',
                params: {id: command.id},
                headers: headersUrlencoded,
                method: 'POST'
              })
              .then(res => {
                if (res.data.state) {
                  this.$message({
                    type: 'success',
                    message: res.data.message
                  })
                  this.$refs.htTable.load()
                }
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      } else if (command.ename == 'ModelLog') {
        this.$router.push({
          name: 'ModelLog',
          params: {
            row: command.row
          }
        })
      }
    },
    loadData(param, cb) {
      let modelIdQuery = [
        {
          group: 'main',
          opreation: 'EQUAL',
          parentGroup: '',
          property: 'modelId',
          relation: 'AND',
          value: this.modelTaskInfo.modelId
        }
      ]
      if (param.querys && param.querys.length) {
        param.querys.push(...modelIdQuery)
      } else {
        param.querys = modelIdQuery
      }
      this.$http
        .post('${cssc}/biz/model/modelTask/v1/query', param)
        .then(
          res => {
            let resp = res.data
            this.data = resp.rows
            this.pageResult = {
              page: resp.page,
              pageSize: resp.pageSize,
              total: resp.total
            }
          },
          error => {
            reject(error)
          }
        )
        .finally(() => cb())
    },
    showDialog(id) {
      if (id) {
        this.saveMethod = 'PUT'
        this.$http.get('${cssc}/biz/model/modelTask/v1/' + id).then(
          resp => {
            this.modelTaskInfo = resp.data
            this.dialogVisible = true
          },
          error => {
            reject(error)
          }
        )
      } else {
        this.saveMethod = 'POST'
        this.dialogVisible = true
      }
    },
    beforeCloseDialog() {
      this.dialogVisible = false
      this.modelTaskInfo = {
        modelId: this.$route.params.id,
        taskRateUnit: 'm'
      }
    },
    afterSaveData() {
      setTimeout(() => {
        this.beforeCloseDialog()
        this.$refs.htTable.load()
      }, 500)
    },

    goBack() {
      this.$router.push({name: 'ModelInfoManager'})
    }
  }
}
</script>
<style lang="scss" scoped>
.sp-manager__dialog /deep/ .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
  padding: 20px;
}
/deep/ .el-page-header__content {
  font-size: 16px;
}
/deep/ .el-dialog__body {
  padding: 30px 70px 10px !important;
}
</style>
