<script>
import { mapGetters } from 'vuex'
import { getSchedule } from '@/api/calendar'
import ScheduleCalendar from './ScheduleCalendar'
import ScheduleSwiper from './ScheduleSwiper'

export default {
  name: 'Schedule',
  components: {
    ScheduleCalendar,
    ScheduleSwiper
  },
  props: {
    schedule: {
      type: String,
      required: true
    },
    editable: {
      type: [Boolean, String],
      default: false
    }
  },
  data () {
    return {
      options: null
    }
  },
  computed: {
    ...mapGetters(['isSuperAdmin', 'tenant', 'userId'])
  },
  watch: {
    schedule: {
      handler () {
        this.getSchedule()
      },
      immediate: true
    }
  },
  methods: {
    getSchedule () {
      const options = {
        loading: true,
        error: false,
        detail: null
      }
      this.options = options
      getSchedule(this.schedule).then(
        schedule => {
          options.detail = schedule
        },
        () => {
          options.error = true
        }
      ).finally(() => {
        options.loading = false
      })
    }
  },
  render (h) {
    if (this.options.loading) {
      return h('div', {
        directives: [
          {
            name: 'loading',
            value: true
          }
        ]
      })
    }

    if (this.options.error) {
      return h('Warning', {
        props: {
          error: true
        },
        on: {
          click: this.getSchedule
        }
      })
    }

    const { detail } = this.options

    if (!detail) {
      return h('el-result', {
        props: {
          icon: 'warning',
          subTitle: '数据不存在'
        }
      })
    }

    if (!this.isSuperAdmin && detail.tenant !== this.tenant) {
      return h('el-result', {
        props: {
          icon: 'warning',
          subTitle: '无权限'
        }
      })
    }

    return h([null, 'ScheduleSwiper', 'ScheduleCalendar'][detail.type - 1], {
      props: {
        detail,
        editable: this.editable && (this.isSuperAdmin || detail.createBy === this.userId),
        ...this.$attrs
      },
      on: this.$listeners
    })
  }
}
</script>
