<template>
  <div id="main">
    <div class="feed-container container-water-fall">
      <waterfall
        :col='col'
        :data="feedList"
        @loadmore="loadmore"
        @scroll="scroll"
      >
        <template>
          <div
            class="cell-item"
            v-for="(item,index) in feedList"
            :key="index"
          >
            <component
              :is="comp[item.type]"
              :data="item"
            ></component>
          </div>
        </template>
      </waterfall>
    </div>
  </div>
</template>

<script>
import CardGraphic from './comm/CardGraphic';
import CardVideo from './comm/CardVideo';
import CardAd from './comm/CardAd';

import PullToRefresh from "pulltorefreshjs";
import { baseUrl, detailUrl, profileUrl } from "./constant.js";
export default {
  components: {
    CardGraphic,
    CardAd,
    CardVideo,
  },
  props: ["data"],
  data() {
    return {
      col: 2,
      deferFnInterval: null,
      feedList: [],
      baseUrl: baseUrl,
      detailUrl: detailUrl,
      profileUrl: profileUrl,
      comp: {
        CardGraphic: CardGraphic,
        CardVideo: CardVideo,
        CardAd: CardAd
      },

      page: 1, // 底部加载页码
      pullPage: 1, // 下拉刷新页码
      pageSize: 10,
      orderBy: 1,
      offsetNum: 0,
      action: 1,
      isAjaxLoaded: true,
      isEnd: false,

      offsetNum: 0,
      initialTime: "",
      offsetTime: "",
      initialRank: 0,
      offsetRank: 0,
      offsetNumUp: 0,
      initialTimeUp: "",
      offsetTimeUp: "",
      initialRankUp: 0,
      offsetRankUp: 0
    };
  },
  mounted() {
    this.getData();
    const ptr = PullToRefresh.init({
      mainElement: ".feed-container",
      triggerElement: ".feed-container",
      instructionsPullToRefresh: "下拉刷新",
      instructionsReleaseToRefresh: "释放刷新",
      instructionsRefreshing: "加载中",
      onRefresh: cb => {
        this.action = 2;
        this.getData(cb);
      }
    });
  },
  beforeDestroy() {
    PullToRefresh.destroyAll();
  },
  methods: {
    getData(callback) {
      if (!this.isAjaxLoaded) return;
      this.isAjaxLoaded = false;
      this.$http
        .get(`${this.baseUrl}/api/feed/list`, {
          params: {
            page: this.action === 1 ? this.page : this.pullPage,
            page_size: this.pageSize,
            order_by: this.orderBy,
            offset_num: this.offsetNum,
            action: this.action,
            offset_num: this.action === 1 ? this.offsetNum : this.offsetNumUp,
            initial_time:
              this.action === 1 ? this.initialTime : this.initialTimeUp,
            offset_time:
              this.action === 1 ? this.offsetTime : this.offsetTimeUp,
            initial_rank:
              this.action === 1 ? this.initialRank : this.initialRankUp,
            offset_rank: this.action === 1 ? this.offsetRank : this.offsetRankUp
          }
        })
        .then(res => {
          this.isAjaxLoaded = true;
          callback && callback();
          if (res.data.code === 0) {
            // 数据加载成功
            let body = res.data.data || {},
              responseInfo = body.response_info || {},
              arr = body.feed_list || [],
              feedList = [];

            arr.forEach(item => {
              let objFeed = {},
                pageInfo = item.page_info || {},
                cards = pageInfo.cards || [],
                picBig = {};

              objFeed.type = this.getCardtype(item);
              // 是否为广告
              if (
                item.quick_ride_info &&
                item.quick_ride_info.object_type === 2
              ) {
                objFeed.isAd = true;
              }
              // 图文
              if (objFeed.type === "CardGraphic") {
                if (cards.length > 0) {
                  picBig = (cards[0].pic_info || {}).pic_big || {};
                  objFeed.arrImgUrls = [picBig.url || ""];
                } else {
                  let picInfos = item.pic_infos || {};
                  objFeed.arrImgUrls = Object.keys(picInfos).map(
                    (key, index) => {
                      if (index === 0) {
                        picBig = picInfos[key].large;
                      }
                      return (
                        picInfos[key] &&
                        picInfos[key]["large"] &&
                        picInfos[key]["large"]["url"]
                      );
                    }
                  );
                }
              }
              // 视频
              if (objFeed.type === "CardVideo") {
                picBig =
                  cards.length > 0
                    ? (cards[0].pic_info || {}).pic_big || {}
                    : (pageInfo.pic_info || {}).pic_big || {};
                objFeed.imgUrl = picBig.url || "";
                objFeed.videoUrl = item.page_info.media_info.mp4_hd_url;
              }
              // 广告
              if (objFeed.imgShow === "CardAd") {
                objFeed.imgUrl = item.ad_content;
                objFeed.adUrl = item.skip_url || "";
              }

              objFeed.profileDesc = item.text || "";
              objFeed.detailUrl = item.mid ? this.detailUrl + item.mid : "";
              objFeed.avatarUrl = (item.user && item.user.avatar_large) || "";
              objFeed.nickName = (item.user && item.user.name) || "";
              objFeed.profileUrl = item.user
                ? this.profileUrl + item.user.idstr
                : "";
              objFeed.uid = item.user ? item.user.idstr : "";
              objFeed.mid = item.mid;
              objFeed.isFollowed =
                item.quick_ride_info && item.quick_ride_info.friend_ships === 1
                  ? true
                  : false;

              // 橱窗
              if (item.common_struct && Object.keys(item.common_struct).length > 0) {
                objFeed.isWin = true;
                objFeed.winData = {
                  url: this.detailUrl + item.mid || "",
                  avatar: item.common_struct.img || "",
                  desc: item.common_struct.name || "",
                  price: item.common_struct.desc || ""
                }
              }

              if (
                // 过滤已经删除的card
                item.deleted != 1 &&
                (objFeed.imgUrl || (objFeed.arrImgUrls || []).length > 0) && // 图片url不存在
                picBig.height / picBig.width <= 3
              ) {
                feedList.push(objFeed);
              }

              // 存储后台数据
              if (responseInfo.action == 1) {
                this.offsetNum = responseInfo.offset_num;
                this.initialTime = responseInfo.initial_time;
                this.offsetTime = responseInfo.offset_time;
                this.initialRank = responseInfo.initial_rank;
                this.offsetRank = responseInfo.offset_rank;
              }
              if (responseInfo.action == 2 || this.page === 1) {
                // 第一次加载数据时， 存储后端数据
                this.offsetNumUp = responseInfo.offset_num;
                this.initialTimeUp = responseInfo.initial_time;
                this.offsetTimeUp = responseInfo.offset_time;
                this.initialRankUp = responseInfo.initial_rank;
                this.offsetRankUp = responseInfo.offset_rank;
              }
            });

            if (this.action === 1) {
              this.page++;
              this.feedList = this.feedList.concat(feedList);
            } else {
              this.pullPage++;
              this.feedList = feedList.concat(this.feedList);
            }
            return;
          }
          if (res.data.code == 50006) {
            this.isEnd = true;
          }
        })
        .catch(() => {
          this.isAjaxLoaded = true;
        });
    },

    /**
     * 获取card类型
     * @params {object}
     * @return {number} 0->视频 1->博文 2->广告
     * */
    getCardtype(obj) {
      let mediaInfo = (obj.page_info || {}).media_info || {};
      if (Object.keys(mediaInfo).length > 0) {
        return "CardVideo";
      }
      if (!obj.idstr || (obj.idstr && obj.idstr.length < 0)) {
        return "CardAd";
      }
      return "CardGraphic";
    },

    scroll(scrollData) {
      // console.log(scrollData);
    },

    loadmore(index) {
      this.action = 1;
      this.getData();
    }
  }
};
</script>

<style lang="scss">
#main {
  margin: 0;
  padding: 0;
  display: flex;
  min-height: 100vh;
  flex-direction: column;
  font: 15px / 1.15 Helvetica, Arial, sans-serif;
}
.feed-container {
  flex: 1;
  transition: transform 0.3s;
}
.container-water-fall {
  width: 100vw;
  box-sizing: border-box;
  background: #f8f8f8;
  .cell-item {
    overflow: hidden;
    margin: 0 3px;
    margin-bottom: 10px;
    background: #fff;
    border: 1px solid rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
}
</style>