<template>
<view>
<!--pages/search/search.wxml-->
<view class="ssbox bgfff">
  <view class="search dflex">
    <view class="searchs dflex flex">
      <image src="/static/pages/images/ssico.png" class="ssico"></image>
      <input name="searchTitle" placeholder="搜索你想要的商品" placeholder-class="placeholder" class="flex" :value="searchTitle" @input="search" @confirm="confirm" confirm-type="search" auto-focus focus="true"></input>
      <image src="/static/pages/images/clear.png" class="clear" @tap="clearInput" v-if="isCuo"></image>
    </view>
    <view class="cancel" @tap="cancelSearch" v-if="isCancel">取消</view>
		<view class="sbtn" @tap="confirmSearch" v-else>搜索</view>
  </view>
</view>
<view class="lishi">
  <view class="tit">历史搜索</view>
  <view class="list dflex">
    <view v-for="(item, index) in history" :key="index" class="li" @tap="toTapSearch" :data-value="item">{{item}}</view>
  </view>
  <view class="delete dflex" @tap="clearHistory" v-if="history.length > 0"><image src="/static/pages/images/delete.png"></image>清空历史记录</view>
</view>
<view class="cai" v-if="likeList.length>0">
	<view class="cai-tit dflex"><image src="/static/pages/images/cai_bg1.png"></image>猜您喜欢<image src="/static/pages/images/cai_bg2.png"></image></view>
	<view class="tabcon pdlr20 dflex">
			<block v-for="(item, index) in likeList" :key="index">
				<view class="li">
					<view class="jsdimgs" @tap="toDetail" :data-id="item.id">
						<image :src="item.pic + '?x-oss-process=style/w375'" mode="aspectFit" class="jsdpro"></image>
						<image src="/static/pages/images/jishida.png" v-if="item.isJs == 1" class="jsdimg"></image>
					</view>
					<view class="jsdinfo">
						<view class="proname" @tap="toDetail" :data-id="item.id">{{item.title}}</view>
						<view class="operate dflex">
							<view class="price proprice">￥<text>{{show_membership_price==1&&item.actualPrice < item.salePrice?item.actualPrice:item.salePrice}}</text></view>
							<view class="add-cart">
								<view class="nums dflex" v-if="item.count > 0">
									<image src="/static/pages/images/jian.png"></image>
									<view class="num">{{item.count}}</view>
									<image src="/static/pages/images/jia1.png"></image>
								</view>
								<image src="/static/pages/images/jia.png" @tap="addShopCart" :data-id="item.id" :data-skuid="item.skuId" :data-index="index" :data-state="item.state" v-else></image>
							</view>
						</view>
					</view>
				</view>
			</block>
		</view>
</view>
</view>
</template>

<script>
// pages/search/search.js
const app = getApp();
const req = require("../../utils/request.js");

export default {
  data() {
    return {
      searchTitle: '',
      history: [],
      page: 1,
      likeList: [],
      isLikeLoad: true,
      merchant: {},
      isCancel: true,
      isCuo: false,
      merchantId: "",
      show_membership_price: 0
    };
  },

  components: {},
  props: {},

  onLoad(options) {
    this.query = options;

    if (options.searchTitle) {
      this.setData({
        searchTitle: options.searchTitle
      });
    }

    if (options.merchantId) {
      this.setData({
        merchantId: options.merchantId
      });
    } else {// this.setData({merchantId:req.getStorage("defaultMerchant").id})
    }

    // console.log(options);
  },

  onShow(options) {
    this.getConfig();
    let history = req.getStorage('HISTORYS'); // let merchant = req.getStorage("MERCHANT");

    this.setData({
      history: history // merchant:merchant

    });
    this.getLikeList();
  },

  methods: {
    getConfig() {
      var _this = this;

      return new Promise((resolve, reject) => {
        req.getRequest('/api/config', {}, function (res) {
          if (res && res.show_membership_price == 1) {
            _this.setData({
              show_membership_price: 1
            });
          }

          resolve();
        });
      });
    },

    search(e) {
      this.searchTitle = e.detail.value;
      this.setData({
        searchTitle: e.detail.value
      });

      if (this.searchTitle.length > 0) {
        this.setData({
          isCancel: false,
          isCuo: true
        });
      } else {
        this.setData({
          isCancel: true,
          isCuo: false
        });
      }

      return e.detail.value.replace(/\s+/g, '').replace(/[^\u4e00-\u9fa5a-zA-Z0-9\w]/g, '');
    },

    cancelSearch() {
      uni.navigateBack();
    },

    clearInput() {
      this.setData({
        searchTitle: '',
        isCancel: true,
        isCuo: false
      });
    },

    addShopCart(e) {
      let state = e.currentTarget.dataset.state;
      let skuId = e.currentTarget.dataset.skuid;
      let id = e.currentTarget.dataset.id;
      let params = {
        skuId: skuId,
        quantity: 1,
        productId: id
      }; // if(state!=1){
      //   return req.msg('您来晚了，商品已经下架')
      // }

      if (this.merchantId) {
        params.merchantId = this.merchantId;
      }

      req.postRequest('/api/purchase/cart', params, res => {
        req.msg('加入购物车成功');
      });
    },

    confirm(e) {
      let value = e.detail.value;
      if (!value) return req.msg('请输入商品名称');
      this.toSearch(value, true);
    },

    confirmSearch() {
      let value = this.searchTitle;
      if (!value) return req.msg('请输入商品名称');
      this.toSearch(value, true);
    },

    toTapSearch(e) {
      let value = e.currentTarget.dataset.value;
      this.toSearch(value, false);
    },

    toSearch(value, isSave) {
      let supplier = '';

      if (this.query.supplier) {
        supplier = '&supplier=' + this.query.supplier;
      }

      if (this.merchantId) {
        if (this.query.shopId) {
          app.globalData.redirectTab('product/list/list?searchTitle=' + value+'&merchantId='+this.query.merchantId + '&shopId=' + this.query.shopId + supplier);
        } else {
          app.globalData.redirectTab('product/list/list?searchTitle=' + value + '&merchantId=' + this.merchantId + supplier);
        }
      } else {
        app.globalData.redirectTab('product/list/list?searchTitle=' + value + supplier);
      }

      if (isSave) {
        let historys = this.history;

        if (historys.length < 1) {
          historys = [];
          historys.unshift(value);
        } else {
          historys.unshift(value);
        }

        req.setStorage('HISTORYS', historys);
      }
    },

    clearHistory() {
      req.removeStorage('HISTORYS');
      this.setData({
        history: []
      });
    },

    getLikeList() {
      //Recommend
      if (!this.isLikeLoad) return false;
      this.isLikeLoad = false;
      let that = this;
      let form = {
        page: that.page,
        limit: 10,
        attr: 'sell_well'
      };

      if (this.merchantId) {
        form.merchantId = this.merchantId;
      }

      req.getRequest('/api/product/list', form, res => {
        if (res && res.length >= 10) that.isLikeLoad = true;
        if (that.page > 1) res = that.likeList.concat(res);
        res = res.map(it => {
          if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs = true;
          return it;
        });
        that.setData({
          likeList: res
        });
      });
    },

    toDetail(e) {
      let id = e.currentTarget.dataset.id;
      // console.log(id);

      if (this.merchantId) {
        app.globalData.openPage('product/detail/detail?id=' + id + "&merchantId=" + this.merchantId);
      } else {
        app.globalData.openPage('product/detail/detail?id=' + id);
      }
    }

  }
};
</script>
<style>
@import "./search.css";
</style>