<template>
  <view>
    <Loading
    	:type="3"
    	:loadStatus="pageLoadStatus"
    	:showText="errorText"
      v-if="pageLoadStatus != 0"
    />

    <zj-page-layout
      v-else
      :isScroll="true"
      :refresherTriggered="refresherTriggered"
      @refresherrefresh="refresherrefresh"
      @scrolltolower="scrolltolower">
      <template slot="header">
        <view class="search-container">
          <view class="mask" @tap.stop="searchData"></view>
          <u-search
            shape="round"
            :showAction="false"
            placeholder="搜索商品"
            disabled>
          </u-search>
        </view>
      </template>

      <view class="all-container">
        <view class="swiper-container" v-if="bannerList.length > 0">
          <u-swiper
            :list="bannerList"
            keyName="imgSrc"
            autoplay
            circular
            indicator
            indicatorMode="line"
            height="175"
            @click="clickBanner"
          ></u-swiper>
        </view>

        <view class="category-container" v-if="categoryList.length">
          <view class="item" :class="categoryList.length <= 4 ? 'four' : ''" v-for="(item, index) in categoryList" :key="index" @tap="clickCategory(item)">
            <image :src="item.imgUrl" mode="aspectFill"></image>
            <view class="text" :class="item.categoryId == categoryValue ? 'active' : ''">{{item.name}}</view>
          </view>
        </view>

        <view class="button-container" v-if="userInfo.isEs && userInfo.type == 'WORKER'">
          <u-button type="primary" text="发布商品" shape="circle" @click="navToPage('/packageHome/pages/recycle/issue')"></u-button>
        </view>

        <view class="tabs-container">
          <u-tabs
          	:scrollable="false"
          	:list="tabList"
          	:current="tabIndex"
          	@click="changeTab"
          	lineColor="#3D8FFD"
          	:activeStyle="{
          		color: '#3D8FFD'
          	}"
          	:inactiveStyle="{
          		color: '#666666'
          	}"
          	itemStyle="padding-left: 0; padding-right: 0; height: 88rpx;">
          </u-tabs>
        </view>

        <view class="list-container">
          <view class="item" v-for="(item, index) in goodsList" :key="index" @tap="toGoodsDetail(item.id)">
            <view class="soldout" v-if="item.status == 'SALE'">
              <image src="@/static/images/recycle/soldout.png" mode="widthFix"></image>
            </view>
            <view class="top">
              <view class="left">
                <image :src="item.userHeadImg" mode="aspectFill"></image>
                <view class="info">
                  <view class="name">{{item.userNickName}}</view>
                  <view class="text">{{item.createTime | timeFilter}}发布</view>
                </view>
              </view>
              <view class="right">{{item.price | priceFilter2}}</view>
            </view>
            <view class="imgs" v-if="item.imgList && item.imgList.length > 0">
              <image :src="it.imgUrl" mode="aspectFill" v-for="(it, idx) in item.imgList" :key="idx"></image>
            </view>
            <view class="title">{{item.goodsName}}</view>
            <view class="message" v-if="item.messageList && item.messageList.length > 0">
              {{item.messageList[0].createBy}}：{{item.messageList[0].content}}
            </view>
            <view class="bottom">
              <view class="it">
                <text class="iconfont icon-dianzan"></text>
                <text class="text">{{item.likeCount || 0}}</text>
              </view>
              <view class="it">
                <text class="iconfont icon-pinglun"></text>
                <text class="text">{{item.messageCount || 0}}</text>
              </view>
              <view class="it">
                <text class="iconfont icon-liulan"></text>
                <text class="text">{{item.queryCount || 0}}</text>
              </view>
            </view>
          </view>
        </view>
        <Loading :loadStatus="loadStatus" :dataList="goodsList" />
      </view>

    </zj-page-layout>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        refresherTriggered: false, // 下拉刷新状态
        userInfo: {},
				bannerList: [], // 轮播图列表
        categoryList: [],
        categoryValue: '',
        tabList: [
          {name: '默认顺序', value: 'A'},
          {name: '在售商品', value: 'B'},
          {name: '人气最高', value: 'C'},
        ],
        tabIndex: 0,
        tabValue: 'A',
        pageNum: 1,
        loadStatus: 0,
        goodsList: [],

        pageLoadStatus: 1,
        errorText: '',
      }
    },

    async onLoad() {
      this.userInfo = await this.$getUserInfo();
      if((this.userInfo.type == 'SERVICE' || this.userInfo.type == 'WORKER') && this.userInfo.moduleEs) {
        this.pageLoadStatus = 0;
        await this.getBannerList();
        this.getCategoryList();
        this.refreshGoodsList();
      }
      else {
        this.pageLoadStatus = 2;
        this.errorText = '抱歉，您无权限访问二手商城';
      }

      this.crossPage.$on('refreshRecycleList', data => {
        this.refreshGoodsList();
      });
    },

    onUnload() {
      this.crossPage.$off('refreshRecycleList');
    },

    methods: {
      navToPage(url) {
        this.$navToPage({
          url
        })
      },

      // 搜索商品
      searchData() {
        this.navToPage('/packageHome/pages/recycle/search');
      },

      // 触发下拉刷新
      refresherrefresh(e) {
        this.refresherTriggered = true;
        this.getBannerList();
        this.getCategoryList();
        this.refreshGoodsList();
      },

      // 获取轮播图列表
      async getBannerList() {
      	return new Promise((resolve, reject) => {
      		this.$api.get('/common/list/page', {
            pageNum: 1,
            pageSize: 10,
            state: true,
            port: 'ESHOP'
      		}).then(res => {
      			this.bannerList = res.data.records;
            resolve(1);
      		}).catch(res => {
            reject(0);
          })
      	})
      },

      // 点击轮播图
      clickBanner(index) {
        let item = this.bannerList[index];
        if(item.type == 1) {
          this.toGoodsDetail(item.goodsId);
        }
      },

      getCategoryList() {
        this.$api.get('/goods/category/list', {
          type: 5,
        }).then(res => {
          this.categoryList = res.data;
        })
      },

      clickCategory(item) {
        this.categoryValue = item.categoryId == this.categoryValue ? '' : item.categoryId;
        this.refreshGoodsList();
      },

      changeTab(e) {
      	this.tabIndex = e.index;
      	this.tabValue = e.value;
        this.refreshGoodsList();
      },

      // 获取商品列表
      getGoodsList() {
        this.loadStatus = 1;
        this.$api.post('/es/goods/list', {
          pageNum: this.pageNum,
          pageSize: 5,
          categoryId: this.categoryValue,
          sortType: this.tabValue,
          status: this.tabValue == 'B' ? 'ON' : 'ON,SALE',
        }).then(res => {
          this.loadStatus = 0;
          let list = res.data.records;
          if (list.length < 5) {
            this.loadStatus = 2;
          }
          this.goodsList = this.goodsList.concat(list);
        }).catch(() => {
          this.loadStatus = 2;
        }).finally(() => {
          this.refresherTriggered = false;
        })
      },

      refreshGoodsList() {
        this.pageNum = 1;
        this.goodsList = [];
        this.getGoodsList();
      },

      scrolltolower() {
        if (this.loadStatus === 0) {
          this.pageNum++;
          this.getGoodsList();
        }
      },

      toGoodsDetail(id) {
      	this.$navToPage({
      		url: `/packageHome/pages/recycle/goodsDetail?id=${id}`
      	})
      },
    }
  }
</script>

<style lang="scss" scoped>
.search-container {
  background: #ffffff;
  padding: 20rpx;
  position: relative;
  .mask {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 999;
  }
  ::v-deep .u-search {
    height: 60rpx;
    input {
      background: #F7F8FF !important;
    }
    .u-search__content {
      background: #F7F8FF !important;
      height: 60rpx;
    }
  }
}

.all-container {
  padding: 0 20rpx 20rpx;
}

.swiper-container {
  @include zj-card;
  margin-top: 20rpx;
  ::v-deep .u-swiper {
    height: 350rpx !important;
    .u-swiper__wrapper {
      height: 350rpx !important;
    }
    .u-swiper__wrapper__item__wrapper__image {
      height: 350rpx !important;
    }
  }
}

.category-container {
  margin-top: 30rpx;
  @include zj-card;
  padding: 30rpx 0;
  display: flex;
  overflow: scroll;
  .item {
    flex-shrink: 0;
    width: 20%;
    margin-right: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    &:last-child {
      margin-right: 0;
    }
    &.four {
      width: 25%;
      margin-right: 0;
    }
    image {
      width: 100rpx;
      height: 100rpx;
    }
    .text {
      font-size: 26rpx;
      margin-top: 12rpx;
      font-weight: 500;
      &.active {
        color: $theme-color;
      }
    }
  }
}

.button-container {
  margin-top: 30rpx;
}

.tabs-container {
  margin-top: 20rpx;
}

.list-container {
  .item {
    @include zj-card;
    padding: 20rpx;
    margin-top: 20rpx;
    position: relative;
    .soldout {
      position: absolute;
      right: 150rpx;
      top: 20rpx;
      image {
        width: 120rpx;
      }
    }
    .top {
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;
        align-items: center;
        image {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
        }
        .info {
          margin-left: 20rpx;
          .name {
            font-size: 28rpx;
          }
          .text {
            font-size: 24rpx;
            color: $sec-font;
            margin-top: 12rpx;
          }
        }
      }
      .right {
        color: $minor-color;
        font-weight: 600;
      }
    }
    .imgs {
      display: flex;
      flex-wrap: wrap;
      image {
        width: 180rpx;
        height: 180rpx;
        margin-right: 20rpx;
        margin-top: 20rpx;
      }
    }
    .title {
      margin-top: 20rpx;
      line-height: 40rpx;
    }
    .message {
      font-size: 24rpx;
      color: $sec-font;
      border-left: 6rpx solid $theme-color;
      margin-top: 20rpx;
      padding-left: 12rpx;
    }
    .bottom {
      border-top: 1px solid #eaeaea;
      margin-top: 20rpx;
      padding-top: 20rpx;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .it {
        display: flex;
        align-items: center;
        margin-left: 30rpx;
        .iconfont {
          font-size: 32rpx;
          color: $sec-font;
        }
        .text {
          font-size: 28rpx;
          margin-left: 6rpx;
          color: $sec-font;
        }
      }
    }
  }
}

</style>
