<template>
    <view class="pages">
        <view class="placeholder-bar">
            <statusBar></statusBar>
            <view :style="{ height: `${navBarHeight}px` }"></view>
        </view>

        <view class="nav-box">
            <!-- #ifndef H5 -->
            <statusBar></statusBar>
            <!-- #endif -->
            <view class="nav" :style="{ height: `${navBarHeight}px` }">
                <!-- #ifdef MP -->
                <view class="mp-button-left-placeholder" :style="{ width: `${mpButtonLeftPlaceholderSize}px` }"></view>
                <!-- #endif -->
                <!-- 搜索功能 -->
                <view class="uni-search-box">
                    <uni-search-bar ref="searchBar" radius="100" cancelButton="none" disabled
                                    :placeholder="inputPlaceholder"/>
                    <view class="cover-search-bar" @click="searchClick"></view>
                </view>
                <!-- #ifdef MP -->
                <view class="mp-button-placeholder" :style="{ width: `${mpButtonPlaceholderSize}px` }"></view>
                <!-- #endif -->
            </view>
        </view>

        <unicloud-db ref='udb' v-slot:default="{ pagination, hasMore, loading, error, options }" @error="onqueryerror"
                     :collection="colList" :page-size="10" orderby="publish_date desc" @load="listLoad">
            <!-- 基于 uni-list 的页面布局 field="user_id.nickname"-->
            <!-- #ifdef APP-NVUE -->
            <list class="uni-list" :border="false" :style="{ height: listHeight }">
                <!-- #endif -->
                <!-- #ifndef APP-NVUE -->
                <scroll-view
                        scroll-y
                        class="uni-list"
                        refresher-enabled
                        :refresher-triggered="loadType=== 'refresh'"
                        :style="{ height: listHeight }"
                        @refresherrefresh="refresh"
                        @scrolltolower="loadMore"
                >
                    <!-- #endif -->
                    <!-- #ifdef APP-NVUE -->
                    <refresh-box :loading="loading" @refresh="refresh"></refresh-box>
                    <!-- #endif -->

                    <!-- 列表渲染 -->
                    <template v-for="item in listData">
                        <not-cover v-if="item.thumbnail && item.thumbnail.length === 0" :data="item"></not-cover>
                        <right-small-cover v-else-if="item.thumbnail && item.thumbnail.length === 1"
                                           :data="item"></right-small-cover>
                        <three-cover v-else-if="item.thumbnail && item.thumbnail.length === 3"
                                     :data="item"></three-cover>
                    </template>

                    <!-- 加载状态：上拉加载更多，加载中，没有更多数据了，加载错误 -->
                    <!-- #ifdef APP-PLUS -->
                    <uni-list-item>
                        <template v-slot:body>
                            <!-- #endif -->
                            <uni-load-state @networkResume="refresh"
                                            :state="{ data: listData, pagination, hasMore, loading, error }"
                                            @loadMore="loadMore">
                            </uni-load-state>
                            <!-- #ifdef APP-PLUS -->
                        </template>
                    </uni-list-item>
                    <!-- #endif -->
                    <!-- #ifndef APP-NVUE -->
                </scroll-view>
                <!-- #endif -->
                <!-- #ifdef APP-NVUE -->
            </list>
            <!-- #endif -->
        </unicloud-db>
    </view>
</template>

<script>
  import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
  import translatePublishTime from "@/uni_modules/uni-cms-article/common/publish-time";
  import refreshBox from "@/uni_modules/uni-cms-article/components/refresh-box/refreshBox.nvue";

  import notCover from "@/uni_modules/uni-cms-article/components/list-template/not-cover.vue";
  import rightSmallCover from "@/uni_modules/uni-cms-article/components/list-template/right-small-cover.vue";
  import threeCover from "@/uni_modules/uni-cms-article/components/list-template/three-cover.vue";
  import {parseImageUrl} from "@/uni_modules/uni-cms-article/common/parse-image-url";

  const db = uniCloud.database();
  const articleDBName = 'uni-cms-articles'
  const userDBName = 'uni-id-users'

  export default {
    components: {
      statusBar,
      refreshBox,
      notCover,
      rightSmallCover,
      threeCover
    },
    computed: {
      // 根据当前语言返回不同的搜索框占位符
      inputPlaceholder(e) {
        if (uni.getStorageSync('CURRENT_LANG') == "en") {
          return 'Please enter the search content' // 英文
        } else {
          return '请输入搜索内容' // 中文
        }
      },
      // 连表查询，返回两个集合的查询结果
      colList() {
        return [
          db.collection(articleDBName).where(this.where).field('thumbnail,title,publish_date,user_id').getTemp(), // 文章集合
          db.collection(userDBName).field('_id,nickname').getTemp() // 用户集合
        ]
      }
    },
    data() {
      return {
        where: '"article_status" == 1', // 查询条件
        showRefresh: false, // 是否显示刷新按钮
        listHeight: 0, // 列表高度
        mpButtonLeftPlaceholderSize: 0, // 小程序左侧icon占位大小
        mpButtonPlaceholderSize: 87, // 小程序导航栏按钮占位大小
        navBarHeight: 44, // 导航栏高度
        refreshStatus: 0, // 刷新状态 0: 未刷新 1: 刷新中 2: 刷新完成
        listData: [], // 列表数据
        loadType: null
      }
    },
    async onReady() {
      // #ifdef MP
      this.initNavBarSize() // 初始化导航栏大小
      // #endif
      /* 可用窗口高度 - 搜索框高 - 状态栏高 */
      this.listHeight = uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight - this.navBarHeight + 'px'; // 计算列表高度
    },
    methods: {
      async listLoad(data) {
        const listData = data.map(item => {
          if (typeof item.thumbnail === 'string') {
            item.thumbnail = [item.thumbnail]
          }

          return item
        })

        // 处理腾讯云文件链接
        for (const article of listData) {
          const parseImages = await parseImageUrl(article.thumbnail)

          article.thumbnail = parseImages ? parseImages.map(image => image.src): []
        }

        this.listData = this.loadType === 'loadMore' ? this.listData.concat(listData) : listData
        this.loadType = null
      },
      // 初始化导航栏大小
      initNavBarSize() {
        // 获取小程序导航栏按钮信息
        // #ifdef MP-TOUTIAO
        let menuButtonInfo = tt.getCustomButtonBoundingClientRect()
        menuButtonInfo.width = menuButtonInfo.capsule.width //  小程序按钮区域中使用的按钮宽度
        this.mpButtonLeftPlaceholderSize = menuButtonInfo.leftIcon.width + 10
        // #endif
        // #ifndef MP-TOUTIAO
        let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
        // #endif
        // 计算小程序导航栏按钮占位大小
        this.mpButtonPlaceholderSize = menuButtonInfo.width + 10
        // 获取系统信息，判断是否为 iOS 系统，设置导航栏高度
        this.navBarHeight = uni.getSystemInfoSync().system.toLowerCase().includes('ios') ? 44 : 48
      },
      // 格式化时间戳
      publishTime(timestamp) {
        return translatePublishTime(timestamp)
      },
      // 点击搜索框
      searchClick(e) {
        uni.hideKeyboard();
        uni.navigateTo({
          url: '/uni_modules/uni-cms-article/pages/search/search'
        });
      },
      // 重试
      retry() {
        this.refresh()
      },
      // 刷新
      refresh() {
        this.loadType = 'refresh'
        this.$refs.udb.loadData({
          clear: true
        }, () => {
          uni.stopPullDownRefresh()
          // #ifdef APP-NVUE
          this.showRefresh = false
          // #endif
        })
      },
      // 加载更多
      loadMore() {
        this.loadType = 'loadMore'
        this.$refs.udb.loadMore()
      },
      // 查询出错
      onqueryerror(e) {
        console.error(e);
      }
    },
    // #ifdef H5
    // 下拉刷新
    onPullDownRefresh() {
      this.refresh()
    },
    // #endif
  }
</script>

<style scoped>
    /* #ifndef APP-NVUE */
    .pages view {
        display: flex;
        box-sizing: border-box;
        flex-direction: column;
    }
    /* #endif */

    .pages {
        background-color: #FFFFFF;
    }

    .refresh {
        text-align: center;
    }

    .nav-box {
        background-color: #FFFFFF;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;

        /* #ifndef APP-PLUS */
        z-index: 9;
        /* #endif */
    }

    .pages .nav {
        display: flex;
        align-items: center;
        flex-direction: row;
    }

    .uni-search-box {
        flex: 1;
        padding: 0 10px;
    }

    .uni-search-box ::v-deep .uni-searchbar {
        padding: 0;
    }

    .uni-search-box ::v-deep .uni-searchbar__box {
        height: 32px;
        flex-direction: row;
    }

    .cover-search-bar {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        top: 0;
        /* #ifndef APP-NVUE */
        z-index: 999;
        /* #endif */
    }

    .pages .uni-list ::v-deep .uni-list-item__container {
        flex-direction: row;
        width: 100%;
    }

    .pages .uni-list ::v-deep .uni-list-item {
        align-items: flex-start;
    }

    .pages .uni-list ::v-deep .uni-load-more {
        display: flex;
    }

    .pages .uni-list ::v-deep .uni-list--border:after {
        background-color: #f5f5f5;
    }
</style>
