<!--  -->
<template>
  <div class=''>
    <el-breadcrumb class="divi2" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据质量探测</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider class="divi"></el-divider>

    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getMeasureOrJobList">
      <el-form-item>
        <el-button v-if="isAuth('snoop:save')" type="primary" @click="addHandle()">新建探测</el-button>
        <el-button v-if="isAuth('snoop:delete')" type="danger" @click="measureAndJobDelete()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.algorithmName" :placeholder="classificationtag=='度量'?'请输入度量名称':'请输入任务名称' " clearable
                  @keyup.enter.native="pageIndex = 1;getMeasureList()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="pageIndex = 1;getMeasureList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-tag>筛选:</el-tag>
        <el-select v-model="classificationtag" placeholder="类别" size="mini" style="width: 130px;"
                   @change="pageIndex = 1;getMeasureOrJobList()">
          <el-option v-for="data in classification" :key="data" :label="data" :value="data">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>


    <div v-if="classificationtag === '度量'" >
      <el-table key="度量" :data="measureList" border
                v-loading="measDataListLoading"
                @selection-change="SelectionChange"
                style="width: 100%;">
        <el-table-column type="selection" header-align="center" align="center" width="50">
        </el-table-column>
        <el-table-column prop="Id" header-align="center" align="center" width="80" label="序号"
                         type="index" :index='(index)=>{return (index+1) + (this.pageIndex-1)*this.pageSize}'>
        </el-table-column>
        <el-table-column prop="measureName" header-align="center" align="center" label="度量名称">
        </el-table-column>
        <el-table-column prop="measureType" header-align="center" align="center" label="度量类型"></el-table-column>
        <!--        <el-table-column prop="username" header-align="center" align="center" label="创建人">-->
        <!--        </el-table-column>-->
        <!--        <el-table-column prop="createTime" header-align="center" align="center" label="创建时间">-->
        <!--        </el-table-column>-->
        <el-table-column prop="remark" header-align="center" align="center" label="备注">
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small"  v-if="isAuth('snoop:measure:look')" @click="userwatch(scope.row)">查看</el-button>
            <el-button type="text" size="small"  v-if="isAuth('snoop:delete')"  @click="measureDeleteHandle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-if="classificationtag === '任务'">
      <el-table key="任务" :data="jobList" border
                v-loading="jobDataListLoading"
                @selection-change="SelectionChange"
                style="width: 100%;">
        <el-table-column type="selection" header-align="center" align="center" width="50">
        </el-table-column>
        <el-table-column prop="Id" header-align="center" align="center" width="80" label="序号"
                         type="index" :index='(index)=>{return (index+1) + (this.pageIndex-1)*this.pageSize}'>
        </el-table-column>
        <el-table-column prop="jobName" header-align="center" align="center" label="任务名称">
        </el-table-column>
        <el-table-column prop="jobState.previousFireTime" header-align="center" align="center" label="上次执行时间">
          <template slot-scope="scope">
            {{ scope.row.jobState.previousFireTime | timeFormater }}
          </template>
        </el-table-column>
        <el-table-column prop="jobState.nextFireTime" header-align="center" align="center" label="下次执行时间">
          <template slot-scope="scope">
            {{ scope.row.jobState.nextFireTime | timeFormater }}
          </template>
        </el-table-column>
        <el-table-column prop="state" header-align="center" align="center" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.jobState.state === 'NORMAL'" size="small">正常</el-tag>
            <el-tag v-else size="small" type="danger">暂停</el-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="username" header-align="center" align="center" label="创建人">-->
        <!--        </el-table-column>-->
        <!--        <el-table-column prop="createTime" header-align="center" align="center" label="创建时间">-->
        <!--        </el-table-column>-->

        <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
          <template slot-scope="scope">
            <el-button v-if="isAuth('snoop:job:look')" type="text" size="small" @click="jobWatch(scope.row)">查看
            </el-button>
            <el-button v-if="isAuth('snoop:job:delete')" type="text" size="small"
                       @click="jobDeleteHandle(scope.row)">删除
            </el-button>
            <el-button v-if="isAuth('snoop:job:pause')" type="text" size="small"
                       @click="jobPauseHandle(scope.row)" >
              暂停
            </el-button>
            <el-button v-if="isAuth('snoop:job:resume')" type="text" size="small"
                       @click="jobResumeHandle(scope.row)">恢复
            </el-button>
            <el-button v-if="isAuth('snoop:job:result')" type="text" size="small" @click="jobResHandle(scope.row)">结果
            </el-button>
            <el-button v-if="isAuth('sys:schedule:log')" type="text" size="small" @click="jobLogHandle(scope.row)">日志
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
                   :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <snoop v-if="addVisible" ref="addS" @refreshDataList="getMeasureList"></snoop>
    <measureUserWatch v-if="newWatchVisible" ref="measureWatch"></measureUserWatch>
    <job-watch v-if="jobWatchVisible" ref="jobWatch"></job-watch>
    <job-log v-if="jobLoghVisible" ref="jobLog"></job-log>
    <jobResultVisiEchars v-if="jobResVisible" ref="jobRes" ></jobResultVisiEchars>
  </div>
</template>

<script>
// import AlgAdd from './alg-add.vue';
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
// import AddOrUpdate from "./dataset-add-or-update";
// import Watch from "./dataset-watch";
import snoop from './snoop-add'
import measureUserWatch from './measureUserWatch'
import jobWatch from './jobWatch'
import jobLog from './jobLog'
// import jobResultVisi from './jobResult_visi'
import jobResultVisiEchars from './jobResult_visi_echars'
import { MessageBox } from 'element-ui'
import { Message } from 'element-ui'

export default {
  // import引入的组件需要注入到对象中才能使用
  data () {
    return {
      dataForm: {
        algorithmName: ''
      },
      userID: this.$store.state.user.id, // 用户编号
      // userName: this.$store.state.user.name, // 用户编号
      userName: 'test',
      measureList: [],    // 分页使用  当前显示的度量数据
      measureListAll: [],  // 分页使用  所用的度量数据
      jobList: [],   // 分页使用  当前显示的任务数据
      jobListAll: [],  // 分页使用  所用的任务数据
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      jobDataListLoading: false,
      measDataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      newWatchVisible: false,
      jobWatchVisible: false,
      addVisible: false,
      jobLoghVisible: false,
      jobResVisible: false,
      classificationtag: '',
      classification: ['度量', '任务']
    }
  },
  components: {
    // AlgAdd
    // AddOrUpdate,
    // Watch,
    // Add
    snoop,
    measureUserWatch,
    jobWatch,
    jobLog,
    jobResultVisiEchars
  },

  activated () {
    // this.getMeasureList()
    // this.getJobList()
    this.classificationtag = this.classification[0]
    var sign = this.$route.query.status
    if (sign) {
      this.classificationtag = this.classification[sign]
      this.getMeasureOrJobList()
    }
  },
  mounted () {
    this.getMeasureList()
  },
  filters: {
    timeFormater (value) {
      var date = new Date(value)
      let years = date.getFullYear()
      let month = (date.getMonth() + 1) > 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
      let day = (date.getDate() >= 10) ? date.getDate() : '0' + date.getDate()
      let hours = (date.getHours() >= 10) ? date.getHours() : '0' + date.getHours()
      let minutes = (date.getMinutes() >= 10) ? date.getMinutes() : '0' + date.getMinutes()
      let seconds = (date.getSeconds() >= 10) ? date.getSeconds() : '0' + date.getSeconds()
      if (value) {
        return years + '-' + month + '-' + day +
          ' ' + hours + ':' + minutes + ':' + seconds
      } else {
        return 'N/A'
      }
    }
  },
  methods: {
    getMeasureOrJobList () {
      if (this.classificationtag === '度量') {
        this.getMeasureList()
      } else {
        this.getJobList()
      }
    },
    // 获取数据列表
    getMeasureList () {
      this.measureListAll = []
      this.measureList = []
      this.measDataListLoading = true

      // this.measureList = [
      //   {'measureID': 1, 'measureName': 'demo1', 'measureType': 'profiling', 'remark': '测试'},
      //   {'measureID': 1, 'measureName': 'demo1', 'measureType': 'profiling', 'remark': '测试'}
      //
      // ]
      this.$http({
        url: this.$http.snoopUrl('/v1/measures/owner/') + this.userName,
        methods: 'get'
      }).then((datas) => {
        if (datas && datas.status === 200) {
          var res = datas.data.reverse()
          // console.log(res)
          res.map((info) => {
            var measure = {
              'measureID': info['id'],
              'measureName': info['name'],
              'measureType': info['dq.type'],
              'remark': info['description']
            }
            this.measureListAll.push(measure)
          })
        }
        this.unique(this.measureListAll)
        this.measureList = this.measureListAll.slice(0, this.pageSize)
        this.totalPage = this.measureListAll.length
        this.measDataListLoading = false
      })
    },
    toCamel (myString) {
      return myString.replace(/[.]([a-z])/g, function (g) {
        return g[1].toUpperCase()
      })
    },

    swapJson (json) {
      const ret = {}
      for (const key in json) {
        ret[this.toCamel(key)] = json[key]
      }
      return ret
    },
    getJobList () {
      this.jobListAll = []
      this.jobDataListLoading = true
      const self = this
      this.$http({
        url: this.$http.snoopUrl('/v1/jobs'),
        methods: 'get'
      }).then((datas) => {
        if (datas && datas.status === 200) {
          var data = datas.data
          const trans = Object.keys(data).map(function (index) {
            const job = self.swapJson(data[index])
            job.jobState.previousFireTime = job.jobState.previousFireTime < 0 ? '' : job.jobState.previousFireTime
            return job
          })
          this.jobListAll = Object.assign([], trans).reverse()
          this.jobList = this.jobListAll.slice(0, this.pageSize)
          this.totalPage = this.jobListAll.length
        }

        this.jobDataListLoading = false
      })
    },
    // 去重
    unique (arr) {
      var ss = []
      for (var i = 0; i < arr.length; i++) {
        ss[i] = arr[i].measureName
      }
      return Array.from(new Set(ss))
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      if (this.classificationtag === '任务') {
        let start = (this.pageIndex - 1) * this.pageSize
        this.jobList = this.jobListAll.slice(start, this.pageSize)
      } else {
        let start = (this.pageIndex - 1) * this.pageSize
        this.measureList = this.measureListAll.slice(start, this.pageSize)
      }
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      if (this.classificationtag === '任务') {
        let start = (this.pageIndex - 1) * this.pageSize
        let end = (this.pageIndex) * this.pageSize
        this.jobList = this.jobListAll.slice(start, end)
      } else {
        let start = (this.pageIndex - 1) * this.pageSize
        let end = (this.pageIndex) * this.pageSize
        this.measureList = this.measureListAll.slice(start, end)
      }
    },
    // **********************8多选
    SelectionChange (val) {
      this.dataListSelections = val
    },

    // 查看
    userwatch (info) {
      this.newWatchVisible = true
      this.$nextTick(() => {
        this.$refs.measureWatch.init(info)
      })
    },
    jobWatch (info) {
      this.jobWatchVisible = true
      this.$nextTick(() => {
        this.$refs.jobWatch.init(info)
      })
    },
    jobLogHandle (info) {
      this.jobLoghVisible = true
      this.$nextTick(() => {
        this.$refs.jobLog.init(info)
      })
    },
    jobResHandle (info) {
      this.jobResVisible = true
      this.$nextTick(() => {
        this.$refs.jobRes.init(info)
      })
    },

    // 这里处理新建
    addHandle () {
      this.addVisible = true
      this.$nextTick(() => {
        this.$refs.addS.init()
      })
    },
    jobResumeHandle (info) {
      MessageBox.confirm(
        `确定对[任务名=${info.jobName}]进行[恢复]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then((data) => {
        this.jobDataListLoading = true
        //  进行后台请求
        this.$http({
          url: this.$http.snoopUrl('/v1/jobs/') + info.id + '?action=start',
          method: 'put'
        }).then((data) => {
          if (data && data.status === 200) {
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getJobList()
              }
            })
          } else {
            this.$message.error(info.jobName + '恢复失败')
            this.getJobList()
          }
        })
      })
        .catch(() => {
        })
    },
    jobPauseHandle (info) {
      MessageBox.confirm(
        `确定对[任务名=${info.jobName}]进行[暂停]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then((data) => {
        this.jobDataListLoading = true
        //  进行后台请求
        this.$http({
          url: this.$http.snoopUrl('/v1/jobs/') + info.id + '?action=stop',
          method: 'put'
        }).then((data) => {
          if (data && data.status === 200) {
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getJobList()
              }
            })
          } else {
            this.$message.error(info.jobName + '恢复失败')
            this.getJobList()
          }
        })
      })
        .catch(() => {
        })
    },
    jobDeleteHandle (info) {
      MessageBox.confirm(
        `确定对[任务名=${info.jobName}]进行 [删除] 操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.jobDataListLoading = true
        //  进行后台请求
        this.$http({
          url: this.$http.snoopUrl('/v1/jobs/') + info.id,
          method: 'delete'
        }).then((data) => {
          // console.log(data)
          if (!data.data) {
            Message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getJobList()
              }
            })
          } else {
            MessageBox.error(info.jobName + '删除失败')
            this.getJobList()
          }
        })
      })
        .catch(() => {
        })
    },
    // ********** 删除
    measureDeleteHandle (info) {
      MessageBox.confirm(
        `确定对[${info.measureName}]进行[删除]操作? 删除后，对应job也会被删除`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.snoopUrl('/v1/measures/') + info.measureID,
            method: 'delete'
          }).then(({data}) => {
            this.measDataListLoading = true
            if (!data.data) {
              Message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              this.measDataListLoading = false
              this.getMeasureList()
              this.pageIndex = 1
            } else {
              Message.error(data.msg)
            }
          })
        })
        .catch(() => {
        })
    },
    async measureAndJobDelete () {
      var waitSecond = 1
      if (this.classificationtag === '度量') {
        var allMeasureName = []
        for (var index in this.dataListSelections) {
          allMeasureName.push(this.dataListSelections[index].measureName)
        }
        await MessageBox.confirm(
          `确定对[${allMeasureName}]进行[删除]操作? 删除后，对应job也会被删除`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.measDataListLoading = true
          let failure = []
          for (var index = 0; index < this.dataListSelections.length; index++) {
            waitSecond = waitSecond + 0.5
            this.$http({
              url: this.$http.snoopUrl('/v1/measures/') + this.dataListSelections[index].measureID,
              method: 'delete'
            }).then((data) => {
              if (data.data) {
                failure.push(this.dataListSelections[index])
              }
            })
          }

          if (failure.length === 0) {
            MessageBox({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
          } else {
            var msg = ''
            failure.forEach(x => {
              msg = msg + ' ' + x.measureName
            })
            MessageBox.error(msg)
          }
          setTimeout(() => {
            this.measDataListLoading = false
            this.getMeasureList()
          }, waitSecond * 1000)
        }).catch(() => {

        })
      } else {
        var allJobName = []
        for (var jobindex in this.dataListSelections) {
          allJobName.push(this.dataListSelections[jobindex].jobName)
        }
        await MessageBox.confirm(
          `确定对[${allJobName}]进行[删除]操作? `,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.jobDataListLoading = true
          let failure = []
          for (var index = 0; index < this.dataListSelections.length; index++) {
            waitSecond = waitSecond + 0.5
            this.$http({
              url: this.$http.snoopUrl('/v1/jobs/') + this.dataListSelections[index].id,
              method: 'delete'
            }).then((data) => {
              if (data.data) {
                failure.push(this.dataListSelections[index])
              }
            })
          }

          if (failure.length === 0) {
            MessageBox({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
          } else {
            var msg = ''
            failure.forEach(x => {
              msg = msg + ' ' + x.jobName
            })
            MessageBox.error(msg)
          }
          setTimeout(() => {
            this.jobDataListLoading = false
            this.getJobList()
          }, waitSecond * 1000)
        }).catch(() => {

        })
      }
    }
  }
}
</script>
<style scoped>
.divi {
  display: block;
  height: 1px;
  width: 100%;
  margin: 24px 0;
  background-color: #dcdfe6;
  position: relative;
}

.divi2 {
  display: block;
  height: 1px;
  width: 100%;
  position: relative;
}

.sele {
  border: 1px solid #409eff;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 5px 0px;
  margin: 10px;
}
</style>
