// mycomponent/searchHistory/searchHistory.js
Component({
  properties: {
    storageName: {
      type: String,
      value: 'searchHistory'
    },
    showHistory: {
      type: Boolean,
      value: false,
    }
  },
  data: {
    // 搜索历史
    searchHistoryList: [],
    // 标记显示搜索历史
    showFlag: false,
    loadShow: false,
  },

  lifetimes: {
    attached() {
      console.log(this.properties.storageName,'1212');
      this.initKeywords();
      this.showHistory();
    }
  },

  methods: {
    showHistory() {
      if (this.data.searchHistoryList.length > 0) {
        this.setData({
          showFlag: true
        });
      }
    },

    initKeywords () {
      try {
        var localStorageobj = wx.getStorageSync(this.data.storageName);
        if (localStorageobj) {
          this.setData({
            searchHistoryList: JSON.parse(localStorageobj)
          });
        } else {
          wx.setStorageSync(this.data.storageName, "[]");
        }
      } catch (err) {
        console.log(err);
      }
    },

    // 清空历史记录
    clearHistoryItems() {
      try {
        this.triggerEvent("popTag");
        wx.removeStorageSync(this.data.storageName);
        this.setData({
          searchHistoryList: [],
          showFlag: false
        });
      } catch (err){
        console.log(err);
      }
    },

    // 删除一项历史记录
    popHistoryItems(event) {
      try {
        let value = event.target.dataset.item;
        let arr = this.data.searchHistoryList;
        let index = this.data.searchHistoryList.findIndex((item) => item.name == value);
        if (value !== "" && index >= 0) {
          arr.splice(index, 1);
          this.triggerEvent("popTag");
          this.setData({
            searchHistoryList: arr
          });
          wx.setStorageSync(this.data.storageName, JSON.stringify(arr));
        }
      } catch (err) {
        console.log(err);
      }
      return false;
    },

    appendKeywords(value) {
      var appendFlag = true;
      if (!value) {
        return;
      }
      value = value.trim();
      if (this.data.searchHistoryList && this.data.searchHistoryList.length > 0) {
        this.data.searchHistoryList.forEach((item, index) => {
          if (item.name === value) {
            appendFlag = false;
            return;
          }
        });
      }
      
      if (appendFlag && value !== '') {
        let arr = this.data.searchHistoryList;
        let len = this.data.searchHistoryList.length;
        if (len >= 10) {
          arr.pop();
        }
        let timer = Date.parse(new Date());
        arr.unshift({name: value, key: timer});
        wx.setStorageSync(this.data.storageName, JSON.stringify(arr));
        this.setData({
          searchHistoryList: arr
        });
      } 
    },

    clickTag (event) {
      let value = event.currentTarget.dataset.item;
      this.triggerEvent("clickTag",value);
    },
  }
});