<template>
  <confirm-dialog
    ref="dialog"
    append-to-body
    v-bind="$attrs"
    @confirm="onSave"
  >
    <div
      v-if="task"
      class="c-grid-form mini u-align-self--center"
    >
      <div class="c-grid-form__label">重复方式：</div>
      <div>
        <el-select v-model="task.freq">
          <el-option
            v-for="option in freqOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
      <template v-if="isWeekly">
        <div class="c-grid-form__label c-grid-form__auto required">每周：</div>
        <el-checkbox-group
          v-model="task.dayOfWeek"
          class="c-grid-form__auto l-flex--row"
          size="mini"
          fill="#1c5cb0"
        >
          <el-checkbox-button
            v-for="week in weeks"
            :key="week.value"
            :label="week.value"
          >
            {{ week.label }}
          </el-checkbox-button>
        </el-checkbox-group>
      </template>
      <div class="c-grid-form__label required">触发时间：</div>
      <el-time-picker
        v-model="task.executeTime"
        placeholder="请选择触发时间"
        value-format="HH:mm:ss"
      />
      <slot />
    </div>
  </confirm-dialog>
</template>

<script>
export default {
  name: 'TaskDialog',
  data () {
    return {
      task: null,
      freqOptions: [
        { value: 0, label: '每天' },
        { value: 1, label: '每周' }
      ],
      weeks: [
        { value: '1', label: '一' },
        { value: '2', label: '二' },
        { value: '3', label: '三' },
        { value: '4', label: '四' },
        { value: '5', label: '五' },
        { value: '6', label: '六' },
        { value: '7', label: '日' }
      ]
    }
  },
  computed: {
    isWeekly () {
      return this.task.freq === 1
    }
  },
  methods: {
    show ({ freq = 0, dayOfWeek, executeTime = '00:00:00' } = {}) {
      this.task = {
        freq,
        dayOfWeek: dayOfWeek ? dayOfWeek.split(',') : [],
        executeTime
      }
      this.$refs.dialog.show()
    },
    onSave (done) {
      const { freq, executeTime, dayOfWeek } = this.task
      const task = { freq, executeTime }
      if (this.isWeekly) {
        if (this.task.dayOfWeek.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择生效星期'
          })
          return
        }
        if (this.task.dayOfWeek.length === 7) {
          task.freq = 0
        } else {
          task.dayOfWeek = dayOfWeek.join(',')
        }
      }
      if (!executeTime) {
        this.$message({
          type: 'warning',
          message: '请选择触发时间'
        })
        return
      }
      this.$emit('confirm', {
        value: task,
        done
      })
    }
  }
}
</script>
