import routerUserMenu from '@/mixins/router-user-menu'
import breadcrumbComponent from '@/components/breadcrumb.vue'
import tableComponent from '@/components/table.vue'

/**
 * 页面组件设置
 *
 *  version = "1.0.0";
 *  author = "徐飞";
 *  email = "xu.fei@data-u.com";
 * */
export default {
  name: 'detail',
  components: {breadcrumbComponent, tableComponent},
  mixins: [routerUserMenu],
  data() {
    return {
      // 组件id（修改和查看）
      id: false,
      showDialog: false,
      // 新建对象
      taskForm: {
        periodType: '',
        scheduleOffset: '0',
        hourPeriod: '',
        dayPeriod: '',
        monthPeriod: '',
        selfPeriod: '',
        taskName: '',
        sourceDatabaseId: '',
        targetDatabaseId: '',
        targetTableId: '',
        sourceTableId: '',
        ddlSql: '',
      },
      tableId: '',
      cron: {
        second: '',
        minute: '',
        hour: '',
        day: '',
        month: ''
      },
      scriptForm: {
        columnList: [],
        ddlSql: ''
      },
      minutes: [],
      hours: [],
      days: [],
      taskCron: '',
      tableData: [],
      // 页面打开类型，0：新建，1：查看，2：修改
      dialogState: 0,
      periodOptions: [{
        id: 3,
        name: '小时'
      }, {
        id: 2,
        name: '日'
      }, {
        id: 1,
        name: '月'
      }, {
        id: 0,
        name: '自定义'
      }],
      databaseOptions: [],
      targetDatabaseOptions: [],
      sourceTableOptions: [],
      targetTableOptions: [],
      // 页面打开类型，false可编辑 true不可编辑
      readStatus: false,
      buttonDisabled: false,
    }
  },
  computed: {
    // 组件设置是否只读
    readonly: {
      // getter
      get: function () {
        return this.readStatus
      },
      // setter
      set: function (newValue) {
      }
    },
    // 判断源表是否禁止
    tableCheckSource: {
      // getter
      get: function () {
        return this.taskForm.sourceDatabaseId == ""
      },
      // setter
      set: function (newValue) {
      }
    },
    //判断目标表是否禁止
    tableCheckTarget: {
      // getter
      get: function () {
        return this.taskForm.targetDatabaseId == ""
      },
      // setter
      set: function (newValue) {
      }
    },
  },
  mounted() {
    // 初始化
    this.init()
  },
  methods: {
    //  如果有id，则获取id对应的部门信息赋值给formInfo
    init() {
      // 初始各种周期数下拉列表
      this.getDatabaseOptions()
      this.getTargetDatabaseOptions()
      for (let i = 1; i < 32; i++) {
        this.days.push(i)
      }
      // 获取url参数
      let params = this.$route.params
      if (params.hasOwnProperty('id')) {
        if (params.hasOwnProperty("readonly")) {
          this.readStatus = true
          this.id = params.id
          this.buttonDisabled = true
          this.getDetail()
        } else {
          // 如果有id，则加载组件对象
          this.id = params.id
          this.getDetail()
        }
      }
      // 根据页面参数设置当前页面类型
      this.dialogState = params.id ? 2 : 0
    },
    //数据抽取
    extract() {
      if (!this.taskForm.sourceTableId || this.taskForm.sourceTableId == '') {
        this.$message.error("请先选择源表")
        return
      }
      this.showDialog = true
      //关联ddl语句
      this.scriptForm.ddlSql = this.taskForm.ddlSql
      let param = {tableId: this.taskForm.sourceTableId}
      this.$api.task.listColumnByTableId(param)
        .then(res => {
          this.tableData = res.data
        })
    },
    // 获取源表下拉列表
    getSourceTableOptions() {
      let param = {databaseId: this.taskForm.sourceDatabaseId}
      this.$api.task.listTableByDatabaseId(param).then(res => {
        this.sourceTableOptions = res.data
      })
    },
    // 获取目标表下拉列表
    getTargetTableOptions() {
      let param = {databaseId: this.taskForm.targetDatabaseId}
      this.$api.task.listTableByDatabaseId(param).then(res => {
        this.targetTableOptions = res.data
      })
    },

    // 获取源数据库下拉列表
    getDatabaseOptions() {
      this.$api.task.listOriginal()
        .then(res => {
          this.databaseOptions = res.data
        })
    },
    //获取目标数据库下拉列表
    getTargetDatabaseOptions() {
      this.$api.task.listDatabase()
        .then(res => {
          this.targetDatabaseOptions = res.data
        })
    },
    // 拆解cron表达式
    cronSplit(periodType,taskCron){
      let cronList = taskCron.split(' ');
      // 拆解cron表达式
      switch (periodType) {
        case 0:
          this.cron.second = cronList[0] == '*' ? '' : cronList[0];
          this.cron.minute = cronList[1] == '*' ? '' : cronList[1];
          this.cron.hour = cronList[2] == '*' ? '' : cronList[2];
          this.cron.day = cronList[3] == '*' ? '' : cronList[3];
          this.cron.month = cronList[4] == '*' ? '' : cronList[4];
          break
        case 1:
          for (let i = 0; i < cronList.length - 2; i++) {
            if (cronList[i] != '*' && cronList[i] != '0') {
              this.taskForm.monthPeriod = cronList[i]
            }
          }
          break
        case 2:
          for (let i = 0; i < cronList.length - 2; i++) {
            if (cronList[i] != '*' && cronList[i] != '0') {
              if (cronList[i].length === 2) {
                this.taskForm.dayPeriod = cronList[i] + ':00'
              } else {
                this.taskForm.dayPeriod = '0' + cronList[i] + ':00'
              }
            }
          }
          break
        case 3:
          for (let i = 0; i < cronList.length - 2; i++) {
            if (cronList[i] != '*' && cronList[i] != '0') {
              if (cronList[i].length === 2) {
                this.taskForm.hourPeriod = '00:' + cronList[i]
              } else {
                this.taskForm.hourPeriod = '00:0' + cronList[i]
              }
            }
          }
          break
      }
    },

    // 获取回显详情信息
    getDetail() {
      let params = this.id
      let data = {}
      let _this = this
      _this.$api.task.toEdit(params)
        .then(res => {
          if (res.code == 1) {
            if (res.data) {
              data = res.data
              _this.taskForm.sourceDatabaseId = data.sourceDatabaseId
              _this.taskForm.targetDatabaseId = data.targetDatabaseId

              _this.taskForm.periodType = data.periodType
              _this.cronSplit(data.periodType,data.taskCron)
              _this.taskForm.taskName = data.taskName
              _this.taskForm.scheduleOffset = data.scheduleOffset
              _this.taskForm.ddlSql = data.ddlSql
              _this.$api.task.listTableByDatabaseId({databaseId: data.sourceDatabaseId})
                .then(res => {
                  if (res.code == 1) {
                    _this.sourceTableOptions = res.data
                    _this.taskForm.sourceTableId = data.sourceTableId
                    _this.$nextTick(() => {
                      _this.$refs.taskForm.clearValidate()
                    })
                  }
                })
              _this.$api.task.listTableByDatabaseId({databaseId: data.targetDatabaseId})
                .then(res => {
                  if (res.code == 1) {
                    _this.targetTableOptions = res.data
                    _this.taskForm.targetTableId = data.targetTableId
                    _this.$nextTick(() => {
                      _this.$refs.taskForm.clearValidate()
                    })
                  }
                })

              _this.$nextTick(() => {
                _this.$refs.taskForm.clearValidate()
              })
            }
          }
        })
    },

    //拼接cron表达式
    cronJoint() {
      let cronTemp = ''
      switch (this.taskForm.periodType) {
        case 0:
          console.log(this.cron);
          let cron = this.cron
          let cronList = [cron.second, cron.minute, cron.hour, cron.day, cron.month]
          if (cronList[4] == '') {
            cronTemp += '? * ';
          } else {
            cronTemp += '? ' + cronList[4] + ' ';
          }
          for (let i = 3; i >= 0; i--) {
            if (cronList[i] == '' && cronList[i + 1] == '') {
              cronTemp += '* '
            } else if (cronList[i] != '') {
              cronTemp += cronList[i] + ' '
            } else {
              cronTemp += '0 '
              cronList[i] = '0'
            }
          }
          cronTemp = cronTemp.substring(0, cronTemp.length - 1)
          cronTemp = cronTemp.split(" ").reverse().join(" ")
          console.log(cronTemp)
          break;
        case 1:
          cronTemp = '0 0 0 ' + this.taskForm.monthPeriod + ' * ?';
          break;
        case 2:
          let daycron = (this.taskForm.dayPeriod)[0] !== '0' ? this.taskForm.dayPeriod.substring(0, 2) : this.taskForm.dayPeriod.substring(1, 2)
          cronTemp = '0 0 ' + daycron + ' * * ?';
          break;
        case 3:
          let hourcron = (this.taskForm.hourPeriod)[3] !== '0' ? this.taskForm.hourPeriod.substring(3, 5) : this.taskForm.hourPeriod.substring(4, 5)
          cronTemp = '0 ' + hourcron + ' * * * ?';
          break;
      }
      this.taskCron = cronTemp
    },

    //判断对象属性是否全是空,不为空返回false
    checkNull(obj) {
      if (obj) {
        for (let o in obj) {
          if (!(obj[o] == '')) {
            return false
          }
        }
        return true
      }
    },
    //判断自定义周期类型是否符合规定
    checkSelfPeriod(obj) {
      if (obj) {
        let patten1 = /^\+?[1-9][0-9]*$/
        let patten2 = /^\d+([,]\d+)*$/
        for (let o in obj) {
          if (obj[o] != '') {
            if ((!patten1.test(obj[o])) && (!patten2.test(obj[o]))) {
              return false
            }
          }
        }
        if (!(this.cron.second<61&&this.cron.minute<61&&this.cron.hour<24&&this.cron.day<32&&this.cron.month<13)){
          return false
        }
        return true
      }
    },
    // 新增任务
    add() {
      if (this.taskForm.periodType == '0') {
        if (this.checkNull(this.cron)) {
          this.$message.error("自定义周期内容不能为空")
          return false
        }
        // if (!this.checkSelfPeriod(this.cron)) {
        //   this.$message.error("请输入正确格式的自定义周期内容")
        //   return false
        // }
      }

      this.cronJoint()
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = {
            taskName: this.taskForm.taskName,
            scheduleOffset: this.taskForm.scheduleOffset,
            periodType: this.taskForm.periodType,
            sourceDatabaseId: this.taskForm.sourceDatabaseId,
            sourceTableId: this.taskForm.sourceTableId,
            targetTableId: this.taskForm.targetTableId,
            targetDatabaseId: this.taskForm.targetDatabaseId,
            ddlSql: this.taskForm.ddlSql,
            taskCron: this.taskCron
          }
          _this.$api.task.add(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.goBack()
              }
            })
        } else {
          return false
        }
      })
    },

    // 更新
    update() {
      if (this.taskForm.periodType == '0') {
        if (this.checkNull(this.cron)) {
          this.$message.error("自定义周期内容不能为空")
          return false
        }
        // if (!this.checkSelfPeriod(this.cron)) {
        //   this.$message.error("请输入正确格式的自定义周期内容")
        //   return false
        // }
      }
      let _this = this
      _this.cronJoint()
      // 判断组件设置是否通过验证
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = {
            id: _this.id,
            taskName: this.taskForm.taskName,
            scheduleOffset: this.taskForm.scheduleOffset,
            periodType: this.taskForm.periodType,
            sourceDatabaseId: this.taskForm.sourceDatabaseId,
            sourceTableId: this.taskForm.sourceTableId,
            targetTableId: this.taskForm.targetTableId,
            targetDatabaseId: this.taskForm.targetDatabaseId,
            ddlSql: this.taskForm.ddlSql,
            taskCron: this.taskCron
          }
          _this.$api.task.update(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.goBack()
              }
            })
        } else {
          return false;
        }
      })
    },
    // table组件通用方法
    // 勾选table左侧复选框回调事件
    selectChange(obj) {
      let str = ''
      this.scriptForm.columnList = []
      for (let row of obj) {
        str += row.columnName + ','
        this.scriptForm.columnList.push(row.columnName)
      }
      str = str.substring(0, str.length - 1) + ' '
      let tableName = ''
      for (let o of this.sourceTableOptions) {
        if (o.id == this.taskForm.sourceTableId) {
          tableName = o.tableName
        }
      }
      this.scriptForm.ddlSql = 'SELECT ' + str + 'FROM ' + tableName
    },
    //对话框的确定按钮
    addDDL() {
      if (this.scriptForm.columnList.length == 0) {
        this.$message.error("请先选择字段！")
        return false
      }
      this.taskForm.ddlSql = this.scriptForm.ddlSql
      this.showDialog = false
    },
    //关闭对话框
    closeDialog() {
      this.showDialog = false
    }
  }
}
