<template>
  <confirm-dialog
    ref="dialog"
    append-to-body
    v-bind="$attrs"
    @confirm="onSave"
  >
    <template #default>
      <slot />
      <div
        v-for="(task, index) in tasks"
        :key="index"
        class="c-sibling-item--v c-grid-form u-align-self--center"
      >
        <div class="l-flex--row c-grid-form__row c-grid-form__option u-font-size--sm u-color--black u-bold">
          <div class="c-sibling-item">
            区间段 {{ index + 1 }}
          </div>
          <i
            v-if="multi && tasks.length > 1"
            class="c-sibling-item el-icon-delete has-active"
            @click="onRemoveBlock(index)"
          />
        </div>
        <div class="c-grid-form__label">
          生效日期
        </div>
        <el-date-picker
          v-model="task.date"
          class="u-width--lg"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          :clearable="false"
        />
        <div class="c-grid-form__label c-grid-form__auto">
          每周
        </div>
        <el-checkbox-group
          v-model="task.dayOfWeek"
          class="l-flex--row c-grid-form__auto"
          size="mini"
          fill="#1c5cb0"
          :min="1"
        >
          <el-checkbox-button
            v-for="week in weeks"
            :key="week.value"
            :label="week.value"
          >
            {{ week.label }}
          </el-checkbox-button>
        </el-checkbox-group>
        <div class="c-grid-form__label">
          执行时间
        </div>
        <div style="display: flex; flex-wrap: wrap; gap: 6px;">
          <div
            v-for="(item, tindex) in task.executeTime"
            :key="tindex"
            class="l-flex--row inline"
          >
            <template v-if="strictly">
              <el-time-picker
                v-model="item.time"
                class="c-sibling-item u-width--lg"
                is-range
                range-separator="-"
                :start-placeholder="startPlaceholder"
                :end-placeholder="endPlaceholder"
                value-format="HH:mm:00"
                format="HH:mm"
                placeholder="选择时间范围"
                clearable
              />
            </template>
            <template v-else>
              <el-time-picker
                v-model="item.start"
                class="u-width--xs"
                :placeholder="startPlaceholder"
                value-format="HH:mm:00"
                format="HH:mm"
                clearable
                @change="onTimeChanged(item)"
              />
              <span class="has-padding--h">
                -
              </span>
              <el-time-picker
                v-model="item.end"
                class="c-sibling-item u-width--xs"
                :placeholder="endPlaceholder"
                value-format="HH:mm:00"
                format="HH:mm"
                clearable
                @change="onTimeChanged(item)"
              />
            </template>
            <el-tooltip
              v-if="item.warning"
              placement="top"
              effect="dark"
              :content="item.warning"
            >
              <i class="c-sibling-item el-icon-warning u-color--error dark u-font-size--md" />
            </el-tooltip>
            <i
              v-if="task.executeTime.length > 1"
              class="c-sibling-item el-icon-delete u-font-size--md has-active"
              @click="onRemoveTime(index, tindex)"
            />
          </div>
          <i
            class="c-grid-form__option l-flex--row el-icon-circle-plus-outline u-font-size--md has-active"
            style="margin-left: 6px;"
            @click="onAddTime(index)"
          />
        </div>
      </div>
      <div
        v-if="multi"
        class="c-sibling-item--v c-grid-form u-align-self--center"
      >
        <div class="l-flex--row c-grid-form__row">
          <div
            class="o-button"
            @click="onAddBlock"
          >
            <i class="o-button__icon el-icon-circle-plus-outline" />
            新增区间段
          </div>
        </div>
      </div>
    </template>
  </confirm-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  FOREVER,
  ONE_DAY
} from '@/constant.js'
import {
  parseTime,
  getCronWeekOptions
} from '@/utils'
import { toDate } from '@/utils/event.js'

export default {
  name: 'TaskDialog',
  props: {
    multi: {
      type: Boolean,
      default: true
    },
    startPlaceholder: {
      type: String,
      default: '开启时间'
    },
    endPlaceholder: {
      type: String,
      default: '关闭时间'
    },
    strictly: {
      type: [Boolean, String],
      default: false
    }
  },
  data () {
    return {
      weeks: getCronWeekOptions(),
      pickerOptions: {
        disabledDate: this.isDisableDate,
        shortcuts: [
          {
            text: '本月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              end.setDate(1)
              end.setMonth(end.getMonth() + 1)
              end.setDate(0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '今年',
            onClick (picker) {
              const start = new Date().getFullYear()
              const startYear = new Date()
              const endYear = new Date(start, 11, 31)
              picker.$emit('pick', [startYear, endYear])
            }
          },
          {
            text: '永久生效',
            onClick (picker) {
              const start = new Date()
              const end = new Date(FOREVER)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      tasks: []
    }
  },
  computed: {
    ...mapGetters(['account'])
  },
  methods: {
    isDisableDate (date) {
      return date <= Date.now() - ONE_DAY
    },
    isExpired (endDate) {
      return endDate !== FOREVER && toDate(`${endDate} 00:00:00`) <= Date.now() - ONE_DAY
    },
    show ({ startDate, endDate, dayOfWeek, executeTime } = {}) {
      const today = parseTime(new Date(), '{y}-{m}-{d}')
      this.tasks = [{
        date: startDate && endDate ? [startDate, endDate] : [today, today],
        dayOfWeek: dayOfWeek && dayOfWeek !== '?' ? dayOfWeek.split(',') : this.weeks.map(({ value }) => value),
        executeTime: executeTime
          ? executeTime.map(this.createTime)
          : [this.createTime()],
        flag: Date.now()
      }]
      this.$refs.dialog.show()
    },
    createTime (data) {
      const start = data?.start?.replace(/\d{2}$/, '00') || ''
      const end = data?.end?.replace(/\d{2}$/, '00') || ''
      return this.strictly
        ? { time: start && end ? [start, end] : null, warning: '' }
        : { start, end, warning: '' }
    },
    onAddBlock () {
      const today = parseTime(new Date(), '{y}-{m}-{d}')
      this.tasks.push({
        flag: Date.now(),
        date: [today, today],
        dayOfWeek: this.weeks.map(({ value }) => value),
        executeTime: [this.createTime()]
      })
    },
    onRemoveBlock (index) {
      this.tasks.splice(index, 1)
    },
    onAddTime (index) {
      this.tasks[index].executeTime.push(this.createTime())
    },
    onRemoveTime (index, tindex) {
      this.tasks[index].executeTime.splice(tindex, 1)
    },
    onTimeChanged (executeTime) {
      const { start, end } = executeTime
      if (start && end && start >= end) {
        executeTime.warning = '开启时间必须先于关闭时间'
      } else {
        executeTime.warning = ''
      }
    },
    hasTime (data) {
      return this.strictly
        ? !!data.time
        : !!data.start || !!data.end
    },
    transformTime (data) {
      return this.strictly
        ? `${data.time[0]}_${data.time[1]}`
        : `${data.start || ''}_${data.end || ''}`
    },
    onSave (done) {
      if (this.tasks.some(({ executeTime }) => executeTime.some(({ warning }) => !!warning))) {
        this.$message({
          type: 'warning',
          message: '请先完成异常数据的修改'
        })
        return
      }
      const tasks = this.tasks.filter(({ date, executeTime }) => !this.isExpired(date[1]) && executeTime.some(this.hasTime))
      if (!tasks.length) {
        this.$message({
          type: 'warning',
          message: '请至少添加一个有效执行时间'
        })
        return
      }
      this.$emit('confirm', {
        value: tasks.sort((a, b) => b.flag - a.flag).map(({ flag, date, dayOfWeek, executeTime }) => {
          return {
            flag: `${this.account}_${flag}`,
            startDate: date[0],
            endDate: date[1],
            dayOfWeek: dayOfWeek.length === 7 ? '?' : dayOfWeek.sort().join(','),
            executeTime: [...new Set(executeTime.filter(this.hasTime).map(this.transformTime))].sort().map(time => {
              const timeArr = time.split('_')
              return {
                start: timeArr[0] || '',
                end: timeArr[1] || ''
              }
            })
          }
        }),
        done
      })
    }
  }
}
</script>
