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


  <el-col :span="16" style="height: 100%;margin-left: 160px;">
    <h4> 配置调度任务 :</h4>
    <div style="height: 360px;overflow-scrolling: auto">
      <el-form ref="jobForm" :model="jobcForm" label-width="120px" :rules="rules">
        <el-form-item label="任务名称 :" prop="name">
          <el-input v-model="jobcForm.name"></el-input>
        </el-form-item>
        <el-form-item label="度量名称 :" prop="measureID">
          <el-select v-model="jobcForm.measureID"   @change="onChange" placeholder="请选择"              >
            <el-option
              v-for="measure in measures"
              :key="measure.id"
              :label="measure.name"
              :value="measure.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调度周期 :" prop="cron">
          <el-input  v-model="jobcForm.cron" placeholder="请输入抽取周期"  clearable
                     @focus="dialogVisible = true">
          </el-input>
          <el-dialog custom-class="cron-box-dialog-first" :visible.sync="dialogVisible" v-if="dialogVisible">
            <mycron v-bind:extractionPeriod.sync="jobcForm.cron"></mycron>
          </el-dialog>
        </el-form-item>
        <el-form-item label="请选择时间范围 :" prop="range">
          <el-slider v-model="jobcForm.range" range show-stops :max="0" :min="-10" :marks="marks">
          </el-slider>
        </el-form-item>
        <el-form-item style="float:right ;margin-top: 20px">
          <el-button @click="visible = false;redirectHandle()">取消</el-button>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </el-form-item>
      </el-form>

    </div>
  </el-col>
</div>
</template>

<script>
import mycron from '../visi/quartz/mycron'
import { MessageBox } from 'element-ui'
import { Message } from "element-ui"
export default {
  components: {mycron},
  name: 'job',
  data () {
    // var checkExtractionPeriod = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('抽取周期不能为空'))
    //   } else {
    //     return callback()
    //   }
    // }
    return {
      jobcForm: {
        name: '',
        measureID: '',
        cron: '',
        range: [-1, 0],
        dropdownList: []
      },
      marks: {
        '-1': '-1 day',
        '-2': '-2 day',
        '-3': '-3 day',
        '-5': '-5 day',
        '-7': '-7 day',
        '-10': '-10 day'
      },
      dialogVisible: false,
      measures: [],
      rules: {
        name: [
          {required: true, message: '请输入任务名称', trigger: 'blur'},
          {min: 3, max: 18, message: '长度在 3 到 18 个字符', trigger: 'blur'}
        ],
        measureID: [
          { required: true, message: '请选择度量方案', trigger: 'change' }
        ],
        cron: [
          // { validator: checkExtractionPeriod, trigger: 'blur' }
          { required: true, message: '请输入调度周期', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    redirectHandle () {
      this.$router.replace({ path: '/snoop-home' })
    },

    // 向后台提交数据
    async finallySubmit () {
      this.newJob = {
        'job.name': this.jobcForm.name,
        'job.type': 'batch',
        'measure.id': this.jobcForm.measureID,
        'cron.expression': this.jobcForm.cron,
        // 'cron.time.zone': this.timezone,
        'cron.time.zone': 'GMT+8:00',
        // "predicate.config": {
        // "interval": "1m",
        // "repeat": 2
        // },
        'data.segments': [
          // {
          //   "data.connector.index": "source[0]",
          //   "segment.range": {
          //   "begin": "",
          //   "length": ""
          //   }
          // },
          // {
          //   "data.connector.index": "target[0]",
          //   "segment.range": {
          //   "begin": "",
          //   "length": ""
          //   }
          // }
        ]
      }
      for (let i = 0; i < this.dropdownList.length; i++) {
        var connector = this.dropdownList[i]
        var begin = this.jobcForm.range[0]
        var length = this.jobcForm.range[1] - this.jobcForm.range[0]
        var beginStr = this.getTimeByUnit(begin, connector.size)
        var lengthStr = this.getTimeByUnit(length, connector.size)
        this.newJob['data.segments'].push({
          'data.connector.name': connector.connectorname,
          'as.baseline': true,
          'segment.range': {
            begin: beginStr,
            length: lengthStr
          }
        })
      }
      if (this.dropdownList.length === 2) {
        delete this.newJob['data.segments'][1]['as.baseline']
      }
      console.log(this.newJob)
      await this.$http({
        url: this.$http.snoopUrl('/v1/jobs'),
        method: 'post',
        data: this.$http.adornData(this.newJob)
      }).then((datas) => {
        // console.log(6666)
        if (datas.status === 201) {
          return true
        } else {
          return false
        }
      })
        // .catch(err => {
        //   console.log(err)
        //   let response = JSON.parse(err.error)
        //   console.log(response)
        //   if (response.code === '40004') {
        //     console.log('error', 'Error!', 'Job name already exists!')
        //   } else {
        //     console.log('error', 'Error!', response.message)
        //   }
        // })
    },
    submitForm () {
      this.$refs['jobForm'].validate((valid) => {
        if (valid) {
          var submit = this.finallySubmit()

          setTimeout(() => {
            if (submit) {
              Message({
                message: '调度任务   ' + this.jobcForm.name + '   创建成功',
                type: 'success'
              })
            } else {
              Message({
                message: '调度任务   ' + this.jobcForm.name + '   创建失败',
                type: 'error'
              })
            }
            this.$router.replace({path: '/snoop-home', query: {'status': '1'}})
            this.$destroy()
          }, 2 * 1000)
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    getTimeByUnit (multiplier, unit) {
      var regex = /^(\d+)([a-zA-Z]+)$/g
      var arr = regex.exec(unit)
      if (arr.length > 2) {
        var n = parseInt(arr[1])
        var unitStr = arr[2]
        return ((n * multiplier).toString() + arr[2])
      } else {
        return multiplier.toString()
      }
    },
    onChange (measure) {
      this.dropdownList = []
      console.log(measure)
      for (let index in this.measures) {
        var map = this.measures[index]
        // console.log(measure)
        // console.log(map.id)
        if (measure === map.id) {
          var source = map['data.sources']
          for (let i = 0; i < source.length; i++) {
            var connector = source[i].connector
            if (connector['data.unit'] !== undefined) {
              var table = connector.config.database + '.' + connector.config['table.name']
              var size = connector['data.unit']
              var connectorname = connector['name']
              var detail = {
                id: i + 1,
                name: table,
                size: size,
                connectorname: connectorname
              }
              this.dropdownList.push(detail)
            }
          }
        }
      }
    }
  },
  mounted () {
    // console.log(this.$http.snoopUrl('/v1/measures/owner/') +  this.$store.state.user.name)  实际项目用这个
    this.$http({
      url: this.$http.snoopUrl('/v1/measures/owner/') + 'test',
      method: 'get'
    }).then((datas) => {
      if (datas && datas.status === 200) {
        var res = datas.data.reverse()
        res.forEach((info) => {
          if (info['process.type'] === 'BATCH') {
            this.measures.push(info)
          }
        })
      }
    })
    // for (var i = 0; i < 10; i++) {
    //   obj = { 'id': i, 'name': 'demo' + i}
    //   this.measures.push(obj)
    // }
  }
}
</script>

<style scoped>
.divi2 {
  display: block;
  height: 1px;
  width: 100%;
  position: relative;
}
</style>
