import { loadEnd, loadData } from "../../utils/index";
import { getShoppingCart, _GLOBAL_UI_DATA_KEY } from "../../utils/index";
import { __FAIL_FN } from "../../utils/network";
import { _ACTIVITY_INFO_KEY } from "../../utils/global-key";
const baseUrl = require("../../api/index.js").config;
const masses = require("../../api/masses.js");
const { onShareAppMessage, getHospitalAddress } = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 附近商家列表
    termlist: [],
    termindex: 9,
    termLoadEnd: false,
    // 轮播图
    bannerlist: [],
    // 分类
    catlist: [],
    totalcatg: [],
    // 美味精选
    carefullychosen: [],
    // 优质商家
    preferredmerchants: [],
    recommendlist: [],
    // 是否自动轮播
    autoflag: false,
    // 地址栏
    siteData: {
      showCapsule: 0, //是否显示左上角图标
      title: "", //导航栏 中间的标题
    },
    // 单品推荐
    singlelist: [],
    salesroomid: "",
    // 附近商家分页加载
    pagenum: 0,
    pagesize: 10,
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏
    searchLoadingComplete: false, //“没有数据”的变量，默认false，隐藏
    // 全局有多少个后端请求
    loadEndCount: 5,
    ...loadData,
    // 顶部的固定高度
    headerBoxHeight: 0,
    // 触底加载
    hasMore: true,
    // 顶部活动的高度
    activeBoxHeight: 0,
    // 页面高度
    windowHeight: 0,
    // 添加小程序
    // showAddBox: false,
    // 是否是从活动中跳转过来的
    isActityBack: false,
    // 首页特惠套餐数据
    preferentials: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.activeInfo = wx.getStorageSync(_ACTIVITY_INFO_KEY) || {};
    const isActityBack = !!this.activeInfo.groupid;
    // 查询 dom 实例
    this.query = wx.createSelectorQuery();
    // 初始化埋点统计
    this.setData({
      termQuery: {
        termindex: 9,
        searchOption: 9,
      },
      isActityBack,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    // 获取地理位置
    var that = this;
    try {
      const { addressTitle } = await getHospitalAddress();
      // 附近门店
      if (wx.getStorageSync("pagerefresh") == "agree") {
        that.setData(
          {
            "siteData.title": addressTitle,
            showplace: false,
            pagenum: 0,
            termlist: [],
            hasMore: true,
            termLoad: false,
            termLoadEnd: true,
            ...loadData,
          },
          () => {
            that.getAllData();
          }
        );
        wx.setStorageSync("pagerefresh", "");
      } else if (wx.getStorageSync("pagerefresh") == "lunchagree") {
        that.setData(
          {
            "siteData.title": addressTitle,
            showplace: false,
            // pagenum: 0,
            // termlist: [],
            hasMore: true,
            termLoad: false,
            termLoadEnd: true,
            ...loadData,
          },
          () => {
            that.getAllData();
          }
        );
        wx.setStorageSync("pagerefresh", "");
      } else {
        that.setData(
          {
            "siteData.title": addressTitle,
            hasMore: true,
            showplace: false,
          },
          () => {
            that.getAllData();
          }
        );
      }
    } catch (e) {
      that.setData({
        showplace: true,
      });
    }
  },

  // 页面准备完成
  onReady() {
    this.floatingWindow = this.selectComponent("#floating-window");
  },

  // 页面卸载
  onUnload() {
    wx.setStorageSync(_ACTIVITY_INFO_KEY, {});
  },

  /**
   * 请求多个接口
   */
  getAllData() {
    // 获取附近门店
    this.getTerm();
    // 获取轮播图
    this.getBanner();
    // 获取分类
    this.getCats();
    // 获取商家推荐
    this.getRecommends();
    // 获取单品推荐
    this.getSinglerecommend();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData(
      {
        pagenum: 0,
        termlist: [],
        hasMore: true,
        termLoad: false,
        termLoadEnd: true,
        ...loadData,
      },
      () => {
        this.getAllData();
      }
    );
  },

  // 触底加载
  onReachBottom: function () {
    //触底加载下一页
    this.getTerm();
  },

  toSearch: function () {
    wx.navigateTo({
      url: "../hunt/hunt",
    });
  },

  // 美味精选
  getSinglerecommend: function () {
    var that = this;
    masses.getSingleRecommends(
      baseUrl.waimaiUrl + "/single-recommends/foods",
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        var chunk = 3;
        var len = result.length;
        var test = [];
        for (let i = 0; i < len; i += chunk) {
          test.push(result.slice(i, i + chunk));
        }
        that.setData({
          singlelist: result,
          carefullychosen: test,
        });
        loadEnd(that);
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
        loadEnd(that);
      }
    );
  },

  // 优选商家
  getRecommends: function () {
    var that = this;
    let lat = wx.getStorageSync("latitude");
    let lon = wx.getStorageSync("longitude");
    masses.getRecommends(
      baseUrl.waimaiUrl + "/merchant-recommends/list",
      {
        lat: lat,
        lon: lon,
      },
      {},
      "加载中",
      function (res) {
        var result = res.results;
        var chunk = 4;
        var len = result.length;
        var test = [];
        for (let i = 0; i < len; i += chunk) {
          test.push(result.slice(i, i + chunk));
        }
        that.setData({
          recommendlist: result,
          preferredmerchants: test,
        });
        loadEnd(that);
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
        loadEnd(that);
      }
    );
  },
  // 商家分类
  getCats: function () {
    var that = this;
    masses.getCats(
      baseUrl.merchantUrl + "/categories/enable",
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        var chunk = 10;
        var len = result.length;
        var test = [];
        for (let i = 0; i < len; i += chunk) {
          test.push(result.slice(i, i + chunk));
        }
        that.setData(
          {
            catlist: result,
            totalcatg: test,
          },
          () => {
            loadEnd(that);
          }
        );
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
        loadEnd(that);
      }
    );
  },
  // banner图
  getBanner: function () {
    var that = this;
    masses.getBanner(
      baseUrl.merchantUrl + "/banners/enable",
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        that.setData({
          bannerlist: result,
        });
        loadEnd(that);
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
        loadEnd(that);
      }
    );
  },

  // 获取附近门店
  getTerm(scroll = false) {
    if (this.data.termLoad) return;
    this.setData({
      termLoadEnd: false,
      termLoad: true,
    });
    let { hasMore, pagenum } = this.data;
    if (hasMore) {
      let lat = wx.getStorageSync("latitude");
      let lon = wx.getStorageSync("longitude");
      let jumpType = wx.getStorageSync("jumpType");
      let sourceMerchantId = "";
      if (jumpType === "DETAIL") {
      } else {
        sourceMerchantId = wx.getStorageSync("sourceMerchantId");
      }
      masses.getNear(
        baseUrl.waimaiUrl + "/near",
        {
          lat: lat,
          lon: lon,
          pageNumber: ++pagenum,
          pageSize: this.data.pagesize,
          sourceMerchantId: sourceMerchantId,
          ...this.data.termQuery,
        },
        {},
        "加载中",
        (res) => {
          const { results, curPage, pageCount } = res;
          const { termlist } = this.data;
          //引流
          // wx.setStorageSync('sourceMerchantId', '')
          this.setData(
            {
              termlist: termlist.concat(results),
              hasMore: curPage !== pageCount,
              pagenum,
              termLoadEnd: true,
              termLoad: false,
            },
            () => {
              scroll &&
                wx.pageScrollTo({
                  scrollTop: this.nearbyScreenTop || 0,
                });
            }
          );
          // 购物车的数量
          for (var p = 0; p < this.data.termlist.length; p++) {
            let carts = getShoppingCart(
              `cart_${this.data.termlist[p].sellerId}_${this.data.termlist[p].id}`
            );
            this.data.termlist[p].cartnum = 0;
            if (carts) {
              for (var m = 0; m < carts.length; m++) {
                this.data.termlist[p].cartnum += carts[m].num;
              }
            }
          }
          this.setData({
            termlist: this.data.termlist,
          });
          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);
      }
    );
  },
  // 分类跳转
  takeCatg: function (e) {
    var that = this;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: "../../package/businessdisplay/businessdisplay?category=" + name,
    });
  },
  // 地理位置授权
  onCancel: function () {
    wx.navigateTo({
      url: "../../package/addressswitching/addressswitching",
    });
  },
  //授权设置引导
  onLook: function () {
    wx.openSetting({
      success: (res) => {},
    });
  },
  takeBuiness: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.merchantid;
    that.takeMerchantid(id);
    wx.setStorageSync("noid", "disagree");
  },
  jumpCart: function (e) {
    var that = this;
    const id = e.currentTarget.dataset.id;
    const foodid = e.currentTarget.dataset.foodtemplateid;
    const skuid = e.currentTarget.dataset.foodskutemplateid;
    that.takeMerchantid(id, foodid, skuid);
    wx.setStorageSync("noid", "agree");
  },
  jumpBanner: function (e) {
    var that = this;
    const type = e.currentTarget.dataset.type;
    const jumpcontext = e.currentTarget.dataset.jumpcontext;
    if (type == 1) {
      that.takeMerchantid(jumpcontext);
      wx.setStorageSync("noid", "disagree");
    } else if (type == 2) {
      /^\//.test(jumpcontext) &&
        wx.navigateTo({
          url: jumpcontext,
        });
    }
  },
  jumpSaleroom: function (e) {
    var storeid = e.currentTarget.dataset.storeid;
    let merchantid = e.currentTarget.dataset.merchantid;
    wx.setStorageSync("storeid", storeid);
    wx.setStorageSync("merchantid", merchantid);
    wx.setStorageSync("noid", "disagree");
    wx.navigateTo({
      url: "/store/pages/lunch/index",
    });
  },
  takeMerchantid: function (merchantid, foodid, skuid) {
    var that = this;
    const lat = wx.getStorageSync("latitude");
    const lon = wx.getStorageSync("longitude");
    masses.getMerchantid(
      baseUrl.waimaiUrl + "/merchants/" + merchantid,
      {
        lat: lat,
        lon: lon,
      },
      {},
      "加载中",
      function (res) {
        var result = res.results;
        if (result != null) {
          that.setData({
            salesroomid: result,
          });
          wx.setStorageSync("storeid", result);
          wx.setStorageSync("merchantid", merchantid);
          wx.navigateTo({
            url:
              "/store/pages/lunch/index?foodid=" + foodid + "&skuid=" + skuid,
          });
        } else {
        }
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
      }
    );
  },
  // 门店详情
  takeStoredetail: function (storeid) {
    var that = this;
    const lat = wx.getStorageSync("latitude");
    const lon = wx.getStorageSync("longitude");
    var merchantid = wx.getStorageSync("merchantid");
    masses.getFeedbackstore(
      baseUrl.waimaiUrl +
        "/client/merchants/" +
        merchantid +
        "/stores/" +
        storeid,
      {
        latitude: lat,
        longitude: lon,
      },
      {},
      "加载中",
      function (res) {
        var result = res.results;
        var splitbusiness = result.businessLicenseImgs.split(",");
        // var splithygienicLicense = result.hygienicLicenseImgs.split(",");
        var splitmanageLicense = result.manageLicenseImags.split(",");
        that.setData({
          order: result,
          businessLicenseImgs: splitbusiness,
          // hygienicLicenseImgs: splithygienicLicense,
          manageLicenseImags: splitmanageLicense,
          StarLevel: result.score,
        });
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
      }
    );
  },
  // 请求结束后的函数
  async loadEnd() {
    try {
      const { height: headerBoxHeight = 0 } = await wx.$queryStyles(
        "#header-box"
      );
      const { height: activeBoxHeight = 0 } = await wx.$queryStyles(
        "#active-box"
      );
      const { height: swiperHeight = 0 } = await wx.$queryStyles(
        "#swipergrid-0"
      );
      const { top: nearbyScreenTop = 0, height: nearbyScreenHeight = 0 } = await wx.$queryStyles(
        "#nearby-screen"
      );
      this.nearbyScreenTop = nearbyScreenTop - headerBoxHeight - nearbyScreenHeight;
      const { windowHeight } = wx.getSystemInfoSync();
      this.setData({
        headerBoxHeight,
        activeBoxHeight,
        windowHeight,
        swiperHeight,
      });
    } catch (e) {
      console.error("debug catch", e);
    }
  },
  // 置顶引流
  async getSource() {
    let source = wx.getStorageSync("source");
    let scene = "";
    if (source.scene === 1035) {
      scene = "WECHAT_MP";
    } else if (source.scene === 1005) {
      scene = "SEARCH";
    } else if (source.scene === 1044) {
      scene = "SHARE";
    } else if (source.scene === 1047) {
      scene = "SCAN";
    } else if (source.scene === 1089) {
      scene = "DROP_DOWN";
    } else {
      scene = "OTHER";
    }
    let lat = wx.getStorageSync("latitude");
    let lon = wx.getStorageSync("longitude");
    masses.getSource(
      `${baseUrl.waimaiUrl}/merchants-help-each-other/enter`,
      {},
      {
        lat: lat,
        lon: lon,
        enterType: scene,
        merchantName: source.query.merchantName,
      },
      "加载中",
      function (res) {
        var result = res.results;
        var splitbusiness = result.businessLicenseImgs.split(",");
        // var splithygienicLicense = result.hygienicLicenseImgs.split(",");
        var splitmanageLicense = result.manageLicenseImags.split(",");
        that.setData({
          order: result,
          businessLicenseImgs: splitbusiness,
          // hygienicLicenseImgs: splithygienicLicense,
          manageLicenseImags: splitmanageLicense,
          StarLevel: result.score,
        });
      },
      function (err) {
        __FAIL_FN({
          res: err,
        });
      }
    );
  },
  // 页面滑动
  onPageScroll() {
    if (!this.floatingWindow) return;

    if (this.scrollEndTimer) {
      this.onScrollStart();
      this.scrolling = true;
      clearTimeout(this.scrollEndTimer);
      this.scrollEndTimer = null;
    }

    this.scrollEndTimer = setTimeout(() => {
      this.scrolling = false;
      this.onScrollEnd();
    }, 300);
  },
  // 滑动开始
  onScrollStart() {
    if (this.scrolling) return;
    this.floatingWindow.hideWindow();
  },
  // 滑动结束
  onScrollEnd() {
    this.floatingWindow.showWindow();
  },
  // 分享
  onShareAppMessage,
  // 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
  onShareTimeline() {
    const title = "群友会专享";

    return {
      title,
      query: "",
      imageUrl: "",
    };
  },
});
