import { loadEnd, loadData } from "../../utils/index";
import { __FAIL_FN } from "../../utils/network";
const baseUrl = require("../../api/index.js").config;
const masses = require("../../api/masses.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hotKeywords: [],
    history: [],
    name_focus: true,
    search: "搜索",
    input_value: "", //value值
    inpuVal: "", //input框内值
    keydown_number: 0,
    searchflag: false,
    array1: [0, 1, 2],
    spatialData: "typehunt",
    //检测input框内是否有值
    termlist: [],
    termindex: 9,
    termLoadEnd: false,
    hasMore: true,
    // 分页加载
    pagenum: 0,
    pagesize: 10,
  },
  inputValue: function (e) {
    this.setData({
      inpuVal: e.detail,
    });
    wx.setStorageSync("inputval", e.detail);
    if (e.detail.cursor != 0) {
      this.setData({
        search: "搜索",
        keydown_number: 1,
      });
    } else {
      this.setData({
        search: "取消",
        keydown_number: 0,
      });
    }
    // 搜索为空时
    if (e.detail == "") {
      this.setData({
        searchflag: false,
      });
    }
  },
  // 搜索
  searchTap: function () {
    this.setData({
      pagenum: 0,
      termlist: [],
      hasMore: true,
      termLoad: false,
      termLoadEnd: true,
    });
    this.getTerm();
    if (this.data.keydown_number == 1) {
      let that = this;
      let arr = this.data.history;
      that.setData({
        searchflag: true,
      });
      //判断是手动输入的还是点击赋值
      if (this.data.input_value == "") {
        //判断是否已经存在
        let arrnum = arr.indexOf(this.data.inpuVal);
        if (arrnum != -1) {
          //删除已存在后重新插入至数组
          arr.splice(arrnum, 1);
          arr.unshift(this.data.inpuVal);
        } else {
          arr.unshift(this.data.inpuVal);
        }
      } else {
        let arr_num = arr.indexOf(this.data.input_value);

        if (arr_num != -1) {
          arr.splice(arr_num, 1);
          arr.unshift(this.data.input_value);
        } else {
          arr.unshift(this.data.input_value);
        }
      }
      // var historylists= wx.getStorageSync('history_arr');
      //存储搜索记录
      wx.setStorage({
        key: "history_arr",
        data: arr,
      });
      //取出搜索记录
      wx.getStorage({
        key: "history_arr",
        success: function (res) {
          if (res.data.length >= 10) {
            res.data.splice(10, 1);
            that.setData({
              history: res.data,
            });
          } else {
            that.setData({
              history: res.data,
            });
          }
        },
      });
      // this.setData({
      //   input_value: '',
      // })
    } else {
      console.log("取消");
    }
  },
  //清除最近搜索
  deleteTap: function () {
    this.setData({
      history: [],
    });
    //清空缓存
    wx.removeStorage({
      key: "history_arr",
    });
  },
  //点击热门词出现在输入框里
  this_value: function (e) {
    this.setData({
      name_focus: true,
    });
    let value = e.currentTarget.dataset.text;
    wx.setStorageSync("inputval", value);
    this.setData(
      {
        input_value: value,
        search: "搜索",
        keydown_number: 1,
      },
      () => {
        this.searchTap();
      }
    );
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.setNavigationBarTitle({
      title: "搜索",
    });
    wx.getStorage({
      key: "history_arr",
      success: function (res) {
        that.setData({
          history: res.data,
        });
      },
    });
    that.getHotKeyword();
    this.setData({
      termQuery: {
        termindex: 9,
        searchOption: 9,
      },
    });
  },
  // 热门搜索
  getHotKeyword: function () {
    var that = this;
    masses.getSearchHotKeywords(
      baseUrl.merchantUrl + "/hot-keywords",
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        that.setData({
          hotKeywords: result,
        });
      },
      function (err) {
        wx.showToast({
          title: "失败",
        });
      }
    );
  },
  // 获取搜索结果
  getTerm: function (scroll = false) {
    if (this.data.termLoad) return;
    this.setData({
      termLoadEnd: false,
      termLoad: true,
    });
    let { hasMore, pagenum } = this.data;
    if (hasMore) {
      const lat = wx.getStorageSync("latitude");
      const lon = wx.getStorageSync("longitude");
      const inputdata = wx.getStorageSync("inputval");
      masses.getNear(
        baseUrl.waimaiUrl + "/search",
        {
          keyword: inputdata,
          lat: lat,
          lon: lon,
          pageNumber: ++pagenum,
          pageSize: this.data.pagesize,
          ...this.data.termQuery,
        },
        {},
        "加载中",
        (res) => {
          const { results, curPage, pageCount } = res;
          const { termlist } = this.data;

          this.setData(
            {
              pagenum,
              termlist: termlist.concat(results),
              hasMore: curPage !== pageCount,
              termLoadEnd: true,
              termLoad: false,
            },
            () => {
              wx.stopPullDownRefresh();
              scroll &&
                wx.pageScrollTo({
                  scrollTop: 0,
                });
            }
          );

          loadEnd(this);
        },
        (err) => {
          this.setData({
            termLoadEnd: true,
          });
          __FAIL_FN({
            res: err,
          });
          loadEnd(this);
        }
      );
    }
  },
  // 选择筛选条件 - 改
  sureSelectTermListener(e) {
    const detail = e.detail;
    let termQuery = {};
    if (detail) {
      if (detail.currentTarget !== undefined) {
        const termindex = detail.currentTarget.dataset.index;
        termQuery = {
          termindex,
          searchOption: termindex,
        };
      } else {
        for (var j = 0; j < detail.length; j++) {
          const { activeflag, startPrice, endPrice, discountnum } = detail[j];
          if (activeflag === "first") {
            termQuery = Object.assign({}, termQuery, {
              startPrice,
              endPrice,
              searchOption: 9,
            });
          }
          if (activeflag === "second") {
            termQuery = Object.assign({}, termQuery, {
              actOption: [discountnum],
              searchOption: 9,
            });
          }
        }
      }
    }
    termQuery = Object.assign(
      {},
      {
        searchOption: 9,
      },
      termQuery
    );
    this.setData(
      {
        pagenum: 0,
        termlist: [],
        hasMore: true,
        termLoad: false,
        termLoadEnd: true,
        termQuery,
      },
      () => {
        this.getTerm(true);
      }
    );
  },
  // 跳转商家门店
  jumpSaleroom: function (e) {
    var that = this;
    var storeid = e.currentTarget.dataset.storeid;
    wx.setStorageSync("storeid", storeid);
    wx.navigateTo({
      url: "../../store/pages/lunch/index",
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData(
      {
        pagenum: 0,
        termlist: [],
        hasMore: true,
        termLoad: false,
        termLoadEnd: true,
      },
      () => {
        this.getTerm();
      }
    );
  },
});
