<template>
  <!-- #ifdef H5 -->
  <zj-page-layout
    :hasFooter="false"
    :isScroll="true"
    :refresherTriggered="refresherTriggered"
    @refresherrefresh="refresherrefresh"
    @scrolltolower="scrolltolower">
    <template slot="header">
      <view class="search-container">
        <u-search
          shape="round"
          focus
          :showAction="isShowSearch ? true : false"
          actionText="取消"
          placeholder="搜索商品名称或型号"
          v-model="keyword"
          @search="searchData"
          @clear="searchData"
          @focus="searchFocus"
          @custom="searchCustom">
        </u-search>
      </view>
      <view class="top-container" v-if="!isShowSearch">
        <view class="tab">
          <view class="item" :class="screenType === 0 ? 'current':''" @tap="changeScreen(0)">综合</view>
          <view class="item" :class="screenType === 1 ? 'current':''" @tap="changeScreen(1)">销量</view>
          <view class="item" :class="screenType === 2 || screenType === 3 ? 'current':''"  @tap="changeScreen(2)">价格
            <image src="@/static/icon/price_1.png" v-if="screenType === 2"></image>
            <image src="@/static/icon/price_2.png" v-if="screenType === 3"></image>
            <image src="@/static/icon/price_0.png" v-if="screenType != 2 && screenType != 3"></image>
          </view>
          <!-- <view class="item" :class="screenType === 4 ? 'current':''" @tap="changeScreen(4)">上架时间</view> -->
          <view class="item" :class="screen.priceMin || screen.priceMax || screen.tag || screen.brand ? 'current':''" @tap="openScreen()">筛选</view>
        </view>
        <view class="icon">
          <image src="@/static/icon/show_1.png" v-if="showType == 1" @tap="showType = 2"></image>
          <image src="@/static/icon/show_2.png" v-if="showType == 2" @tap="showType = 1"></image>
        </view>
      </view>
    </template>

    <block v-if="isShowSearch">
      <view class="searchData-container">
        <view class="lately-container">
        	<view class="common-title">
        		<view class="left">最近搜索</view>
        		<view class="right" @tap="clearHistoryList">
        			<text class="iconfont icon-shanchu"></text>
        		</view>
        	</view>
        	<view class="list">
        		<view class="item" v-for="(item, index) in historyList" :key="index" @tap="clickHistory(item)">{{item}}</view>
        	</view>
        </view>

        <view class="brand-container">
        	<view class="common-title">
        		<view class="left">热门品牌</view>
        	</view>
        	<view class="list">
        		<view class="item" v-for="(item, index) in brandList" :key="index" @tap="clickBrand(item)">
        			<image :src="item.imageUrl" mode="aspectFill"></image>
        			<view class="name">{{item.brandName}}</view>
        		</view>
        	</view>
        </view>
      </view>
    </block>

    <block v-else>
      <view class="goods-waterfall-list" v-if="showType == 1">
        <view class="left">
          <block v-for="(item, index) in dataList" :key='index'>
            <view class="item" v-if="index%2==0" @tap="toGoodsDetail(item.goodsId)">
              <view class="image">
                <image :src="item.imgUrl" mode="aspectFill" class="img"></image>
                <image :src="item.logo" mode="aspectFill" class="water" v-if="item.isShowWater"></image>
              </view>
              <view class="content">
                <view class="title ellipsis-2">{{item.goodsName}}</view>
                <view class="tags" v-if="item.tags1 && item.tags1.length > 0">
                  <view class="it" v-for="(it, idx) in item.tags1" :key="idx">{{it}}</view>
                </view>
                <view class="tags2" v-if="(item.tags2 && item.tags2.length > 0) || item.promotionFullPiece || item.isTrade == 'YES'">
                  <view class="it" v-if="item.promotionFullPiece">满件打折</view>
                  <view class="it" v-if="item.isTrade == 'YES'">以旧换新</view>
                  <view class="it" v-for="(it, idx) in item.tags2" :key="idx">{{it}}</view>
                </view>
                <view class="price">
                  <view class="price-1">¥{{item.goodsPrice | priceFilter}}</view>
                  <view class="price-2">¥{{item.orgGoodsPrice | priceFilter}}</view>
                </view>
                <view class="text">销量：{{item.soldNum}}</view>
              </view>
            </view>
          </block>
        </view>
        <view class="right">
          <block v-for="(item, index) in dataList" :key='index'>
            <view class="item" v-if="index%2==1" @tap="toGoodsDetail(item.goodsId)">
              <view class="image">
                <image :src="item.imgUrl" mode="aspectFill" class="img"></image>
                <image :src="item.logo" mode="aspectFill" class="water" v-if="item.isShowWater"></image>
              </view>
              <view class="content">
                <view class="title ellipsis-2">{{item.goodsName}}</view>
                <view class="tags" v-if="item.tags1 && item.tags1.length > 0">
                  <view class="it" v-for="(it, idx) in item.tags1" :key="idx">{{it}}</view>
                </view>
                <view class="tags2" v-if="(item.tags2 && item.tags2.length > 0) || item.promotionFullPiece || item.isTrade == 'YES'">
                  <view class="it" v-if="item.promotionFullPiece">满件打折</view>
                  <view class="it" v-if="item.isTrade == 'YES'">以旧换新</view>
                  <view class="it" v-for="(it, idx) in item.tags2" :key="idx">{{it}}</view>
                </view>
                <view class="price">
                  <view class="price-1">¥{{item.goodsPrice | priceFilter}}</view>
                  <view class="price-2">¥{{item.orgGoodsPrice | priceFilter}}</view>
                </view>
                <view class="text">销量：{{item.soldNum}}</view>
              </view>
            </view>
          </block>
        </view>
      </view>

      <view class="goods-row-list" v-if="showType == 2">
        <block v-for="(item, index) in dataList" :key='index'>
          <view class="item" @tap="toGoodsDetail(item.goodsId)">
            <view class="image">
              <image :src="item.imgUrl" mode="aspectFill" class="img"></image>
              <image :src="item.logo" mode="aspectFill" class="water" v-if="item.isShowWater"></image>
            </view>
            <view class="right">
              <view>
                <view class="title ellipsis-2">{{item.goodsName}}</view>
                <view class="tags" v-if="item.tags1 && item.tags1.length > 0">
                  <view class="it" v-for="(it, idx) in item.tags1" :key="idx">{{it}}</view>
                </view>
                <view class="tags2" v-if="(item.tags2 && item.tags2.length > 0) || item.promotionFullPiece || item.isTrade == 'YES'">
                  <view class="it" v-if="item.promotionFullPiece">满件打折</view>
                  <view class="it" v-if="item.isTrade == 'YES'">以旧换新</view>
                  <view class="it" v-for="(it, idx) in item.tags2" :key="idx">{{it}}</view>
                </view>
              </view>
              <view>
                <view class="bottom">
                  <view class="price">
                    <view class="price-1">¥{{item.goodsPrice | priceFilter}}</view>
                    <view class="price-2">¥{{item.orgGoodsPrice | priceFilter}}</view>
                  </view>
                  <view class="text">销量：{{item.soldNum}}</view>
                </view>
              </view>
            </view>
          </view>
        </block>
      </view>

      <Loading :loadStatus="loadStatus" :dataList="dataList" />
    </block>

    <zjDialogScreen :isShow="isShowScreenDialog" @cancel="cancelScreen" @confirm="confirmScreen"></zjDialogScreen>

  </zj-page-layout>
  <!-- #endif -->
  <!-- #ifndef H5 -->
  <web-view :src="webViewHref(`/packageGoods/pages/search`, pam,crossPagePam)" @message="crossPage.$listener"></web-view>
  <!-- #endif -->
</template>

<script>
  // #ifdef H5
  import { compareTime } from '@/common/utils/util.js'
  import zjDialogScreen from '@/components/zj-dialog/zj-dialog-screen';

	export default {
    components: {
      zjDialogScreen
    },

		data() {
			return {
				screenType: '',
				dataList: [],
				pageNum: 1,
        loadStatus: 0,
        refresherTriggered: false,
				showType: 1,
        keyword: '',
        isShowScreenDialog: false,
        screen: {
          priceMin: '',
          priceMax: '',
          tag: '',
          brand: ''
        },
        brandList: [],
        historyList: [],
        isShowSearch: false,
			}
		},

		onLoad() {
			this.getList();
      this.getHistoryList();
      this.getBrandList();
		},

		methods: {
      getBrandList() {
        this.$api.get('/goods/category/brand', {
          categoryId: '',
        }).then(res => {
          this.brandList = res.data;
        })
      },

			// 获取商品列表
			getList() {
        if(!this.keyword) {
          return this.$nextTick(() => {
            this.loadStatus = 2;
            this.refresherTriggered = false;
          })
        }
				this.$api.get('/goods/list/sort/page', {
          pageNum: this.pageNum,
          pageSize: 10,
          categoryId: '',
          keyword: this.keyword,
          sort: this.screenType,
          minPrice: this.screen?.priceMin,
          maxPrice: this.screen?.priceMax,
          tag: this.screen?.tag,
          brandId: this.screen?.brand,
				}).then(res => {
					res.data.records.forEach(item => {
						if(item.logo && item.logoStartTime) {
							item.isShowWater = compareTime(item.logoStartTime, item.logoEndTime);
						}else {
							item.isShowWater = false;
						}
					})
					this.loadStatus = 0;
					let list = res.data.records;
					if (list.length < 10) {
					  this.loadStatus = 2;
					}
					this.dataList = this.dataList.concat(list);
				}).catch(() => {
          this.loadStatus = 2;
        }).finally(res => {
          this.refresherTriggered = false;
        })
			},

      // 滚动到底部
      scrolltolower(e) {
        if (this.loadStatus === 0) {
          this.pageNum++;
          this.getList();
        }
      },

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

      refreshList() {
        this.dataList = [];
        this.pageNum = 1;
        this.getList();
      },

      // 切换筛选类型
      changeScreen(type) {
        if(type != 2) {
          if(this.screenType !== type) {
            this.screenType = type;
          }else {
            this.screenType = '';
          }
        }else {
          if(this.screenType != 2 && this.screenType != 3) {
            this.screenType = 2;
          }else if(this.screenType == 2) {
            this.screenType = 3;
          }else {
            this.screenType = '';
          }
        }
        this.refreshList();
      },

			toGoodsDetail(id) {
				this.$navToPage({
					url: '/packageGoods/pages/detail?id=' + id
				})
			},

      moveStringToFront(arr, str) {
      	const index = arr.indexOf(str);
      	if (index !== -1) {
      		arr.splice(index, 1);
      	}
      	arr.unshift(str);
      	return arr;
      },

      getHistoryList() {
      	this.historyList = this.$getStorage('historySearchData') || [];
      },

      setHistoryList(keyword) {
      	let list = this.$getStorage('historySearchData') || [];
      	list = this.moveStringToFront(list, keyword);
      	this.$setStorage('historySearchData', list);
      },

      clearHistoryList() {
      	this.$modal({
      		content: '清空最近搜索记录？'
      	}).then(() => {
      		this.$setStorage('historySearchData', []);
      		this.getHistoryList();
      	}).catch(() => {})
      },

      clickHistory(keyword) {
      	this.keyword = keyword;
      	this.searchData();
      },

      searchData() {
        this.isShowSearch = false;
        this.refreshList();
        if(this.keyword) {
          this.setHistoryList(this.keyword);
          this.getHistoryList();
        }
      },

      searchFocus() {
        this.isShowSearch = true;
      },

      searchCustom() {
        this.isShowSearch = false;
      },

      openScreen() {
        this.isShowScreenDialog = true;
      },

      cancelScreen() {
        this.isShowScreenDialog = false;
      },

      confirmScreen(data) {
        this.screen = data;
        this.isShowScreenDialog = false;
        this.refreshList();
      },

      clickBrand(item) {
        this.$navToPage({
          url: `/packageGoods/pages/list?brandId=${item.id}&brandName=${item.brandName}`
        }, 'redirectTo')
      },
		}
	}
  // #endif
  // #ifndef H5
  export default {
    data() {
      return {
        pam: {},
      }
    },

    onLoad(pam) {
      this.pam = pam;
    },
  }
  // #endif
</script>

<style lang="scss">
  .search-container {
  	background: #ffffff;
    padding: 20rpx;
  	::v-deep .u-search {
  		height: 60rpx;
      input {
        background: #F7F8FF !important;
      }
  		.u-search__content {
        background: #F7F8FF !important;
  			height: 60rpx;
  		}
  	}
  }
	.top-container {
		background: #FFFFFF;
		display: flex;
		padding: 0 20rpx;
		align-items: center;
		box-sizing: border-box;
		.tab {
			flex: 1;
			display: flex;
			padding: 0 80rpx 0 30rpx;
			box-sizing: border-box;
			justify-content: space-between;
			.item {
				height: 88rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
				color: #666666;
				&.current {
					color: $theme-color;
				}
				image {
					width: 18rpx;
					height: 30rpx;
					display: block;
					margin-left: 10rpx;
				}
			}
		}
		.icon {
			padding-right: 10rpx;
			image {
				width: 36rpx;
				height: 36rpx;
				display: block;
			}
		}
	}

  .searchData-container {
    background: #ffffff;
    padding: 30rpx;
    height: 100%;
    box-sizing: border-box;
  }

  .common-title {
  	display: flex;
  	align-items: center;
  	justify-content: space-between;
  	.left {
  		font-size: 32rpx;
  		font-weight: 600;
  	}
  	.right {
  		.iconfont {
  			font-size: 36rpx;
  		}
  	}
  }

  .lately-container {
  	.list {
  		display: flex;
  		flex-wrap: wrap;
  		.item {
  			background: #f5f5f5;
  			padding: 12rpx 16rpx;
  			border-radius: 50rpx;
  			font-size: 24rpx;
  			margin-right: 20rpx;
  			margin-top: 20rpx;
  		}
  	}
  }

  .brand-container {
  	margin-top: 50rpx;
  	.list {
  		display: flex;
  		flex-wrap: wrap;
  		.item {
  			display: flex;
  			flex-direction: column;
  			align-items: center;
  			margin-right: 20rpx;
  			margin-top: 20rpx;
  			width: calc((100% - 60rpx) / 4);
  			font-size: 24rpx;
  			image {
  				width: 100%;
  				height: 140rpx;
  				margin-bottom: 8rpx;
  			}
  			.name {
  				width: 100%;
  				text-align: center;
  			}
  			&:nth-child(4n) {
  				margin-right: 0;
  			}
  		}
  	}
  }
</style>
