<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="ttaskId" label="任务id"></el-table-column>
        <el-table-column align="center" prop="ttaskName" label="名称"></el-table-column>
        <el-table-column align="center" prop="ttaskStatus" label="状态" :formatter="formatPtaskStatus"></el-table-column>
        <el-table-column align="center" prop="tcreateTime" label="创建时间" :formatter="formatCreateTime"></el-table-column>
        <el-table-column align="center" prop="tcronExpression" label="定时任务"></el-table-column>
        <el-table-column align="center" prop="tanalysisReport" label="报告分析" width="100">
          <template slot-scope="{row}">
            <el-button @click="viewReport(row)" type="text" size="small">预览</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="trunInfo" 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-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="tTaskName" label-width="100px">
                <el-input v-model="formData.tTaskName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="定时任务" prop="tCronExpression" label-width="100px">
                <el-input v-model="formData.tCronExpression"></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.powerRationing.componentType" @change="powerRationingNameChange"
                         placeholder="请选择"
                         size="small" style="width: 100%">
                <el-option
                  v-for="item in powerRationingName"
                  :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.powerRationing.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">
                  <power-rationing-form ref="powerRationing" :form-data="formData.powerRationing"
                                        @child-event="getPowerRationing"></power-rationing-form>
                </div>
              </span>
            </div>
            <!--    模型        -->
            <div class="flex model-table-tr">
            <span class="pa-0 td td0">
              <el-select v-model="formData.model.componentType" @change="isDisableModeTest" 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" v-if="!modelTestDisable">
              <span class="pa-0 td td0">{{ formData.modelTest.componentType }}</span>
              <span class="pa-0 td td1">
                 <el-radio-group v-model="formData.modelTest.isEnable" size="mini">
                  <el-radio-button :label="true" :disabled="modelTestDisable">开启</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-test-form ref="modelTest" :form-data="formData.modelTest"
                                   @child-event="getModelTest"></model-test-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 class="flex model-table-tr">
              <span class="pa-0 td td0">分析报告</span>
              <span class="pa-0 td td1">
                 <el-radio-group v-model="formData.report.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">
                  <report-form ref="report" :form-data="formData.report"
                               @child-event="getReport"></report-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 powerRationingForm from './powerRationingForm.vue'
import modelForm from './modelForm.vue'
import modelTestForm from './modelTestForm.vue'
import processingForm from './processingForm.vue'
import reportForm from './reportForm.vue'
import {addTask, deleteId, queryTasks, updateTask} from "@/api/xvji/training";
import {formatDateTime} from "@/utils/dateUtil";

export default {
  components: {modelForm, modelTestForm, dataCleanForm, powerRationingForm, processingForm, reportForm},
  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: {}},
      },
      modelTestDisable: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
      },
      isEdit: false,
      dialogVisible: false,
      dialogInfoVisible: false,
      info: '',
      rules: {
        tTaskName: [
          {required: true, message: '请填写任务名称', trigger: 'blur'}
        ],
        name: [
          {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', '机器学习模型',],
      modelTestOption: ['LSTM-测试', '机器学习模型-测试',],
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      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 = {
        tTaskName: '',
        tCronExpression: '',
        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: {}},
      }
      this.$nextTick(() => {
        this.powerRationingNameChange() // 无意义，限电清洗表单不渲染刷新操作
        this.$refs.ruleForm.clearValidate()
      })
    },
    // 编辑
    handleClick(row) {
      this.isEdit = true
      this.formData = {
        tTaskId: row.ttaskId,
        tTaskName: row.ttaskName,
        tTaskStatus: row.ttaskStatus,
        tAnalysisReport: row.tanalysisReport,
        tComponentIds: row.tcomponentIds,
        tCreateTime: row.tcreateTime,
        tCronExpression: row.tcronExpression,
        tQuartzTask: row.tquartzTask,
        tRunInfo: row.trunInfo,
        dataAcquisition: row.components.find(w => w.componentType.includes('数据获取')) || {
          componentType: '数据获取',
          isEnable: true,
          params: {}
        },
        dataCleaning: row.components.find(w => w.componentType === '数据处理') || {
          componentType: '数据处理',
          isEnable: true,
          params: {}
        },
        powerRationing: row.components.find(w => w.componentType.includes('限电清洗')) || {
          componentType: '限电清洗-光伏',
          isEnable: true,
          params: {}
        },
        model: row.components.find(w => this.modelOption.includes(w.componentType)) || {
          componentType: '光伏物理模型',
          isEnable: true,
          params: {}
        },
        modelTest: row.components.find(w => this.modelTestOption.includes(w.componentType)) || {
          componentType: '模型测试',
          isEnable: true,
          params: {}
        },
        processing: row.components.find(w => w.componentType === '后处理') || {
          componentType: '后处理',
          isEnable: true,
          params: {}
        },
        report: row.components.find(w => w.componentType === '分析报告') || {
          componentType: '分析报告',
          isEnable: true,
          params: {}
        },
      }
      // console.log(this.formData.powerRationing)
      this.dialogVisible = true
    },
    //删除
    handleDeleteClick(row) {
      this.$confirm('此操作将永久删除' + row.ttaskName + '任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteId(row.ttaskId).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: '已取消删除'
        });
      });
    },
    //保存
    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.powerRationing.saveTask()
          if (JSON.stringify(this.formData.powerRationing.params) === '{}') {
            return false
          }
          await this.$refs.model.saveTask()
          if (JSON.stringify(this.formData.model.params) === '{}') {
            return false
          }
          if (this.formData.model.componentType.includes('LSTM') || this.formData.model.componentType.includes('机器')) {
            await this.$refs.modelTest.saveTask()
            if (JSON.stringify(this.formData.modelTest.params) === '{}') {
              return false
            }
          } else {
            this.formData.modelTest = {}
          }
          await this.$refs.processing.saveTask()
          if (JSON.stringify(this.formData.processing.params) === '{}') {
            return false
          }
          await this.$refs.report.saveTask()
          if (JSON.stringify(this.formData.report.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;
        }

      });

    },

    // 数据处理数据
    getDataCleaning(val) {
      this.formData.dataCleaning.params = val
    },
    getPowerRationing(val) {
      this.formData.powerRationing.params = val
    },
    getModel(val) {
      this.formData.model.params = val
    },
    getModelTest(val) {
      this.formData.modelTest.params = val
    },
    getProcessing(val) {
      this.formData.processing.params = val
    },
    getReport(val) {
      this.formData.report.params = val
    },
    powerRationingNameChange() {
      if (!this.isEdit) {
        if (this.formData.powerRationing.componentType.includes('光伏')) {
          this.formData.powerRationing.params = {
            mongodb_database: '',
            mongodb_read_table: '',
            mongodb_write_table: '',
            col_power: '',
            col_radiance: '',
            sigma: 1
          }
        } else {
          this.formData.powerRationing.params = {
            mongodb_database: '',
            mongodb_read_table: '',
            mongodb_write_table: '',
            col_power: '',
            col_ws: '',
            cap: '',
            eps: 0.1,
            min_samples: '20'
          }
        }
      }
    },
    isDisableModeTest() {
      if (this.formData.model.componentType.includes('LSTM') || this.formData.model.componentType.includes('机器')) {
        this.modelTestDisable = false
        this.formData.modelTest.isEnable = true
        this.formData.modelTest.componentType = this.formData.model.componentType + '测试'
        return
      }
      this.modelTestDisable = true
      this.formData.modelTest.isEnable = false
    },
    handleClose() {
      this.$refs.ruleForm.resetFields()
      // this.formData = {
      //   tTaskName: '',
      //   tCronExpression: '',
      //   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:{}},
      // }
      this.dialogVisible = false
    },
    // 预览报告文件
    viewReport(row) {
      if(row.tanalysisReport !==null){
        window.open(row.tanalysisReport)
        // window.open('http://192.168.1.29:11111/J00001_1758852448094_3865.html')
      }else{
        this.$message({
          type: 'warning',
          message: '暂无报告文件'
        });
      }
    },
    // 运行信息
    viewInfo(row) {
      if(row.trunInfo !==null){
        this.info = row.tRunInfo
        this.dialogInfoVisible = true
      }else{
        this.info = null
        this.$message({
          type: 'warning',
          message: '暂无运行信息'
        });
      }
    },
    formatCreateTime(row){
      return formatDateTime(new Date(row.tcreateTime))
    },
    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;
  &:first-child{
    border-bottom: 1px solid #ebeef5;
  }
}
.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;
  }
}
.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;
}
</style>
