<template>
  <list-view
    class="pdd-feed"
    :show-scrollbar="false"
    :lower-threshold="240"
    @scrolltolower="handleLoadMore"
  >
    <list-item v-for="(row, rowIndex) in rows" :key="'row-' + rowIndex" class="pdd-row-item">
      <view class="pdd-row">
        <view class="pdd-col">
          <PddWaterfallCard
            v-if="row.left != null"
            :product="row.left"
            @select="handleSelect"
          />
        </view>
        <view class="pdd-col">
          <PddWaterfallCard
            v-if="row.right != null"
            :product="row.right"
            @select="handleSelect"
          />
        </view>
      </view>
    </list-item>

    <list-item class="pdd-footer-item">
      <view class="pdd-footer">
        <text class="pdd-footer-text">{{ getFooterText() }}</text>
      </view>
    </list-item>
  </list-view>
</template>

<script lang="uts">
import PddWaterfallCard from './PddWaterfallCard.uvue'

type FeedRow = {
  left: any | null
  right: any | null
}

export default {
  components: {
    PddWaterfallCard
  },
  props: {
    items: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    noMore: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rows: [] as FeedRow[]
    }
  },
  created() {
    this.buildRows()
  },
  watch: {
    items: {
      handler() {
        this.buildRows()
      },
      deep: true
    }
  },
  methods: {
    buildRows() {
      const source = this.items as any[]
      const nextRows: FeedRow[] = []
      let index = 0
      while (index < source.length) {
        const left = source[index]
        const right = index + 1 < source.length ? source[index + 1] : null
        nextRows.push({
          left,
          right
        })
        index += 2
      }
      this.rows = nextRows
    },
    handleLoadMore() {
      this.$emit('loadMore')
    },
    getFooterText(): string {
      if (this.loading) return '\u6B63\u5728\u52A0\u8F7D\u66F4\u591A\u5546\u54C1...'
      if (this.noMore) return '\u5DF2\u7ECF\u5230\u5E95\u4E86'
      return '\u7EE7\u7EED\u4E0A\u6ED1\uFF0C\u53D1\u73B0\u66F4\u591A\u4F4E\u4EF7\u597D\u7269'
    },
    handleSelect(product: any) {
      this.$emit('select', product)
    }
  }
}
</script>

<style scoped>
.pdd-feed {
  flex: 1;
  background: #f5f5f5;
}

.pdd-row-item {
  padding-left: 12rpx;
  padding-right: 12rpx;
}

.pdd-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-top: 12rpx;
}

.pdd-col {
  width: 49.1%;
}

.pdd-footer-item {
  padding: 18rpx 0 26rpx;
}

.pdd-footer {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.pdd-footer-text {
  font-size: 22rpx;
  color: #9a9a9a;
}
</style>
