<template>
<view id="store-search">
    <view class="search-box">
        <view class="input-box">
            <i class="iconfont icon-sousuo " type="search" size="20"></i>
            <input type="text" :value="text" @input="search" confirm-type="search" bindconfirm="searchKeywords"></input>
            <!-- #ifdef MP-WEIXIN -->
            <icon type="clear" size="20" class="clear" :hidden="clear" @tap="clearF"></icon>
            <!-- #endif -->
        </view>
        <view class="text" @tap="searchKeywords">
            搜索
        </view>
    </view>
    <view class="history-box" v-if="searches.length && show">
        <view class="keywords mx-1px-bottom" v-for="(item, index) in searches" :key="index">
            <view class="name" :data-index="index" @tap="searchHistory">{{item}}</view>
            <view class="clear" :data-index="index" @tap="removeSearchHistory">
                <i class="iconfont icon-close" type="clear" size="20"></i>
            </view>
        </view>
        <view class="clear-all" @tap="clearSearchHistory">
            清空历史记录
        </view>
    </view>
    <view class="goods-list" v-if="!show">
        <view v-for="(item, idx) in storeList" :key="idx">
            <view class="commodity-out" :data-id="item.id" v-for="(item, index) in storeList[idx]" :key="index" @tap="jump">
                <view class="commodity-box">
                    <view class="commodity-img">
                        <image mode="widthFix" :src="item.img"></image>
                    </view>
                    <view class="commodity-name">
                        {{item.name}}
                    </view>
                    <view class="commodity-money">
                        {{item.sell_price}}
                    </view>
                </view>
            </view>
        </view>

    </view>
</view>


</template>
<script>
import {pageLogin, getUrl,config} from '@/common/js/utils.js';

export default {
  data() {
    return {
      storeList: [],
      text: '',
      clear: true,
      searches: [],
      show: true,
      meta: ''
    };
  },

  onReachBottom() {
    var hasMore = this.meta.pagination.total_pages > this.meta.pagination.current_page;

    if (hasMore) {
      var query = {
        keyword: this.text
      };
      var page = this.meta.pagination.current_page + 1;
      this.querySearchList(query, page);
    } else {
      wx.showToast({
        image: '../../../static/error.png',
        title: '再拉也没有啦'
      });
    }
  },

  onShow() {// let app =getApp();
    // app.isBirthday().then(()=>{
    //     if(this.$cookieStorage.get("birthday_gift")){
    //         var giftData=this.$cookieStorage.get("birthday_gift").data;
    //         new app.ToastPannel().__page.showText(giftData);
    //     }
    // });
  },

  onReady() {
    var searches = this.$cookieStorage.get('goods_search_history');

    if (searches && searches.length) {
      this.setData({
        searches: searches
      });
    }
  },

  components: {},
  props: {},
  methods: {
    jump(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/store/detail/detail?id=' + id
      });
    },

    search(e) {
      this.setData({
        text: e.detail.value,
        clear: e.detail.value <= 0
      });
    },

    clearF() {
      this.setData({
        text: '',
        clear: true
      });
    },

    // 单击搜索
    searchKeywords() {
      var keyword = this.text;
      if (!keyword || !keyword.length) return;
      var searches = JSON.parse(JSON.stringify(this.searches));

      for (let i = 0, len = searches.length; i < len; i++) {
        let search = searches[i];

        if (search === keyword) {
          searches.splice(i, 1);
          break;
        }
      }

      searches.unshift(keyword);
      this.$cookieStorage.set('goods_search_history', searches);
      wx.setNavigationBarTitle({
        title: '搜索：' + "'" + keyword + "'"
      });
      this.querySearchList({
        keyword: keyword
      });
      this.setData({
        show: false,
        searches: searches
      });
    },

    // 点击单个搜索记录搜索
    searchHistory(e) {
      var searches = JSON.parse(JSON.stringify(this.searches));
      var keyword = searches[e.currentTarget.dataset.index];
      searches.splice(e.currentTarget.dataset.index, 1);
      searches.unshift(keyword);
      this.$cookieStorage.set('goods_search_history', searches);
      wx.setNavigationBarTitle({
        title: '搜索：' + "'" + keyword + "'"
      });
      this.querySearchList({
        keyword: keyword
      });
      this.setData({
        show: false,
        searches: searches,
        text: keyword
      });
    },

    // 删除单个搜索记录
    removeSearchHistory(e) {
      var searches = JSON.parse(JSON.stringify(this.searches));
      searches.splice(e.currentTarget.dataset.index, 1);
      this.$cookieStorage.set('goods_search_history', searches);
      this.setData({
        searches: searches
      });
    },

    // 清空搜索记录
    clearSearchHistory() {
      uni.removeStorageSync('goods_search_history');
      this.setData({
        show: false,
        searches: []
      });
    },

    // 搜索商品
    querySearchList(query = {}, page = 1) {
      var params = Object.assign({}, query, {
        page
      });
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      this.$http.get({
        api: 'api/store/list',
        data: params
      }).then(res => {
        res = res.data;

        if (res.status) {
          // var keyReg = new RegExp('(' + this.text + ')(?!</i>)', 'g')
          // list.forEach(item => {
          // 	item.name = item.name.replace(keyReg, '<i>$1</i>');
          // })
          if (!res.data || !res.data.length) {
            wx.showModal({
              content: '暂无该商品',
              showCancel: false
            });
          }

          this.setData({
            [`storeList.${page - 1}`]: res.data,
            meta: res.meta
          });
        } else {
          wx.showModal({
            title: '',
            content: res.message
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.showModal({
          title: '',
          content: '请求失败，请稍后重试'
        });
        wx.hideLoading();
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "search";
</style>