<template>
  <ui-load-more
    ref="loadMore"
    class="ui-timeline"
    :query-method="queryMethod"
    :page-size="pageSize"
    :merge-data-method="handleMergeDataMethod"
  >
    <template slot="data" slot-scope="scope">
      <slot :data="scope.data" />
    </template>
    <template slot="refreshing">
      <timeline-skeleton></timeline-skeleton>
    </template>
    <template slot="empty">
      <ui-empty />
    </template>
  </ui-load-more>
</template>
<script>
import UiEmpty from '@huntianning/components/packages/empty'
import UiLoadMore from '@huntianning/components/packages/load-more'
import TimelineSkeleton from './timeline-skeleton.vue'
import { formatDate, parseDate } from '@huntianning/components/src/utils/date'

export default {
  name: 'UiTimeline',
  components: {
    UiEmpty,
    UiLoadMore,
    TimelineSkeleton
  },
  props: {
    queryMethod: {
      type: Function,
      default: null
    },
    pageSize: {
      type: Number,
      default: 20
    },
    groupField: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      data: [],
      reloading: false,
      loading: false,
      groupMapData: {}
    }
  },
  computed: {
    weekCnText() {
      return {
        1: '星期一',
        2: '星期二',
        3: '星期三',
        4: '星期四',
        5: '星期五',
        6: '星期六',
        0: '星期天'
      }
    },
    groupListData() {
      return Object.keys(this.groupMapData).map(key => {
        const week = parseDate(key).getDay()
        return {
          id: key,
          label: key,
          week: this.weekCnText[week],
          children: this.groupMapData[key]
        }
      })
    }
  },
  methods: {
    handleMergeDataMethod({ newData, oldData }) {
      const groupData = this.serializeData(newData)
      return Object.keys(groupData).reduce((rs, k) => {
        const group = rs.find(v => v.id === k)
        if (group) {
          group.children = [].concat(group.children, groupData[k])
        } else {
          const week = parseDate(k).getDay()
          rs.push({
            id: k,
            label: k,
            week: this.weekCnText[week],
            children: groupData[k]
          })
        }
        return rs
      }, oldData)
    },
    serializeData(data) {
      return (data || []).reduce((rs, v) => {
        const groupDate = parseDate(v[this.groupField])
        const groupkey = formatDate(groupDate, 'YYYY-mm-dd')
        if (!rs[groupkey]) {
          this.$set(rs, groupkey, [])
        }
        rs[groupkey].push(v)
        return rs
      }, {})
    },
    reload() {
      return this.$refs.loadMore.reload()
    }
  }
}
</script>
<style lang="less">
.ui-timeline__empty{
  padding: 60px;
}
</style>
