<template>
  <view class="search" :class="{ search_whrite: !isSearch }">
    <!-- 搜索框 -->
    <search-panel
      v-if="isLoading"
      ref="panel"
      :is-search="isSearch"
      :holder="searchWord"
      @enter="searchEnterEvent"
      @clear="clearKeywords"
    />
    <view v-if="!isSearch">
      <search-record
        v-if="historyArr.length"
        del-icon
        title="历史搜索"
        :record-list="historyArr"
        text-class="one-hide"
        @select="selectKeywords"
        @clear="clearHistoryData"
      />
      <search-record
        v-if="termsArray.length"
        title="大家都在搜"
        :record-list="termsArray"
        @select="selectKeywords"
      />
      <search-record
        v-if="hotActivity.length"
        text-key="activityName"
        title="热门活动"
        text-class="Sr-body-text__red"
        :record-list="hotActivity"
        @select="selectHotKeyWords"
      />
    </view>
    <view v-else class="search-list">
      <search-tab @change="searchTabChange" />
      <scroll-view
        class="search-list-container"
        scroll-y
        :scroll-top="tabScrollTop"
        :scroll-with-animation="isAnimate"
        @scrolltolower="loadData"
        @scroll="pageScroll"
      >
        <search-recommed v-if="hasRecommend" :key-words="searchParam.searchText" />
        <goods-list v-if="goodsList.length" :goods-list.sync="goodsList" />
        <uni-load-more v-if="goodsList.length > 3" :status="loadingType" />
        <view v-if="!goodsList.length && loadingType === 'noMore'" class="search-list__empty">
          没有搜到相关宝贝哦～
        </view>
      </scroll-view>
    </view>
    <view class="goods-top">
      <to-top :scroll-top="scrollTop" @toTop="toTop" />
    </view>
  </view>
</template>
<script>
import { homeSearch, getTerms } from "@/api/home.api.js";
import { setRegisterPage } from "@/utils/sa.js";
import { isHttpLink, jumpWebViewUrl, throtte } from "@/utils";
import toTop from "@/components/toTop";
import goodsList from "@/components/goodsList";
import SearchPanel from "./components/SearchPanel";
import SearchRecord from "./components/SearchRecord";
import SearchTab from "./components/SearchTab";
import SearchRecommed from "./components/SearchRecommed";
import { mpConfig } from "@/utils/mpConfig/types";
export default {
  components: {
    goodsList,
    toTop,
    SearchPanel,
    SearchRecord,
    SearchTab,
    SearchRecommed
  },
  data() {
    return {
      isLoading: false,
      isAnimate: mpConfig.isAnimate,
      searchWord: "搜索你想要的宝贝", // 获取输入框placeHorder推荐词
      isSearch: false, // 是否回车之后搜索的状态
      loadingType: "loading",
      hasRecommend: false, // 是否展示推荐流
      loading: false,
      searchParam: {
        searchText: "",
        pageNo: 1,
        pageSize: 10,
        rankType: 1, //排序类型 1:综合; 2:价格倒序; 3: 价格 正序; 4. 销量倒序; 5: 销量正序;
        searchId: "" //搜索批次ID(首次搜索不传)
      },
      historyArr: [], // 历史搜索 推荐词
      termsArray: [], // 大家都在搜推荐词
      hotActivity: [], // 热门活动推荐词
      goodsList: [],
      tabScrollTop: 0,
      scrollTop: 0,
      old: {
        scrollTop: 0
      }
    };
  },
  onLoad(option) {
    this.init(option);
    this.historyArr = uni.getStorageSync("historyArr") || [];
    this.getTermsList();
    this.setCurrentPath();
  },
  onShow() {
    setRegisterPage({
      parent_channelid: uni.getStorageSync("vccChannel") || "",
      son_channelid: uni.getStorageSync("sonVccChannel") || ""
    });
  },
  methods: {
    init(option) {
      this.$nextTick(() => {
        this.searchWord = option.keyWords || "搜索你想要的宝贝";
        this.isLoading = true; // 支付宝小程序真机props只接收第一次参数，获取到参数之后再次渲染
      });
    },
    async getTermsList() {
      const [res] = await getTerms(); // 大家都在搜的关键词接口
      this.termsArray = res?.terms || [];
      this.hotActivity = res?.hotActivity || [];
    },
    setCurrentPath() {
      const routes = getCurrentPages();
      this.searchParam.appPrePage = routes[routes.length - 2]?.route || "";
    },
    setHistoryArray(keyWords) {
      if (!this.historyArr.includes(keyWords)) {
        this.historyArr.unshift(keyWords);
        uni.setStorageSync("historyArr", this.historyArr);
      }
    },
    selectHotKeyWords({ jumpUrl, activityName }) {
      if (jumpUrl) {
        const url = isHttpLink(jumpUrl) ? jumpWebViewUrl(jumpUrl) : jumpUrl;
        return uni.navigateTo({ url });
      }
      this.selectKeywords(activityName);
    },
    clearHistoryData() {
      uni.removeStorageSync("historyArr");
      this.historyArr = [];
    },
    searchEnterEvent(keyWords) {
      this.setHistoryArray(keyWords);
      this.searchParam.searchText = keyWords;
      this.search();
    },
    selectKeywords(keyWords) {
      this.$refs.panel.keyWords = keyWords;
      this.searchEnterEvent(keyWords);
    },
    clearKeywords() {
      this.searchParam.searchText = "";
      this.isSearch = false;
    },
    searchTabChange(rankType) {
      this.searchParam.rankType = rankType; // 切换筛选项
      this.search();
    },
    search() {
      this.isSearch = true;
      this.goodsList = [];
      this.searchParam.pageNo = 1;
      this.searchParam.searchId = "";
      this.getSearchResult();
    },
    async getSearchResult() {
      this.loading = false;
      this.hasRecommend = false; // 重置推荐流
      this.loadingType = "loading";
      const [res] = await homeSearch(this.searchParam, false);
      this.goodsList = [...this.goodsList, ...(res?.goodsList || [])];
      this.searchParam.searchId = res?.searchId;
      this.hasRecommend = res?.hasRecommend;
      this.loadingType = res?.hasNext ? "more" : "noMore";
      this.searchParam.pageNo++;
      this.loading = true;
    },
    async loadData() {
      if (this.loading && this.loadingType !== "noMore") {
        await this.getSearchResult();
      }
    },
    pageScroll: throtte(function(val) {
      this.scrollTop = val.detail.scrollTop;
      this.old.scrollTop = val.detail.scrollTop;
    }, 1000),
    //滚动到顶部
    toTop() {
      this.tabScrollTop = this.old.scrollTop;
      this.$nextTick(function() {
        this.tabScrollTop = 0;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.search {
  height: 100vh;
  &_whrite {
    background: $white;
  }
  &-list {
    height: calc(100% - 80rpx);
    background-color: $white;
    &-container {
      height: calc(100% - 80rpx);
    }
    &__empty {
      font-size: 30rpx;
      color: $text-color-n1;
      text-align: center;
      padding-top: 250rpx;
    }
  }
}
</style>
