<template>
  <div class="search" :class="{ search_whrite: !isSearch }">
    <search-panel
      ref="panel"
      :placeholder-text="placeholderText"
      :is-search="isSearch"
      @clear="clearKeywords"
      @enter="searchEnterEvent"
      @changeListType="changeListType"
    />
    <search-record
      v-if="!isSearch"
      :terms-array="termsArray"
      :history-arr="historyArr"
      @clear="clearHistoryData"
      @select="selectKeywords"
    />
    <div v-else :class="['search-list', isParams && 'search-h']">
      <search-tab
        :filter-data="filterData"
        :total-cnt-str="totalCntStr"
        :search-text="searchText"
        @change="searchTabChange"
        @filterCondition="filterCondition"
      />
      <!-- 优惠券凑单页 -->
      <div v-if="iscoupon" class="search-coupon">
        {{ couponLimitInfo.couponDesc }}
      </div>
      <div :class="['home-container', { 'home-container-h': isParams }]">
        <scroll-view ref="scrollView" :to-top="scrollTop" @toBottom="loadData" @scroll="onScroll">
          <search-recommed v-if="hasRecommend" :key-words="searchText" />
          <goodsListMultiLayout
            v-if="goodsList.length"
            :layout-type="goodsListType"
            :goods-list.sync="goodsList"
            @addProduct="addProduct"
          />
          <load-more v-if="goodsList.length > 3" :status="loadingType" />
          <div v-if="!goodsList.length && loadingType === 'noMore'" class="home-container-noData">
            <cr-image
              src="https://img.lkbang.net/search-no-data.19cce2da.png"
              width="160px"
              height="160px"
            />
            没有搜到相关宝贝哦～
          </div>
        </scroll-view>
      </div>
    </div>
    <shopcart v-if="isSearch && !iscoupon" :shopcart-count="shopcartCount" />
    <to-top :scroll-top="scrollTop" show-shopcart @toTop="handleToTop" />
    <CouponBottom v-if="iscoupon && isSearch" :coupon-limit-info="couponLimitInfo" />
  </div>
</template>
<script>
import { homeSearch, getTerms } from '@/api/home.api';
import goodsListMultiLayout from '@/components/goodsListMultiLayout';
import scrollView from '@/components/scrollView';
import loadMore from '@/components/loadMore';
import localStorage from '@/service/localStorage.service';
import toTop from '@/components/toTop';
import SearchTab from './components/SearchTab';
import SearchPanel from './components/SearchPanel';
import SearchRecord from './components/SearchRecord';
import SearchRecommed from './components/SearchRecommed';
import historyRecordMixins from '@/mixins/historyRecord.mixins';
import shopcart from '@/components/shopcart';
import CouponBottom from './couponComponent/CouponBottom.vue';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'search',
  components: {
    goodsListMultiLayout,
    toTop,
    scrollView,
    loadMore,
    SearchPanel,
    SearchTab,
    SearchRecord,
    SearchRecommed,
    shopcart,
    CouponBottom
  },
  mixins: [historyRecordMixins],
  data() {
    return {
      isParams: false, // 是否有地址参数，区分是否是搜索还是外链
      isSearch: false,
      hasRecommend: false, // 是否展示推荐流
      loading: false,
      scrollTop: 0,
      loadingType: 'loading',
      searchParam: {
        pageNo: 1,
        pageSize: 50,
        rankType: 1, //排序类型 1:综合; 2:价格倒序; 3: 价格 正序; 4. 销量倒序; 5: 销量正序;
        searchId: '', //搜索批次ID(首次搜索不传)
        labelIds: '',
        searchContent: [],
        filterCategoryIds: '', // 过滤类目
        filterBrandIds: '', // 过滤品牌
        maxPrice: '', // 价格区间 max
        minPrice: '' // 价格区间 min
      },
      goodsList: [],
      termsArray: [],
      historyArr: [],
      goodsListType: 1, // 1：一行一  2：一行二
      placeholderText: '',
      searchText: '',
      filterData: {},
      totalCntStr: 0,
      iscoupon: false,
      couponLimitInfo: {}
    };
  },
  computed: {
    shopcartCount() {
      return this.$store.state.shopCart.cartCount;
    }
  },
  activated() {
    const currnetScrollTop = this.scrollTop;
    this.scrollTop = 0;
    this.$nextTick(() => {
      this.scrollTop = currnetScrollTop;
    });
  },
  created() {
    const { categoryId, labelId, title, brandId } = this.$route.query;
    this.isParams = !!(labelId || categoryId || brandId);
    this.placeholderText = title || '';
    if (this.isParams) {
      // 列表页面
      title && this.$store.commit('CHANGE_TITLE', '搜索');
      this.createParams();
      this.search();
      this.$track.registeredEvents('H5_2B_CommodityListPageExposure');
    } else {
      this.historyArr = localStorage.get('historyArr') || [];
      this.getTermsList(); // 展示热词 || 暂留疑问？
      this.$track.registeredEvents('H5_2B_SearchPageExposure');
    }
  },
  methods: {
    createParams(data) {
      // 构造请求参数的方法
      // data object, key: text and tagType
      // tagType 0-正常文字，1品牌id，11品牌名，2分类id，21分类名
      const { categoryId, labelId, brandId, couponId } = this.$route.query;
      const searchContent = [
        { tagType: 2, text: categoryId },
        { tagType: 1, text: brandId },
        { tagType: 0, text: this.searchText }
      ];
      if (data) {
        const tagType = data.tagType;
        searchContent.map(item => {
          if (item.tagType == tagType && item.tagType === 0) {
            item.text = data.text;
          }
        });
      }
      if (couponId) {
        // 优惠券凑单
        this.iscoupon = true;
        this.searchParam.activityType = 2;
        this.searchParam.activityId = couponId;
      }
      this.searchParam.rankType = 1;
      this.searchParam.labelIds = labelId;
      this.searchParam.searchContent = searchContent.filter(item => !!item.text);
    },
    changeListType(type) {
      this.goodsListType = type;
    },
    async getTermsList() {
      const [res] = await getTerms(); // 获取热词接口
      this.termsArray = res?.terms || [];
    },
    onScroll(top) {
      this.scrollTop = top;
    },
    //滚动到顶部
    handleToTop() {
      this.scrollTop = 0;
      let top = this.$refs.scrollView.$refs.scrollContent.scrollTop;
      const timeTop = setInterval(() => {
        this.$refs.scrollView.$refs.scrollContent.scrollTop = top -= 50;
        if (top <= 0) clearInterval(timeTop);
      }, 10);
    },
    setHistoryArray(keyWords) {
      if (!this.historyArr.includes(keyWords)) {
        this.historyArr.unshift(keyWords);
        localStorage.set('historyArr', this.historyArr);
      }
    },
    clearHistoryData() {
      localStorage.remove('historyArr');
      this.historyArr = [];
    },
    searchEnterEvent(keyWords) {
      this.setHistoryArray(keyWords);
      this.searchText = keyWords;
      this.createParams({
        tagType: 0,
        text: keyWords
      });
      this.filterCondition({});
    },
    selectKeywords(keyWords) {
      this.$refs.panel.keyWords = keyWords;
      this.searchText = keyWords;
      this.createParams({
        tagType: 0,
        text: keyWords
      });
      this.filterCondition({});
    },
    clearKeywords() {
      this.searchText = '';
      this.isSearch = false;
    },
    searchTabChange(rankType) {
      this.searchParam.rankType = rankType;
      this.search();
    },
    filterCondition(eventData) {
      const { categoryId, brandIds, maxPrice, minPrice, lastOperateType } = eventData;
      this.searchParam.filterCategoryIds = categoryId || '';
      this.searchParam.filterBrandIds = brandIds || '';
      this.searchParam.maxPrice = isNaN(parseFloat(maxPrice)) ? '' : maxPrice;
      this.searchParam.minPrice = isNaN(parseFloat(minPrice)) ? '' : minPrice;
      this.searchParam.lastOperateType = lastOperateType || '';
      this.search();
    },
    async search() {
      this.isSearch = true;
      this.goodsList = [];
      this.searchParam.pageNo = 1;
      this.getSearchResult();
    },
    async getSearchResult() {
      this.loading = false;
      this.hasRecommend = false; // 重置推荐流
      this.loadingType = 'loading';
      const [res] = await homeSearch(this.searchParam);
      this.goodsList = [...this.goodsList, ...(res?.goodsList || [])];
      this.searchParam.searchId = res?.searchId;
      this.hasRecommend = res?.hasRecommend;
      if (res && res.filterItemsData) this.filterData = res.filterItemsData;
      this.totalCntStr = res?.totalCntStr || 0;
      this.loadingType = res?.hasNext ? 'more' : 'noMore';
      this.couponLimitInfo = res?.couponLimitInfo || {};
      this.loading = true;
      if (res && res.totalCntStr && this.totalCntStr == 0) {
        this.$toast('暂无匹配商品，换个选项试试吧');
      }
    },
    async loadData() {
      if (this.loading && this.loadingType !== 'noMore') {
        this.getSearchResult();
        this.searchParam.pageNo++;
      }
    },
    // 优惠券加购小计
    addProduct(val) {
      this.couponLimitInfo.totalAmt =
        Math.round((+this.couponLimitInfo.totalAmt + +val) * 100) / 100;
      this.couponLimitInfo.needAmt =
        +this.couponLimitInfo.needAmt - +val > 0
          ? Math.round((this.couponLimitInfo.needAmt - +val) * 100) / 100
          : '0.00';
    }
  }
};
</script>
<style lang="less" scoped>
.search {
  height: 100%;
  overflow: hidden;
  &_whrite {
    background: @white;
  }
  &-list {
    height: calc(100% - 40px);
    // background-color: @white;
    // background-color: @gray-6;
    &.search-h {
      height: 100%;
    }
    .home-container {
      height: calc(100% - 60px);
      &.home-container-h {
        height: calc(100% - 45px);
      }
      &-noData {
        display: flex;
        flex-direction: column;
        align-items: center;
        .text-size(14);
        color: @gray-4;
        text-align: center;
        margin-top: 125px;
        .cr-image {
          margin-bottom: 20px;
        }
      }
    }
  }
  &-coupon {
    padding: 14px 11px;
    font-size: 13px;
    font-weight: 400;
    color: #333333;
  }
}
</style>
