<template>
  <div>
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="任务名称">
        <el-input size="small" v-model="queryParams.name" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" plain @click="getList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="success" plain @click="addTask()">创建任务</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column align="center" prop="ptaskId" label="任务id"></el-table-column>
        <el-table-column align="center" prop="ptaskName" label="名称"></el-table-column>
        <el-table-column align="center" prop="ptaskStatus" label="状态" :formatter="formatPtaskStatus"></el-table-column>
        <el-table-column align="center" prop="pcreateTime" label="创建时间" :formatter="formatCreateTime"></el-table-column>
        <el-table-column align="center" prop="pcronExpression" label="定时任务"></el-table-column>
        <el-table-column align="center" prop="prunInfo" label="运行信息" width="100">
          <template slot-scope="{row}">
            <el-button @click="viewInfo(row)" type="text" size="small">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center"
                         fixed="right"
                         label="操作" width="200"
        >
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="light" content="配置定时" placement="top">
              <el-button @click="handleCronClick(row)" plain size="mini" icon="el-icon-timer"/>
            </el-tooltip>
            <el-button @click="handleClick(row)" type="primary" plain size="mini">编辑</el-button>
            <el-button @click="handleDeleteClick(row)" type="danger" plain size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      :title="isEdit?'修改任务':'创建任务'"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose" :close-on-click-modal="false">
      <div>
        <el-form ref="ruleForm" :rules="rules" :model="formData" class="demo-form-inline" label-width="130px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务名称" prop="pTaskName" label-width="100px">
                <el-input v-model="formData.pTaskName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="定时任务" prop="pCronExpression" label-width="100px">
                <el-input v-model="formData.pCronExpression"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>
        <div class="mode-table">
          <div class="mode-table-thead">
            <div class="flex model-table-tr">
              <span class="pa-0 td td0"></span>
              <span class="pa-0 td td1 font-bold">是否开启</span>
              <span class="pa-0 td2 font-bold">参数</span>
            </div>
          </div>
          <div class="mode-table-body">
            <!--    数据获取        -->
            <div class="flex model-table-tr">
              <span class="pa-0 td td0">数据获取</span>
              <span class="pa-0 td td1">
                 <el-radio-group v-model="formData.dataAcquisition.isEnable" size="mini">
                  <el-radio-button :label="true">开启</el-radio-button>
                  <el-radio-button :label="false">关闭</el-radio-button>
                </el-radio-group>
              </span>
              <span class="pa-0 td2">
                <div class="form-table-item">
                   <el-form ref="ruleForm" :rules="dataAcquisitionRules" :model="formData.dataAcquisition.params"
                            class="demo-form-inline"
                            label-width="130px">
                      <el-form-item label="查询语句" prop="query_sql">
                        <el-input v-model="formData.dataAcquisition.params['query_sql']" size="mini"
                                  :disabled="!formData.dataAcquisition.isEnable" type="textarea"
                                  :autosize="{ minRows: 1 }"></el-input>
                      </el-form-item>
                      <el-form-item label="mongo库" prop="mongodb_database">
                        <el-input v-model="formData.dataAcquisition.params['mongodb_database']" size="mini"
                                  :disabled="!formData.dataAcquisition.isEnable" type="textarea"
                                  :autosize="{ minRows: 1 }"></el-input>
                      </el-form-item>
                     <el-form-item label="写入的mongo表" prop="mongodb_write_table">
                        <el-input v-model="formData.dataAcquisition.params['mongodb_write_table']" size="mini"
                                  :disabled="!formData.dataAcquisition.isEnable" type="textarea"
                                  :autosize="{ minRows: 1 }"></el-input>
                      </el-form-item>
                     <el-form-item label="查询的mysql库" prop="mysql_database">
                        <el-input v-model="formData.dataAcquisition.params['mysql_database']" size="mini"
                                  :disabled="!formData.dataAcquisition.isEnable" type="textarea"
                                  :autosize="{ minRows: 1 }"></el-input>
                      </el-form-item>
                   </el-form>
                </div>
              </span>
            </div>
            <!--    数据处理        -->
            <div class="flex model-table-tr">
              <span class="pa-0 td td0">数据处理</span>
              <span class="pa-0 td td1">
                 <el-radio-group v-model="formData.dataCleaning.isEnable" size="mini">
                  <el-radio-button :label="true">开启</el-radio-button>
                  <el-radio-button :label="false">关闭</el-radio-button>
                </el-radio-group>
              </span>
              <span class="pa-0 td2">
                <div class="form-table-item">
                  <data-clean-form ref="dataCleaning" :form-data="formData.dataCleaning"
                                   @child-event="getDataCleaning"></data-clean-form>
                </div>
              </span>
            </div>

            <!--    模型        -->
            <div class="flex model-table-tr">
            <span class="pa-0 td td0">
              <el-select v-model="formData.model.componentType" placeholder="请选择" size="small"
                         style="width: 100%">
                <el-option
                  v-for="item in modelName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </span>
              <span class="pa-0 td td1">
                 <el-radio-group v-model="formData.model.isEnable" size="mini">
                  <el-radio-button :label="true">开启</el-radio-button>
                  <el-radio-button :label="false" disabled>关闭</el-radio-button>
                </el-radio-group>
              </span>
              <span class="pa-0 td2">
                <div class="form-table-item">
                  <model-form ref="model" :form-data="formData.model" @child-event="getModel"></model-form>
                </div>
              </span>
            </div>

            <!--    后处理        -->
            <div class="flex model-table-tr">
              <span class="pa-0 td td0">后处理</span>
              <span class="pa-0 td td1">
                 <el-radio-group v-model="formData.processing.isEnable" size="mini">
                  <el-radio-button :label="true">开启</el-radio-button>
                  <el-radio-button :label="false">关闭</el-radio-button>
                </el-radio-group>
              </span>
              <span class="pa-0 td2">
                <div class="form-table-item">
                  <processing-form ref="processing" :form-data="formData.processing"
                                   @child-event="getProcessing"></processing-form>
                </div>
              </span>
            </div>

          </div>


        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" @click="saveTask">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="运行信息"
      :visible.sync="dialogInfoVisible"
      width="50%"
    >
      <div class="runInfoBox">
        {{ info }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogInfoVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import dataCleanForm from './dataCleanForm.vue'
import modelForm from './modelForm.vue'
import processingForm from './processingForm.vue'
import {addTask, deleteId, queryTasks,updateTask} from "@/api/xvji/predict";
import {formatDateTime} from "@/utils/dateUtil";

export default {
  components: {modelForm, dataCleanForm, processingForm},
  data() {
    return {
      loading: false,
      tableData: [],
      formData: {
        dataAcquisition: {componentType:  '数据获取', isEnable: true, params: {}},
        dataCleaning: {componentType:  '数据处理', isEnable: true, params: {}},
        powerRationing: {componentType:  '限电清洗', isEnable: true, params: {}},
        model: {componentType:  '模型', isEnable: true, params: {}},
        modelTest: {componentType:  '模型测试', isEnable: true, params: {}},
        processing: {componentType:  '后处理', isEnable: true, params: {}},
        report: {componentType:  '分析报告', isEnable: true, params: {}},
      },
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name:  '',
      },
      isEdit: false,
      dialogVisible: false,
      dialogInfoVisible: false,
      info: '',
      rules: {
        pTaskName: [
          {required: true, message: '请填写任务名称', trigger: 'blur'}
        ]
      },
      dataAcquisitionRules: {
        query_sql: [
          {required: true, message: '请填写查询语句', trigger: 'blur'}
        ],
        mongodb_database: [
          {required: true, message: '请填写mongo库', trigger: 'blur'}
        ],
        mongodb_write_table: [
          {required: true, message: '请填写写入的mongo表', trigger: 'blur'}
        ],
        mysql_database: [
          {required: true, message: '请填写查询的mysql库', trigger: 'blur'}
        ],
      },
      powerRationingName: [
        {label: '限电清洗-光伏', value: '限电清洗-光伏'},
        {label: '限电清洗-风电', value: '限电清洗-风电'}
      ],
      modelName: [
        {label: '光伏物理模型', value: '光伏物理模型'},
        {label: '风电物理模型', value: '风电物理模型'},
        {label: 'Holtwinters模型', value: 'Holtwinters模型'},
        {label: 'LSTM', value: 'LSTM'},
        {label: '机器学习模型', value: '机器学习模型'}
      ],
      modelOption:['光伏物理模型', '风电物理模型','Holtwinters模型','LSTM','机器学习模型',],
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.loading = true
      queryTasks(this.queryParams).then(res=>{
        this.tableData = res.data.list
        // console.log(this.tableData[0])
        this.total = res.data.total
        this.loading = false
      }).catch(err=>{
        this.loading = false
      })
    },
    // 新增
    addTask() {
      this.isEdit = false
      this.dialogVisible = true
      this.formData = {
        pTaskName: '',
        pCronExpression: '',
        dataAcquisition: {componentType:  '数据获取', isEnable: true, params: {}},
        dataCleaning: {componentType:  '数据处理', isEnable: true, params: {}},
        model: {componentType:  '光伏物理模型', isEnable: true, params: {}},
        processing: {componentType:  '后处理', isEnable: true, params: {}},
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
    },
    // 编辑
    handleClick(row) {
      this.isEdit = true
      this.formData = {
        pTaskId:row.ptaskId,
        pTaskName: row.ptaskName,
        pTaskStatus: row.ptaskStatus,
        pComponentIds:row.pcomponentIds,
        pCreateTime:row.pcreateTime,
        pCronExpression:row.pcronExpression,
        pQuartzTask:row.pquartzTask,
        pRunInfo:row.prunInfo,
        dataAcquisition: row.components.find(w=>w.componentType.includes('数据获取'))|| {componentType: '数据获取', isEnable: true, params:{}},
        dataCleaning: row.components.find(w=>w.componentType ==='数据处理')|| {componentType: '数据处理', isEnable: true, params:{}},
        model: row.components.find(w=>this.modelOption.includes(w.componentType))|| {componentType: '光伏物理模型', isEnable: true, params:{}},
        processing: row.components.find(w=>w.componentType ==='后处理') || {componentType: '后处理', isEnable: true, params:{}},
      }
      this.dialogVisible = true
    },
    //保存
    saveTask() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          await this.$refs.dataCleaning.saveTask()
          if (JSON.stringify(this.formData.dataCleaning.params) === '{}') {
            return false
          }
          await this.$refs.model.saveTask()
          if (JSON.stringify(this.formData.model.params) === '{}') {
            return false
          }
          await this.$refs.processing.saveTask()
          if (JSON.stringify(this.formData.processing.params) === '{}') {
            return false
          }
          if(!this.isEdit){
            addTask(this.formData).then(res=>{
              if(res.code === 200){
                this.$message({
                  type: 'success',
                  message: res.msg
                });
              }else{
                this.$message({
                  type: 'danger',
                  message: res.msg
                });
              }
              this.getList()
              this.dialogVisible = false
            })
          }else{
            updateTask(this.formData).then(res=>{
              if(res.code === 200){
                this.$message({
                  type: 'success',
                  message: res.msg
                });
              }else{
                this.$message({
                  type: 'danger',
                  message: res.msg
                });
              }
              this.getList()
              this.dialogVisible = false
            })
          }
        } else {
          this.$message({
            message: '校验不通过',
            type: 'warning'
          })
          return false;
        }
      });
      // this.dialogVisible = false
    },
    //定时任务跳转
    handleCronClick(row){
      let param = {
        taskId:row.ptaskId,
        taskName:row.ptaskName,
        jobGroup: "PREDICT_TASK"
      }
      this.$router.push({ name: 'Job', params: { row: JSON.stringify(param)} })
    },
    // 数据处理数据
    getDataCleaning(val) {
      this.formData.dataCleaning.params = val
    },
    getModel(val) {
      this.formData.model.params = val
    },

    getProcessing(val) {
      this.formData.processing.params = val
    },

    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.formData = {
        pTaskId: '',
        pTaskName: '',
        pCronExpression: '',
        dataAcquisition: {componentType:  '数据获取', isEnable: true, params: {}},
        dataCleaning: {componentType:  '数据处理', isEnable: true, params: {}},
        model: {componentType:  '光伏物理模型', isEnable: true, params: {}},
        processing: {componentType:  '后处理', isEnable: true, params: {}},
      }
      this.dialogVisible = false
    },

    // 运行信息
    viewInfo(row) {
      if(row.prunInfo !==null){
        this.info = row.prunInfo
        this.dialogInfoVisible = true
      }else{
        this.info = null
        this.$message({
          type: 'warning',
          message: '暂无运行信息'
        });
      }

    },
    //删除
    handleDeleteClick(row){
      this.$confirm('此操作将永久删除'+row.ptaskName+'任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteId(row.ptaskId).then(res=>{
          if(res.code === 200){
            this.$message({
              type: 'success',
              message: res.msg
            });
          }else{
            this.$message({
              type: 'danger',
              message: res.msg
            });
          }
          this.getList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    formatCreateTime(row){
      return formatDateTime(new Date(row.pcreateTime))
    },
    formatPtaskStatus(row){
      return row.ptaskStatus === 0?'失败':row.ptaskStatus === 1?'成功':'未运行'
    }
  }
}
</script>

<style scoped lang="scss">
.form-table-item {
  max-height: 30vh;
  overflow-y: auto;

  ::v-deep .el-form-item {
    margin-bottom: 15px;
  }
}

.td0 {
  width: 200px;
}

.td1 {
  width: 150px;
}

.td2 {
  width: calc(100% - 350px);
}
.mode-table{
  max-height: 63vh;
  overflow-y: auto;
  position: relative;
  border-collapse: separate;
}
.mode-table-thead {
  position: sticky;
  top: 0;
  z-index: 1000000;
  background-color: white;
}
.mode-table.mode-table-body .model-table-tr {
  &:last-child{
    border-bottom: 1px solid #ebeef5;
  }
}
.mode-table .mode-table-body .model-table-tr{
  &:first-child{
    border-top: none;
  }
}
.mode-table .model-table-tr:last-child {
  border-bottom: 1px solid #ebeef5;
}

.model-table-tr {
  width: 100%;
  text-align: center;
  border: 1px solid #ebeef5;
  border-bottom: none;
  line-height: 30px;

  .td {
    border-right: 1px solid #ebeef5;
    display: grid;
    place-items: center;
  }

  .pa-0 {
    padding: 0 .5vw;

  }
}
.runInfoBox{
  line-height: 25px;
  white-space: pre-wrap;
}
</style>
