<template>
  <Article
    ref="article"
    type="niceGoods"
    :title="title"
    :thumbs="articleNiceThumbList"
    :on-fetch="onFetch"
    :no-header="noHeader"
    :pos-id="sceneId"
  >
  </Article>
</template>

<script>
import { get } from 'lodash';
import Article from './components/article/article';
import { createNamespacedHelpers, mapState } from 'vuex';
import YAS from 'utils/yas-constants';
const { mapState: articleMapState, mapActions } = createNamespacedHelpers(
  'article'
);

export default {
  name: 'ArticleNicePage',
  data() {
    return {
      title: '',
      sceneId: YAS.scene.list
    };
  },
  mounted() {
    // 自定义title
    const { title = '' } = this.$route.query || {};

    this.title = title || '发现好货';
  },
  async serverPrefetch() {
    return this.fetchFindNiceGoodsArticles({
      page: 1,
      limit: 3,
      thumb: true
    });
  },
  computed: {
    ...articleMapState(['articleNiceThumbList']),
    ...mapState(['yoho']),
    noHeader() {
      return this.yoho.context.env.isChat;
    }
  },
  methods: {
    ...mapActions(['fetchFindNiceGoodsArticles']),
    init() {
      this.page = 1;
      this.$refs.article.init();
    },
    async onFetch() {
      if (this.fetching) {
        return [];
      }

      this.fetching = true;
      this.page = this.page || 1;

      const result = await this.fetchFindNiceGoodsArticles({
        page: this.page
      });

      let list = [];

      let end = false;

      if (result.code === 200) {
        this.page++;

        if (get(result, 'data.detailList' || []).length) {
          list = result.data.detailList;
        }

        if (this.page > get(result, 'data.totalPage')) {
          end = true;
        }
      } else {
        this.$createToast &&
          this.$createToast({
            txt: result.message || '服务器开小差了',
            type: 'warn',
            time: 1000
          }).show();
      }
      this.fetching = false;

      return end ? false : list;
    }
  },
  components: {
    Article
  }
};
</script>

<style lang="scss" scoped>
.article-page {
  background-color: #f0f0f0;
}
</style>