// const extConfig = tt.getExtConfigSync ? tt.getExtConfigSync() : {}
// let ifStoreApp = extConfig.attr.ifStoreApp;
// let businessSwitch = extConfig.attr.businessSwitch
// let mch_id = extConfig.attr.mchId
const navigationBarHeight = (getApp().statusBarHeight + 60) + "px"
const navigationBarHeight1 = (getApp().statusBarHeight + 50) + "px"
const Http = require("../utils/HttpBasics");
const imgurl = require("../utils/imgurl");
const config = require("../config/config");
const QR = require("../utils/memberqrcode.js");
const util = require("../utils/util");
const bgColor = require("../utils/bgColor.js")
let app = getApp();
Page({
  data: {
    userAvatarUrl: '',
    userName: '',
    // aa: (app.statusBarHeight + 60) + "rpx",
    noDataFlag: false,
    busineKye: 0,
    businePageNum: 1,
    credit: 0,
    businessList: [], //优选好物导航
    businessData: [], //优选好物数据
    topicObj2: null, //欢乐城首页限时抢购
    topicObj3: null, //欢乐城首页砍价
    topicObj4: null, //欢乐城首页拼团
    topicObj5: null, //欢乐城首页消费卡
    topicObj6: null, //欢乐城首页积分商城
    specialLsit: [], //欢乐城首页专题
    marketName: "", //商场名称
    mouldType: null,
    navLineHeight: ((app.statusBarHeight + app.statusBarHeight) + 50) + "px",
    navImgHeight: (((app.statusBarHeight + app.statusBarHeight) + 34) / 2) + "px",
    huanlechengImgurl: "https://formall.oss-accelerate.aliyuncs.com/cimg/v20211214/",
    // mch_id: mch_id,
    goUrl: "", //商圈跳转链接
    accreditFlag: 1, //1是未授权微信且未授权手机号 2授权了微信 没授权手机号 3微信和手机号都授权了
    // businessSwitch: businessSwitch,
    typeLsit: {},
    showLocationIf: true,
    // ifStoreApp: ifStoreApp,
    navigationBarTitle: '首页',
    navigationBarHeight,
    navigationBarHeight1,
    chengzhangBox: bgColor.colorFirst.main.chengzhangBox,
    activeColor: bgColor.colorFirst.main.activeColor,
    qg: bgColor.colorFirst.main.qg,
    newUrl: "",
    cover: "",
    kanjia: imgurl.kanjia.url,
    pintuan: imgurl.pintuan.url,
    xiaofeika: imgurl.xiaofeika.url,
    xingyun: imgurl.xingyun.url,
    jfshangcheng: imgurl.jfshangcheng.url,
    toutiao: imgurl.toutiao.url,
    more: imgurl.more.url,
    giftHr: imgurl.giftHr.url,
    giftHr: imgurl.giftHr.url,
    next: imgurl.next.url,
    usergift: imgurl.usergift.url,
    guanbi1: imgurl.guanbi1.url,
    icon0001: imgurl.icon0001.url,
    icon0002: imgurl.icon0002.url,
    icon0003: imgurl.icon0003.url,
    icon0004: imgurl.icon0004.url,
    icon0005: imgurl.icon0005.url,
    icon0006: imgurl.icon0006.url,
    icon0007: imgurl.icon0007.url,
    icon0008: imgurl.icon0008.url,
    barcode: imgurl.barcode.url,
    leftarrows: imgurl.leftarrows.url,
    newcard: imgurl.newcard.url,
    newseckill: imgurl.newseckill.url,
    newbargain: imgurl.newbargain.url,
    newgroup: imgurl.newgroup.url,
    product: imgurl.product.url,
    barginicon: imgurl.barginicon.url,
    pintuan: imgurl.pintuan.url,
    live: imgurl.live.url,
    duihuan: imgurl.duihuan.url,
    market: app.globalData.market,
    list: [],
    xslist: [],
    loading: true,
    fistLogin: null,
    alphaData: null,
    alphaData1: null,
    swiperCurrent: 0,
    title: null,
    weappShareTitle: '', //分享标题
    weappShareCoverImg: '', //分享图片
    desc: null,
    scrollTop: 0,
    showGame: false,
    showTopic: false,
    showQg: false,
    gamedata: {},
    couponId: '', //游戏返回时传回的字段
    played: false, //从游戏页面跳回首页返回true
    havePlayEd: app.globalData.havePlayEd,
    havePlayEd1: app.globalData.havePlayEd1,
    staticGamedata: {},
    showIf: false,
    showPages: false,
    display: 'none',
    display1: 'none',
    optionsData: null,
    page: 1, // 刷新进入页面时已经加载了第一页数据，onReachBottom时 page++,从第2页开始加载
    openId: '',
    showGg: false,
    ggdata: {},
    liveFlag: 0, //直播按钮显隐标志位
    squareName: "", //当前广场
    isShowSqare: false,
    moduleList: [], //按钮列表
    currentMall: '富茂广场',
    shopList: [],
    mallTenantId: tt.getStorageSync('mallTenantId') || '',
    index: tt.getStorageSync('mallIndex') || 0,
    locateData: {},
    scanIn: false, // 扫码进入首页
    scanInTenantId: '',
    scene: ""
  },

  getCongig() { //获取小程序是否开通授权手机号
    Http.get({
      url: config.api.getConfig,
      data: {
        key: "douyinPhoneStatus"
      }
    }).then(res => {
      app.globalData.ifCongPh = res.data ? res.data : 1
    }).catch(err => {
      app.globalData.ifCongPh = 1
    })
  },

  mallSync() {
    this.setData({
      mallTenantId: tt.getStorageSync('mallTenantId') || '',
      index: tt.getStorageSync('mallIndex') || 0,
    })
  },

  getsubMallList() {
    Http.get({
      url: '/mall/subMall?isAll=1',
    }).then(res => {

      tt.setStorageSync('shopList', JSON.stringify(res.data));

      if (this.data.scanIn) {
        console.log('Over Here!!!!!!!!!!!!!!');
        let obj = {}
        let i = 0
        res.data.forEach((item, index) => {
          if (item.tenantId == this.data.scanInTenantId) {
            obj = item
            i = index
            return
          }
        })
        console.log(obj, 'obj');
        this.setData({
          shopList: res.data,
          mallTenantId: obj.tenantId,
          index: i
        });
        tt.setStorageSync('mallTenantId', obj.tenantId)
        tt.setStorageSync('mallIndex', i)

      } else {
        console.log('IIIOver Here!!!!!!!!!!!!!!');
        this.setData({
          shopList: res.data,
          mallTenantId: tt.getStorageSync('mallTenantId') || res.data[0].tenantId
        });
        if (!tt.getStorageSync('mallTenantId') && res.data.length > 1) {
          tt.setStorageSync('mallTenantId', res.data[0].tenantId)
          tt.setStorageSync('mallIndex', 0)
        }
        const locationSwitch = tt.getStorageSync('locationSwitch');
        if (locationSwitch) {
          this.getLocation()
        }
      }

    }).catch(err => {
      console.log(err, 'err');
    })
  },

  bindPickerChange(e, indexIn, id) {
    const index = e ? e.detail.value : indexIn

    const mallTenantId = id || this.data.shopList[index].tenantId
    tt.setStorageSync('mallTenantId', mallTenantId)
    tt.setStorageSync('mallIndex', index)
    this.setData({
      index: index,
      mallTenantId: mallTenantId,
      businePageNum: 1, // 切换广场后将页码切换至1
      noDataFlag: false
    });
    this.getBannerlist();
    this.getBusinessList()
    this.getCouponChannelList(this.data.busineKye)
  },

  getBusineData(e) {
    this.setData({
      businePageNum: 1,
      busineKye: e.detail,
      noDataFlag: false,
    })
    this.getCouponChannelList(e.detail)
  },
  getBusinessList() { //获取优选导航
    Http.get({
      url: config.api.businessList,
      data: {
        filter: 2,
        mallTenantId: this.data.mallTenantId || this.data.scanInTenantId || "",
      }
    }).then(res => {
      this.setData({
        businessList: [{
          id: 0,
          title: "全部",
          type: 1
        }].concat(res.data)
      });
    }).catch(err => {
      tt.showModal({
        title: '提示',
        content: err.message ? err.message : err.data,
        showCancel: false
      })
    })
  },
  getCouponChannelList(key) {
    const that = this
    if (that.data.noDataFlag) {
      return
    }
    tt.showLoading({
      title: "加载中"
    });
    let param = {}
    if (key == 0) {
      param = {
        pageNum: that.data.businePageNum,
        pageSize: 6,
        targetAd: 101,
        mallTenantId: tt.getStorageSync('mallTenantId') || that.data.scanInTenantId || ""
      }
    } else {
      param = {
        pageNum: that.data.businePageNum,
        pageSize: 6,
        business: key,
        targetAd: 101,
        mallTenantId: tt.getStorageSync('mallTenantId') || that.data.scanInTenantId || ""
      }
    }

    Http.get({
      url: config.api.couponChannelList,
      data: param
    }).then(res => {

      if (res.data.list && res.data.list.length != 0) {
        let tempLsit = that.data.businessData

        let data = res.data.list
        data.map(item => {
          if (item.salePriceStr && item.salePriceStr.indexOf('.') != -1) {
            let str = item.salePriceStr.split('.')
            item.salePriceStrQ = str[0]
            item.salePriceStrH = str[1]
          }
          item.sale = item.inventory - item.remainInventory
        })

        if (that.data.businePageNum > 1) {
          that.setData({
            businessData: [...tempLsit, ...data]
          })
        } else {
          that.setData({
            businessData: data
          })
        }
      } else {
        that.setData({
          noDataFlag: true,
        })
      }
      tt.hideLoading();
      console.log(that.data.businessData, 'businessData');
    }).catch(err => {
      tt.hideLoading();
      tt.showModal({
        title: '提示',
        content: err.message ? err.message : err.data,
        showCancel: false
      })
    })
  },
  goPage(e) {
    let obj = e.currentTarget.dataset.obj
    console.log(obj, "obj")
    if (obj.linkType == 1) {
      if (obj.linkUrl == "/pages/game/index") {
        // this.gotogame()
      } else {

        tt.navigateTo({
          url: obj.linkUrl,

        })

      }
      //小程序内部跳转
    } else if (obj.linkType == 2) {
      //跳转到外部小程序
      tt.navigateToMiniProgram({
        appId: obj.outLinkAppid,
        path: obj.linkUrl ? obj.linkUrl : '',
        fail: err => {
          tt.showModal({
            title: '提示',
            content: err,
            showCancel: false
          })
        }
      })
    }
  },
  //获取按钮列表
  getModule() {
    Http.get({
      url: config.api.wxCustomizeModule
    }).then(res => {
      this.setData({
        moduleList: res.data,
      })
    }).catch(err => {
      if (err.status != 404)
        tt.showModal({
          title: '提示',
          content: err.message ? err.message : err.data,
          showCancel: false
        })
    })
  },
  //判断用户是否授权
  uesrInfo() {
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
      Http.get({
        url: config.api.checkPhoneStatus
      }).then(res => { //全部授权
        this.setData({
          accreditFlag: 3
        })
      }).catch(err => {
        if (err.code == 11005) { //未授权手机号
          this.setData({
            accreditFlag: 2
          })
        } else {
          tt.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
    }).catch(err => {
      if (err.code == 11004) { //未授权微信
        this.setData({
          accreditFlag: 1
        })
      } else {
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      }
    })
  },

  //获取当前广场名
  //跳转到每日签到
  goSign() {
    tt.navigateTo({
      url: '/pages/activityCalendar/activityCalendar',
    })
  },
  //活动日历
  goCalendar() {
    tt.navigateTo({
      url: '/pages/dateLsit/dateLsit',
    })
  },
  //跳转到其他广场列表
  goSquareList() {
    if (this.data.isShowSqare) {
      tt.navigateTo({
        url: '/pages/location/location',
      })
    }

  },
  goLive() {
    tt.navigateTo({
      url: '/pages2/live/livelist/index',
    })
  },
  alphaClick1: function (even) {
    var animation = tt.createAnimation({})
    animation.opacity(0).step({
      duration: 2000
    })
    this.setData({
      alphaData: animation.export()
    })
  },
  alphaClick: function (even) {
    var animation = tt.createAnimation({})
    animation.opacity(0).step({
      duration: 2000
    })
    this.setData({
      alphaData1: animation.export()
    })
  },
  // 我的卡包
  mycard: function () {
    tt.navigateTo({
      url: '/pages/cardorder/index/index',
    })
  },
  //我的券包
  mycoupon: function () {
    tt.navigateTo({
      url: '/pages/couponorder/index/index',
    })
  },
  gotoSpellGroup: function () {
    tt.navigateTo({
      url: '/pages/spellGroup/spellGroup',
    })
  },
  qrcode: function () {
    var that = this;
    let memberId = that.data.memberId;
    if (memberId) {
      tt.navigateTo({
        url: '/pages/specialcourtesy/specialcourtesy'
      })
    }
  },
  //跳往限时秒杀
  gotoRushBuy: function () {
    tt.navigateTo({
      url: '/pages/rushToBuy/index',
    })
  },
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    });
  },
  gotogame: function () {
    let that = this;
    if (!that.data.showIf) {
      tt.showToast({
        title: '暂无游戏频道',
        icon: "none",
        duration: 3000
      })
    } else {
      Http.get({
        url: config.api.checkUserStatus,
        data: {
          token: app.globalData.token
        }
      }).then(res1 => {
        app.globalData.type = 'gm'
        Http.get({
          url: config.api.checkPhoneStatus,
          data: {}
        }).then(res => {
          var data = {
            couponChannelId: "" + that.data.couponChannelId,
            couponId: "" + that.data.couponId
          };
          if (that.data.couponChannelId == null) {
            var data = {
              couponId: "" + that.data.couponId
            };
          }
          tt.redirectTo({
            url: '/pages/game/index?url=' + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
          })
        }).catch(err => {
          if (err.code == 11005) {
            // 用户手机未授权
            /**
             * 将值传到用户手机号授权的页面
             *
             */
            app.globalData.skipUrl = '/pages/game/index?url=' + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
              app.globalData.skip = 'redirectTo'
            tt.redirectTo({
              url: "/pages/getphoneInfo/index?path=index&url=" + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
            });
          } else if (err.code == 11006) {
            // 用户手机已加密
            tt.redirectTo({
              url: "/pages/phoneinput/phoneinput?path=index&url=" + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
            });
          } else {
            tt.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000,
              mask: false
            });
          }
        })
      }).catch(err => {
        if (err.code == 11004) { //未授权微信
          app.globalData.type = 'gm'
          tt.redirectTo({
            url: "/pages/getuserinfo/index?path=index&url=" + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
          });
        } else {
          tt.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })

    }

  },
  mySpecial: function () {
    console.log("special");
    tt.navigateTo({
      url: '/pages/specialcourtesy/specialcourtesy',
    })
  },
  //是否属于集团
  ifShowSqare() {
    if (tt.getStorageSync("squareList")) {
      this.setData({
        isShowSqare: true
      })
    } else {
      this.setData({
        isShowSqare: false
      })
    }
  },
  /**
   * 获取全局样式
   */
  getType() {
    Http.get({
      url: config.api.setType,
      data: {
        mouldType: app.globalData.mouldType
      }
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code == 200) {
        app.globalData.typeLsit = data
        this.setData({
          typeLsit: data,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad: function (options) {
    console.log(options, 'options');
    let that = this;
    let optionss;

    const locationSwitch = options.type || ''
    tt.setStorageSync('locationSwitch', locationSwitch);

    if (options.tenantId) {
      that.setData({
        scanIn: true,
        scanInTenantId: options.tenantId
      })
      console.log(that.data.scanInTenantId, 'scanInTenantId');
    }

    let openId = tt.getStorageSync('openId')
    if (tt.getStorageSync('options')) {
      optionss = JSON.parse(tt.getStorageSync('options'));
    }
    if (options.played == "true") {
      that.setData({
        played: true
      })
    }
    if (optionss && optionss.couponChannelId || optionss && optionss.orderId) {
      that.setData({
        optionsData: optionss
      })
      that.getWeapNote(optionss.couponChannelId, optionss.orderId);
    } else {
      that.getWeapNote()
    }
    //获取条形码
    // util.barcode("barcode", optionss.quancode, 510, 100);
    // console.log(Http.headers.token, "?")
  },
  /**
   * 获得经纬度
   */
  getLocation() {
    console.log('getLocation');
    let that = this;
    tt.getLocation({
      type: "wgs84",
      // isHighAccuracy: true,
      success: function (res) {
        console.log(res, 'getLocation')

        const locateData = {
          latitude: res.latitude,
          longitude: res.longitude,
        }
        that.setData({
          locateData: locateData
        })
        if (res && res.longitude && res.latitude) {
          Http.post({
            url: config.api.updateLBS,
            data: {
              latitude: res.latitude,
              longitude: res.longitude,
              city: res.city
            }
          }).then(res => {
            // 获取到的用户的坐标
            const latitudeNow = that.data.locateData.latitude
            const longitudeNow = that.data.locateData.longitude

            const mallLocationArr = []

            const shopList = JSON.parse(tt.getStorageSync('shopList'));

            shopList.forEach((item, index) => {
              const obj = {
                latitude: item.latitude,
                longitude: item.longitude,
                mallTenantId: item.tenantId,
                index: index
              }
              mallLocationArr.push(obj)
            })

            console.log(mallLocationArr, 'mallLocationArr');

            const tempArr = shopList
            const bloobArr = []

            // 调整广场列表数据
            mallLocationArr.forEach((item, index) => {
              const distanceData = that.getDistances(latitudeNow, longitudeNow, item.latitude, item.longitude)
              tempArr[index].distance_str = distanceData.distance_str
              tempArr[index].distanceName = tempArr[index].name + ' ' + distanceData.distance_str
              tempArr[index].distance = distanceData.distance
              bloobArr.push(distanceData.distance)
            })
            that.setData({
              shopList: tempArr
            })

            // 通过排序获取最近广场
            const nearestDistance = that.bloob(bloobArr)[0]
            const nearestArr = that.data.shopList.filter((item, index) => {
              // 切换至最近的广场
              const locationFlag = tt.getStorageSync('locationFlag');
              if ((item.distance == nearestDistance)) {
                if (locationFlag) {
                  that.bindPickerChange('', index, item.tenantId)
                  tt.setStorageSync('locationFlag', false);
                } else {
                  that.bindPickerChange('', tt.getStorageSync('mallIndex'), tt.getStorageSync('mallTenantId'))
                }

                return true
              } else {

                return false
              }
            })
            console.log(nearestArr[0], 'nearestArr');

          })
        }
      },
      // 拒绝提供定位权限
      fail: error => {
        console.log(error);
        const shopList = JSON.parse(tt.getStorageSync('shopList'));
        let obj = {}
        shopList.forEach((item, index) => {
          if (item.defaultSign == 1) {
            const tempObj = {
              index: index,
              tenantId: item.tenantId
            }
            obj = tempObj
            return
          }
        })
        console.log(obj, 'obj');
        const locationFlag = tt.getStorageSync('locationFlag');
        if (locationFlag) {
          that.bindPickerChange('', obj.index, obj.tenantId)
          tt.setStorageSync('locationFlag', false);
        } else {
          that.bindPickerChange('', tt.getStorageSync('mallIndex'), tt.getStorageSync('mallTenantId'))
        }
      },
      complete: finish => {

      }
    })

  },

  /**
   * @description:根据经纬度计算距离
   * @param {*} locationInfo (lat1, lng1, lat2, lng2)
   * @return: distanceObj: { distance , distance_str }
   */
  getDistances(lat1, lng1, lat2, lng2) {
    function rad(num) {
      return num * Math.PI / 180.0;
    }
    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    var a = radLat1 - radLat2;
    var b = rad(lng1) - rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
      distance_str = distance.toFixed(2) + "km";
    } else if (!arseInt(distance)) {
      return false
    } else {
      distance_str = (distance * 1000).toFixed(2) + "m";
    }

    let objData = {
      distance: distance,
      distance_str: distance_str
    }
    return objData
  },

  bloob(arr) {
    const tempArr = arr
    for (let i = 0; i < tempArr.length - 1; i++) {
      for (let j = 0; j < tempArr.length - 1 - i; j++) {
        if (tempArr[j] > tempArr[j + 1]) {
          let temp = tempArr[j];
          tempArr[j] = tempArr[j + 1];
          tempArr[j + 1] = temp;
        }
      }
    }
    return tempArr
  },


  onShow: function () {

    this.mallSync()
    console.log(app.globalData.mouldType, "mouldType")
    // tt.requestSubscribeMessage({
    //   tmplIds: [], // 需要填入开放平台申请的模版id，支持最多3个同类型模版
    //   success(res) {
    //     //订阅成功
    //     console.log("订阅成功", res);
    //   },
    //   fail(error) {
    //     //订阅失败
    //     console.log("订阅失败, 错误详情: ", error);
    //     tt.showToast({
    //       title: "订阅失败",
    //       icon: "fail",
    //     });
    //   },
    //   complete(res) {
    //     //订阅完成
    //     console.log("tt.requestSubscribeMessage API调用完成: ", res);
    //   },
    // });

    this.setData({
      mouldType: app.globalData.mouldType,
      marketName: app.globalData.marketName,
      activeColor: app.globalData.mouldType == 1 ? "#E9D0AA" : bgColor.colorFirst.main.activeColor
    })
    // this.uesrInfo()
    this.ifShowSqare();
    if (tt.getStorageSync("squareList") && tt.getStorageSync("selectedMall")) {
      // var temp = tt.getStorageSync("squareList").filter(item => item.tenantId == tt.getStorageSync("selectedMall"))[0].name
      // this.setData({
      //   squareName: temp
      // })
    }
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,
      })
    }
    let that = this;
    that.setData({
      havePlayEd: app.globalData.havePlayEd ? app.globalData.havePlayEd : false,
      havePlayEd1: app.globalData.havePlayEd1 ? app.globalData.havePlayEd1 : false
    })

    /**
     * couponNum  是否有普通的优惠券购买
     * couponNum2 是否有新买的消费卡
     */
    let num = tt.getStorageSync('couponNum');
    let num1 = tt.getStorageSync('couponNum2');

    // if (num == 'couponNum' || num1 == 'couponNum2') {
    //   tt.showTabBarRedDot({
    //     index: 3
    //   })
    // } else {
    //   tt.hideTabBarRedDot({
    //     index: 3
    //   })
    // }

    if (app.globalData.score) {
      that.setData({
        fistLogin: app.globalData.score
      })
    }
    // 如果有游戏
    setTimeout(function () {
      that.alphaClick();
    }, 8000)
    // 如果有广告 
    setTimeout(function () {
      that.alphaClick1();
    }, 8000)

    setTimeout(() => {
      that.getBannerlist();
      that.getBusinessList()
      that.getCouponChannelList(that.data.busineKye)
    }, 2000)

  },


  getmemberId: function (token) {
    let that = this;
    Http.get({
        url: config.api.getScore,
        data: {
          token: token
        }
      }).then(res => {
        if (res.data.avatarUrl || res.data.nickName) {
          app.globalData.avatarUrl = res.data.avatarUrl
          app.globalData.nickName = res.data.nickName
        }
        that.setData({
          levelName: res.data.levelName,
          upgradePercent: res.data.upgradePercent,
          upgradeScore: res.data.upgradeScore,
          memberId: res.data.id,
          credit: res.data.credit,
          userAvatarUrl: res.data.avatarUrl ? res.data.avatarUrl : '',
          userName: res.data.nickName ? res.data.nickName : '',
        })
      })
      .catch(err => {
        tt.showModal({
          title: '提示',
          content: err.message,
          showCancel: false
        })
      })
  },
  gotoChengzhangzhi: function () {
    tt.navigateTo({
      url: '/pages/czdetail/czdetail',
    })
  },
  goIntegralmall() {
    tt.navigateTo({
      url: '/pages/integralmall/index',
    })
  },
  gotoBargain: function () {
    tt.navigateTo({
      url: '/pages/bargain/bargain',
    })
  },
  gotoSpellGroup: function () {
    tt.navigateTo({
      url: '/pages/spellGroup/spellGroup',
    })
  },
  gotoCard: function () {
    tt.navigateTo({
      url: '/pages/discountCardList/discountCardList',
    })
  },
  // gotoGame: function () {
  //   tt.navigateTo({
  //     url: '/pages/game/index',
  //   })
  // },
  gotoJfsc: function () {
    tt.navigateTo({
      url: '/pages/integralmall/index',
    })
  },

  /**
   * 
   * @param {code,page} 
   * 子组件向父组件传值 
   */
  onGetCode: function (e) {
    this.setData({
      code: e.detail.val,
      page: e.detail.pageNum,
    });
    console.log(e.detail.val)
    console.log(e.detail.pageNum)
  },
  getWeapNote: function (couponChannelId, couponId, orderId) {
    var that = this;

    if (app.globalData.token) {
      that.getsubMallList()
      // 登录
      console.log(app.globalData.token)
      that.getCongig() //获取小程序是否开通授权手机号
      that.setData({
        mouldType: app.globalData.mouldType,
        marketName: app.globalData.marketName,
        activeColor: app.globalData.mouldType == 1 ? "#E9D0AA" : bgColor.colorFirst.main.activeColor
      })

      //获取首页按钮 抖音暂时屏蔽
      // that.getModule()

      that.getmemberId(app.globalData.token);
      that.getBannerlist();
      // if (that.data.mouldType == 0) { //富茂原版
      //   that.topicShow();
      //   that.getxsList();
      // } else if (that.data.mouldType == 1) { //欢乐城模板
      // }
      that.getShowList()
      that.topicShowall(2);
      that.topicShowall(3);
      that.topicShowall(4);
      that.topicShowall(5);
      that.topicShowall(6);
      that.getBusinessList();
      that.getCouponChannelList(0)
      that.getsubMallList()

      that.getType()
      that.uesrInfo()
      // that.getLocation();
      that.getMallInfo(app.globalData.token);

      if (app.couponChannelListCallback) {
        app.couponChannelListCallback(app.globalData.token);
      }
      if (app.couponListCallback) {
        app.couponListCallback(app.globalData.token);
      }
      if (app.businessListCallback) {
        app.businessListCallback(app.globalData.token);
      }
      Http.get({
          url: config.api.getWeapNote,
          data: {
            appId: app.globalData.appId,
          }
        })
        .then(res => {
          console.log(33333333333)
          console.log(app.globalData.token)
          console.log(res)
          console.log(33333333333)
          // that.getGameOne(app.globalData.token)
          // that.getStaticGame(app.globalData.token)
          that.getGg(app.globalData.token)
          let weapNote = JSON.parse(res.data.weapNote);
          that.setData({
            // desc: weapNote.firstpage.desc?weapNote.firstpage.desc:"",
            // title: weapNote.firstpage.title?weapNote.firstpage.title:'',
          })
        })
        .catch(err => {
          // that.getGameOne(app.globalData.token)
          // that.getStaticGame(app.globalData.token)
          that.getGg(app.globalData.token)
          tt.showModal({
            title: "提示",
            content: err.message,
            showCancel: false
          });
        });

    } else {
      app.tokenCallback = token => {
        that.getsubMallList()
        // 登录
        console.log(app.globalData.token)
        that.getCongig() //获取小程序是否开通授权手机号
        that.setData({
          mouldType: app.globalData.mouldType,
          marketName: app.globalData.marketName,
          activeColor: app.globalData.mouldType == 1 ? "#E9D0AA" : bgColor.colorFirst.main.activeColor
        })
        //获取首页按钮  抖音暂时屏蔽
        // that.getModule()
        that.getmemberId(app.globalData.token);
        that.getBannerlist();
        // if (that.data.mouldType == 0) { //富茂原版
        //   that.topicShow();
        //   that.getxsList();
        // } else if (that.data.mouldType == 1) { //欢乐城模板
        // }
        that.getShowList()
        that.topicShowall(2);
        that.topicShowall(3);
        that.topicShowall(4);
        that.topicShowall(5);
        that.topicShowall(6);
        that.getBusinessList();

        that.getCouponChannelList(0)
        that.getType()
        that.uesrInfo()
        // that.getLocation();
        that.getMallInfo(app.globalData.token);
        if (app.couponChannelListCallback) {
          app.couponChannelListCallback(app.globalData.token);
        }
        if (app.couponListCallback) {
          app.couponListCallback(app.globalData.token);
        }
        if (app.businessListCallback) {
          app.businessListCallback(app.globalData.token);
        }

        Http.get({
            url: config.api.getWeapNote,
            data: {
              appId: app.globalData.appId,
            }
          })
          .then(res => {
            console.log(33333333333)
            console.log(app.globalData.token)
            console.log(res)
            console.log(33333333333)
            // that.getGameOne(app.globalData.token)
            // that.getStaticGame(app.globalData.token)
            that.getGg(app.globalData.token)
            let weapNote = JSON.parse(res.data.weapNote);
            that.setData({
              // desc: weapNote.firstpage.desc?weapNote.firstpage.desc:"",
              // title: weapNote.firstpage.title?weapNote.firstpage.title:'',
            })
          })
          .catch(err => {
            // that.getGameOne(app.globalData.token)
            // that.getStaticGame(app.globalData.token)
            that.getGg(app.globalData.token)
            tt.showModal({
              title: "提示",
              content: err.message,
              showCancel: false
            });
          });
      }
    }

  },

  getStaticGame(token) {
    let _this = this;
    Http.get({
        url: config.api.getGame,
        data: {
          triggleAction: 2, // 固定入口
          token: token
        }
      }).then(res => {
        if (res.data.id) {
          _this.setData({
            showIf: true,
            newUrl: res.data.imgUrl
          })
        } else {
          _this.setData({
            showIf: false
          })
        }
        _this.setData({
          staticGamedata: res.data
        })
      })
      .catch(err => {
        _this.setData({
          showIf: false
        })
        console.log(err)
      })
  },
  getGameOne: function (token) {
    let _this = this;
    Http.get({
        url: config.api.getGame,
        data: {
          triggleAction: 1, // 登录触发
          token: token
        }
      }).then(res => {
        if (res.data.id) {
          _this.setData({
            showGame: true,
          })
        } else {
          _this.setData({
            showGame: false
          })
        }
        _this.setData({
          gamedata: res.data
        })
      })
      .catch(err => {
        _this.setData({
          showGame: false
        })
        this.alphaClick();
      })
  },
  /**
   * mallinfo
   */
  getMallInfo: function (token) {
    let that = this;
    Http.get({
        url: config.api.getMallInfo,
        data: {
          token: token,
        }
      }).then(res => {
        that.setData({
          liveFlag: res.data.liveSupport,
          weappShareTitle: res.data.weappShareTitle ? res.data.weappShareTitle : null,
          weappShareCoverImg: res.data.weappShareCoverImg ? res.data.weappShareCoverImg : null,
        });
        console.log(that.data.liveFlag, "||||")
      })
      .catch(err => {
        // 不需要错误提示
      });
  },
  //获取限时抢购列表
  getxsList() {
    let that = this;
    Http.get({
        url: config.api.couponChannelList,
        data: {
          pageNum: 1,
          pageSize: 3,
          targetAd: 2
        }
      }).then(res => {
        if (res && res.data.total > 0) {
          that.setData({
            xslist: res.data.list,
            showQg: true
          });
        } else {
          that.setData({
            showQg: false
          })
        }
      })
      .catch(err => {
        console.log(err)
        tt.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      })
  },
  /**
   * banner
   */
  getBannerlist: function () {
    let that = this;
    Http.get({
        url: config.api.bannerlist,
        data: {
          pageNum: 1,
          pageSize: 7,
          plat: 3,
          mallTenantId: tt.getStorageSync('mallTenantId') || that.data.scanInTenantId || ""
        }
      }).then(res => {
        that.getmemberId(app.globalData.token);
        // that.checkUserCarStatus();
        that.setData({
          list: res.data.list
        });
      })
      .catch(err => {
        that.getmemberId(app.globalData.token);
        // that.checkUserCarStatus();
      });
  },
  //获取欢乐城专题
  getShowList() {
    Http.get({
      url: config.api.showList
    }).then(res => {
      let tempData = res.data
      tempData.map(item1 => {
        if (item1.couponList) {
          item1.couponList.map(item2 => {
            if (item2.salePriceStr && item2.salePriceStr.indexOf('.') != -1) {
              let str = item2.salePriceStr.split('.')
              item2.salePriceStrQ = str[0]
              item2.salePriceStrH = str[1]
            }
          })
        }

      })
      this.setData({
        specialLsit: res.data ? res.data : []

      })
    }).catch(err => {
      tt.showToast({
        title: err.message ? err.message : err.data,
        icon: 'none',
        duration: 2000,
        mask: false
      });
    })
  },
  /**
   * topicType=2 限时抢购
   * topicType=3 砍价
   * topicType=4 拼团
   * topicType=5 消费卡
   * topicType=6 积分商城
   */
  topicShowall(topicType) {
    Http.get({
      url: config.api.topicShow,
      data: {
        topicType
      }
    }).then(res => {

      let data = res.data

      if (data.couponList != null && data.couponList.length > 0) {
        data.couponList.map(item => {
          if (item.salePriceStr && item.salePriceStr.indexOf('.') != -1) {
            let str = item.salePriceStr.split('.')
            item.salePriceStrQ = str[0]
            item.salePriceStrH = str[1]
          }
        })
      }

      if (topicType == 2) {
        let tempData = data
        this.setData({
          topicObj2: data
        })
      } else if (topicType == 3) {
        this.setData({
          topicObj3: data
        })
      } else if (topicType == 4) {
        this.setData({
          topicObj4: data
        })
      } else if (topicType == 5) {
        this.setData({
          topicObj5: data
        })
      } else if (topicType == 6) {
        this.setData({
          topicObj6: data
        })
      }

    }).catch(err => {
      tt.showToast({
        title: err.message ? err.message : err.data,
        icon: 'none',
        duration: 2000,
        mask: false
      });
    })
  },
  // 专题显示
  topicShow: function () {
    let that = this;
    Http.get({
        url: config.api.topicShow,
        data: {
          token: app.globalData.token
        }
      }).then(res => {
        if (res && res.data) {
          that.setData({
            name: res.data.name,
            cover: res.data.cover,
            id: res.data.id,
            showTopic: true
          })
        } else {
          that.setData({
            showTopic: false
          })
        }
      })
      .catch(err => {
        console.log(err);
      })
  },
  gotoTopic() {
    tt.navigateTo({
      url: `/pages/topicDetail/index?id=${this.data.id}`
    })
  },
  /**
   * 检查用户是否有车
   */
  // checkUserCarStatus: function() {
  //   var that = this;
  //   Http.get({
  //     url: config.api.userCarCount,
  //     data: {}
  //   }).then(res => {
  //     if (res.data > 0) {
  //       // 用户名下有车
  //       app.globalData.phone = res.data.phone;
  //       app.globalData.supportCar = true;
  //       // 共同登录
  //       that.userCarLogin();
  //     }
  //   });
  // },
  /**
   * car共同登录
   */
  // userCarLogin: function() {
  //   var that = this;
  //   if (!app.globalData.carLogin) {
  //     // 共同登录
  //     Http.post({
  //       url: config.api.carInit,
  //       data: {
  //         phone: app.globalData.phone
  //       }
  //     }).then(res => {
  //       app.globalData.carLogin = true;
  //       app.globalData.parkVendor = res.data.vendor;
  //       if (res.data.token != "undefined") {
  //         app.globalData.etcpToken = res.data.token;
  //       }
  //     });
  //   }
  // },
  /**
   * 获取用户信息
   */
  // getUserInfo: function() {
  //   // 获取用户信息
  //   tt.getSetting({
  //     success: res => {
  //       if (res.authSetting["scope.userInfo"]) {
  //         // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
  //         tt.getUserInfo({
  //           success: res => {
  //             // 可以将 res 发送给后台解码出 unionId
  //           }
  //         });
  //       }
  //     }
  //   });
  // },
  gotoBargain: function () {
    tt.navigateTo({
      url: '/pages/bargain/bargain'
    })
  },
  //限时抢购的详情页面
  gotodetail: function (e) {
    tt.navigateTo({
      url: `/pages/coupon/detail/index?couponChannelId=${e.currentTarget.dataset.couponchannelid
        }&couponId=${e.currentTarget.dataset.couponid}`
    });
  },
  //浮层广告
  getGg: function (token) {

    let that = this
    Http.get({
        url: config.api.getGg,
        data: {
          token: token,
          appId: app.globalData.appId,
          openId: "" // tt.getStorageSync('openId')
        }
      }).then(res => {
        console.log(res)
        if (res.data.id) {
          that.setData({
            showGg: true,
          })
          console.log(that.data.showGg, 1111111111111)
        } else {
          that.setData({
            showGg: false
          })
          // that.getGameOne(app.globalData.token)
          console.log(that.data.showGg, 222222222222222222)
        }
        that.setData({
          ggdata: res.data
        })
      })
      .catch(err => {
        this.setData({
          showGg: false
        })
        // that.getGameOne(app.globalData.token)
        that.alphaClick1();
      })
  },
  /**
   * 刷新
   */
  onPullDownRefresh() {
    tt.showLoading({
      title: "加载中..."
    });
    let that = this;
    // that.setData({
    //   topicObj2: null, //欢乐城首页限时抢购
    //   topicObj3: null, //欢乐城首页砍价
    //   topicObj4: null, //欢乐城首页拼团
    //   topicObj5: null, //欢乐城首页消费卡
    //   topicObj6: null, //欢乐城首页积分商城
    //   specialLsit: null, //专题
    // })
    // // that.getWeapNote();
    that.setData({
      page: 1,
      businePageNum: 1,
      noDataFlag: false
    })
    // if (that.data.optionsData != null && (that.data.optionsData.couponChannelId || that.data.optionsData.orderId)) {
    //   that.getWeapNote(that.data.optionsData.couponChannelId, that.data.optionsData.orderId);
    // } else {
    //   that.getWeapNote()
    // }
    // if (that.selectComponent("#lists")) {
    //   if (that.data.code == 0 || that.data.code == undefined) {
    //     that.selectComponent("#lists").getList(0, 1, "refresh");
    //     tt.stopPullDownRefresh();
    //   } else {
    //     that.selectComponent("#lists").getList(that.data.code, 1, "refresh");
    //     tt.stopPullDownRefresh();
    //   };
    //   that.selectComponent("#hot").getList();
    // }

    // // 砍价下拉刷新
    // // that.selectComponent("#bargain").getList();
    // // that.selectComponent("#spellGroup").getList();
    // // that.selectComponent("#rushtobyCard").getList();

    // // 爆款专区下拉刷新

    // that.getxsList();
    // that.topicShow();

    this.getBannerlist();
    this.getBusinessList()
    this.getCouponChannelList(this.data.busineKye)

    setTimeout(() => {
      tt.hideLoading();
      tt.stopPullDownRefresh();
    }, 1600);

  },
  //加载更多
  onReachBottom: function () {
    console.log("我到底了")
    let that = this;
    that.data.page++;
    that.setData({
      page: that.data.page,
      businePageNum: that.data.businePageNum + 1
    });
    console.log("加载更多页数" + that.data.page, );
    console.log("加载更多key" + that.data.code);
    // if (that.data.mouldType == 0) { //富茂源模板
    //   //父组件获得子组件的方法
    //   //如果code == 0
    //   if (that.data.code == 0 || that.data.code == undefined) {
    //     that.selectComponent("#lists").getList(0, that.data.page);
    //   } else {
    //     that.selectComponent("#lists").getList(that.data.code, that.data.page);
    //   }
    // } else if (that.data.mouldType == 1) {
    // }
    this.getCouponChannelList(that.data.busineKye)

  },
  // 用户点击右上角分享
  onShareAppMessage: function () {
    app.globalData.previewFlag = true
    return {
      path: "/pages/index/index",
      title: this.data.weappShareTitle,
      imageUrl: this.data.weappShareCoverImg,
      success: function (res) {
        tt.showToast({
          title: "分享成功",
          duration: 1000,
          icon: "success"
        });
      }
    };
  }
});

Array.prototype.bubbleSort = function () {
  for (let i = 0; i < this.length - 1; i += 1) {
    for (let j = 0; j < this.length - 1 - i; j += 1) {
      if (this[j] > this[j + 1]) {
        const temp = this[j];
        this[j] = this[j + 1];
        this[j + 1] = temp;
      }
    }
  }
}