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: {
    termlist: [],
    termindex: 9,
    datalist: [],
    words: "",
    search: "搜索",
    category: "",
    inpuVal: "",
    spatialData: {
      showtop: 1, //top的距离
    },
    termLoadEnd: false,
    // 筛选条件
    termindex: 9,
    pagenum: 0,
    pagesize: 10,
    hasMore: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(
      {
        category: options.category,
        termQuery: {
          termindex: 9,
          searchOption: 9,
        },
      },
      () => {
        this.getTerm();
      }
    );
  },

  inputValue: function (e) {
    this.setData({
      inpuVal: e.detail.value,
    });
    if (e.detail.cursor != 0) {
      this.setData({
        search: "搜索",
        keydown_number: 1,
      });
    } else {
      this.setData({
        search: "取消",
        keydown_number: 0,
      });
    }
    // 搜索为空时
    if (e.detail.value == "") {
      this.setData({
        searchflag: false,
      });
    }
  },
  searchTap: function () {
    // that.getDatas(that.data.category, that.data.inpuVal);
    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("取消");
    }
  },
  // 跳转商家门店
  jumpSaleroom: function (e) {
    var that = this;
    var storeid = e.currentTarget.dataset.storeid;
    wx.setStorageSync("storeid", storeid);
    wx.navigateTo({
      url: "../../store/pages/lunch/index",
    });
  },
  // 搜索
  toSearch: function () {
    var that = this;
    wx.navigateTo({
      url: "../../pages/hunt/hunt",
    });
  },
  // 选择筛选条件 - 改
  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);
      }
    );
  },
  // 获取附近门店
  getTerm(scroll = false) {
    if (this.data.termLoad) return;
    this.setData({
      termLoadEnd: false,
      termLoad: true,
    });
    let { hasMore, pagenum } = this.data;
    if (hasMore) {
      const { category } = this.data;
      let lat = wx.getStorageSync("latitude");
      let lon = wx.getStorageSync("longitude");
      masses.getNear(
        baseUrl.waimaiUrl + "/category",
        {
          category,
          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(
            {
              termlist: termlist.concat(results),
              hasMore: curPage !== pageCount,
              pagenum,
              termLoadEnd: true,
              termLoad: false,
            },
            () => {
              scroll &&
                wx.pageScrollTo({
                  scrollTop: 0,
                });
            }
          );
          loadEnd(this);
          wx.stopPullDownRefresh();
        },
        (err) => {
          this.setData({
            termLoadEnd: true,
          });
          __FAIL_FN({
            res: err,
          });
          loadEnd(this);
          wx.stopPullDownRefresh();
        }
      );
    }
  },
  // 触底加载
  onReachBottom: function () {
    //触底加载下一页
    this.getTerm();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData(
      {
        pagenum: 0,
        termlist: [],
        hasMore: true,
        termLoad: false,
        termLoadEnd: true,
        ...loadData,
      },
      () => {
        this.getTerm();
      }
    );
  },
});
