<template>
  <div>
    <form-list class="mt-5 mb-5" ref="form" :items="option" @change="handleChange">
      <template v-slot:triggerDay="{item}">
        <v-btn class="ml-2 half-button" rounded color="primary" @click="addAll(item)">全选</v-btn>
      </template>
      <template v-slot:triggerWeek="{item}">
        <v-btn class="ml-2 half-button" rounded color="primary" @click="addAll(item)">全选</v-btn>
      </template>
      <template v-slot:triggerMonth="{item}">
        <v-btn class="ml-2 half-button" rounded color="primary" @click="addAll(item)">全选</v-btn>
      </template>
    </form-list>
    <edit-dialog title="表达式选择" :visible.sync="cronShow" @submit="cronSubmit">
    </edit-dialog>
  </div>
</template>

<script>
import EditDialog from '@/components/Dialog'
import FormList from '@/components/Form/list.vue'
import { setLocalStorageAndTime, getLocalStorageAndTime } from '@/utils/localStorageAndTime'
import { dataFactoryDictList } from '@/api/dataFactory'
import { getNow, currentHMS } from '@/utils/date'
export default {
  name: 'data-dispatch',
  components: { FormList, EditDialog },
  props: {
    updater: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      // updateMethod: true,
      cronShow: false,
      dictionary: {},
      option: {
        options: [
          {
            type: 'autocomplete',
            key: 'frequency',
            value: '2',
            default: '2',
            label: '请选择执行频率 *',
            outlined: true,
            dense: true,
            rules: [v => v !== null || '请选择执行频率'],
            items: [],
            change: this.frequencyChange
          },
          {
            type: 'autocomplete',
            key: 'triggerMonth',
            slotName: 'triggerMonth',
            isShow: [2],
            multiple: true,
            value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
            default: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
            hide: false,
            label: '请选择月份 *',
            outlined: true,
            clearable: true,
            dense: true,
            rules: [v => v !== null || '请选择月份'],
            items: []
          },
          {
            type: 'autocomplete',
            key: 'triggerType',
            col: '3',
            isShow: [2],
            value: '1',
            default: '1',
            hide: false,
            label: '请选择触发类型 *',
            outlined: true,
            dense: true,
            rules: [v => v !== null || '请选择触发类型'],
            items: [],
            change: this.triggerTypeChange
          },
          {
            type: 'autocomplete',
            key: 'triggerDay',
            col: '9',
            isTriggerType: '1',
            isShow: [2],
            multiple: true,
            value: [1],
            default: [1],
            clearable: true,
            hide: false,
            slotName: 'triggerDay',
            label: '请选择触发日 *',
            outlined: true,
            dense: true,
            rules: [v => v !== null || '请选择触发日'],
            items: []
          },
          {
            type: 'autocomplete',
            key: 'triggerWeek',
            slotName: 'triggerWeek',
            col: '9',
            isTriggerType: '2',
            isShow: [2],
            multiple: true,
            value: null,
            default: null,
            hide: true,
            clearable: true,
            label: '请选择触发周 *',
            outlined: true,
            dense: true,
            rules: [v => v !== null || '请选择触发周'],
            items: [
              { value: 1, label: '星期一' },
              { value: 2, label: '星期二' },
              { value: 3, label: '星期三' },
              { value: 4, label: '星期四' },
              { value: 5, label: '星期五' },
              { value: 6, label: '星期六' },
              { value: 7, label: '星期日' }
            ]
          },
          {
            type: 'text',
            key: 'cron',
            isShow: [3],
            hide: true,
            value: null,
            default: null,
            label: '请输入表达式 *',
            // readonly: true,
            outlined: true,
            dense: true,
            rules: [v => v !== null || '请输入表达式'],
            click: this.cronHandleClick
          },
          {
            type: 'date',
            key: 'startTime',
            isShow: [1, 2, 3],
            value: `${getNow()[0]}-${getNow()[1]}-${getNow()[2]}`,
            default: null,
            label: '开始时间',
            hide: false,
            option: {
              type: 'date',
              validate: false,
              placeholder: '请选择开始时间 *',
              attach: false
            }
          },
          {
            type: 'date',
            key: 'endTime',
            isShow: [2, 3],
            value: `${+getNow()[0] + 50}-${getNow()[1]}-${getNow()[2]}`,
            default: null,
            label: '结束时间',
            hide: false,
            option: {
              type: 'date',
              validate: false,
              placeholder: '请选择结束时间 *',
              attach: false
            }
          },
          {
            type: 'date',
            key: 'triggerTime',
            isShow: [1, 2],
            value: currentHMS(30),
            default: null,
            label: '触发时间',
            hide: false,
            option: {
              type: 'time',
              validate: false,
              placeholder: '请选择触发时间 *',
              attach: false
            }
          }
        ]
      }
    }
  },
  created () {
    if (this.updater) {
      this.option.options.forEach(e => {
        e.value = this.updater[e.key] ?? null
        if (e.change) {
          e.change(e.value)
        }
      })
    }

    this.overData()
  },
  methods: {
    async overData () {
      await this.initDictionary('frequency_type')
      this.option.options.find(e => e.key === 'frequency').items = this.dictionary.frequency_type
      await this.initDictionary('trigger_type')
      this.option.options.find(e => e.key === 'triggerType').items = this.dictionary.trigger_type
      // if (this.updateMethod) {
      //   await this.initDictionary('updateMethod_type')
      //   this.option.options.find(e => e.key === 'updateMethod').items = this.dictionary.updateMethod_type
      // }
      for (let i = 0; i < 31; i++) {
        if (i < 12) {
          this.option.options.find(e => e.key === 'triggerMonth').items.push({ value: i + 1, label: `${i + 1}月` })
        }
        this.option.options.find(e => e.key === 'triggerDay').items.push({ value: i + 1, label: `${i + 1}号` })
      }
    },
    addAll (item) {
      const obj = this.option.options.find(e => e.key === item.key)
      obj.value = obj.items.map(e => e.value)
      this.handleChange()
    },
    cronHandleClick () {
      // 表达式执行
      this.cronShow = true
      // console.log('表达式执行')
    },
    cronSubmit () {},
    async frequencyChange (val) {
      this.option.options.forEach(item => {
        if (!item.isShow) return
        // console.log(item.key, item.isShow.includes(+val))
        item.hide = !item.isShow.includes(+val)
      })
      // 重复执行
      if (val === '2') {
        this.triggerTypeChange(this.option.options.find(e => e.key === 'triggerType').value)
      }
    },
    // 触发类型
    triggerTypeChange (val) {
      const opt = this.option.options.find(e => e.key === 'triggerType')
      if (opt.hide) return
      this.option.options.forEach(item => {
        if (!item.isTriggerType) return
        if (item.isTriggerType === val) item.hide = false
        else {
          item.hide = true
          item.value = null
        }
      })
    },
    // updateMethodChange (val) {
    //   this.option.options.find(e => e.key === 'mateCondition').hide = (val !== '3')
    //   if (val === '3') this.initSourceData()
    // },
    handleChange () {
      const obj = this.getValue()
      this.$emit('change', obj)
    },
    async initDictionary (type) {
      const dictionary = getLocalStorageAndTime('dataFactory', type)
      if (dictionary) {
        this.dictionary[type] = dictionary
        return
      }
      try {
        const { data } = await dataFactoryDictList({ type })
        if (!data || !data.length) return
        this.dictionary[type] = data[0].itemList
        setLocalStorageAndTime('dataFactory', type, data[0].itemList)
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    validate () {
      return this.$refs.form.$refs.form.validate() && this.$refs.form.validateTime()
    },
    getValue () {
      const obj = this.option.options.reduce((res, item) => {
        if (!item.hide) res[item.key] = item.value
        return res
      }, {})
      // 组合时间数据
      if (obj.endTime) obj.endTime = obj.endTime.split(' ')[0] + ' 00:00:00'
      if (obj.startTime && obj.triggerTime) obj.startTime = obj.startTime.split(' ')[0] + ' ' + obj.triggerTime
      if (obj.startTime && !obj.triggerTime) obj.startTime = obj.startTime.split(' ')[0] + ' 00:00:00'
      return {
        updater: obj
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
