<template>
  <div class="search-list-con">
    <list-header
      :searchForm="searchForm"
      @search="handleSearch"
      @filterChange="filterChange"
    />
    <div class="list-scroll" v-show="!loading">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="requestData"
      >
        <list-item
          v-for="(item, index) of goodsList"
          :key="'search-item-' + index"
          :data="item"
        />
      </van-list>
    </div>
    <loading-mask v-show="loading" />
  </div>
</template>

<script>
import ListHeader from "./list-header.vue";
import ListItem from "./list-item";
import LoadingMask from "./loading-mask";
export default {
  components: {
    ListHeader,
    ListItem,
    LoadingMask,
  },
  data() {
    return {
      loading: false,
      finished: false,
      searchForm: {
        page: 1,
        size: 10,
        searchKey: "",
        categoryId: "",
        price: "asc",
        sale: "desc",
      },
      downOption: {
        autoShowLoading: false,
        use: false,
      },
      upOption: {
        use: true,
        page: {
          num: 0,
          size: 10,
          time: null,
        },
      },

      goodsList: [],
    };
  },
  watch: {
    loading(val) {
      val ? this.$showLoading() : this.$hideLoading();
    },
  },
  methods: {
    handleSearch(clear) {
      let { searchKey } = this.searchForm;
      if (clear) {
        searchKey = "";
      }
      this.$router.replace({ name: "search", query: { searchKey } });
    },
    requestData() {
      if (this.searchForm.page == 1) {
        this.loading = true;
        this.goodsList = [];
      }
      this.$api({
        apiName: "goodsSearch",
        postData: this.searchForm,
        success: (res) => {
          setTimeout(() => {
            let { list, count } = res;
            this.goodsList = this.goodsList.concat(list);
            this.loading = false;
            this.finished = this.goodsList.length >= count
            this.searchForm.page++
          }, 500);
        },
      });
    },

    filterChange(filterData) {
      let { index, val, subVal } = filterData;
      if (val == "price") {
        this.searchForm.price = subVal;
        this.searchForm.sale = "";
      } else if (val == "sale") {
        this.searchForm.sale = subVal;
        this.searchForm.price = "";
      } else {
        this.searchForm.sale = "desc";
        this.searchForm.price = "asc";
      }
      this.searchForm.page = 1;
      this.requestData();
    },
  },
  created() {
    let { searchKey, categoryId } = this.$route.query;
    this.searchForm.searchKey = searchKey;
    this.searchForm.categoryId = categoryId;

    this.requestData()
  },
};
</script>

<style lang="less">
.search-list-con {
  background: #f5f7fb;
  display: flex;
  flex-direction: column;
  .list-scroll {
    flex: 1;
    overflow-y:auto;
  }
}
</style>
