function setLastSearchedSpace(item) {
  if (!(item && item.spaceId)) {
    return Promise.reject()
  }
  return new Promise((resolve, reject) => {
    wx.setStorage({
      key: "lastSearchedSpace",
      data: {
        spaceId: item.spaceId
      },
      success: () => {
        resolve()
      },
      fail: () => {
        reject()
      }
    });
  })
}


function setHistorySearchedSpaceList(historyList, item) {
  // 去重
  historyList.find((history, index) => {
    if (history.spaceId == item.spaceId && history.value == item.value) {
      historyList.splice(index, 1);
      return true;
    }
    return false;
  });
  historyList.unshift(item);
  const maxLength = 10;
  // 最多记录10条数据
  if (historyList.length > maxLength) {
    historyList.splice(maxLength, historyList.length - maxLength);
  }

  wx.setStorage({
    key: "historySearchedSpaceList",
    data: {
      historyList: historyList,
    },
  });
  return historyList;
}

function getHistorySearchedSpaceList() {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: "historySearchedSpaceList",
      success: (res) => {
        if (res && res.data) {
          const historyList = res.data.historyList || [];
          resolve(historyList);
        }
      },
      fail: () => {
        resolve([]);
      }
    });
  })
}

export {
  setLastSearchedSpace,
  getHistorySearchedSpaceList,
  setHistorySearchedSpaceList
}