const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
console.log(extConfig, 'extConfig');
let ifStoreApp = extConfig.attr.ifStoreApp;
let businessSwitch = 1 * extConfig.attr.businessSwitch ? extConfig.attr.businessSwitch : false

if (businessSwitch) {
  var myPluginInterface = requirePlugin('auto-points-plugin')
  var businessVersion = 1 * extConfig.attr.businessVersion
}

let mch_id = extConfig.attr.mchId
const navigationBarHeight = (getApp().statusBarHeight + 44) + "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: {
    aa: (app.statusBarHeight + 34) + "rpx",
    noDataFlag: false,
    busineKye: 0,
    businePageNum: 1,
    credit: 0,
    businessList: [], //优选好物导航
    businessData: [], //优选好物数据
    topicObj2: null, //欢乐城首页限时抢购
    topicObj3: null, //欢乐城首页砍价
    topicObj4: null, //欢乐城首页拼团
    topicObj5: null, //欢乐城首页消费卡
    topicObj6: null, //欢乐城首页积分商城
    specialLsit: [], //欢乐城首页专题
    marketName: "", //商场名称
    mouldType: 0,
    navLineHeight: ((app.statusBarHeight + app.statusBarHeight) + 44) + "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,
    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: [], //按钮列表
    userAvatarUrl: "",
    userName: "",
    showPrivacy: false,
    isModalVisible: false,
  },
  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
      }
    }).then(res => {
      this.setData({
        businessList: [{
          id: 0,
          title: "全部",
          type: 1
        }].concat(res.data)
      });
    }).catch(err => {
      wx.showModal({
        title: '提示',
        content: err.message ? err.message : err.data,
        showCancel: false
      })
    })
  },

  // 2022年11月8日微信收回接口“wx.getUserProfile”、“wx.getUserInfo”之后，需要手动设置用户头像与昵称
  goSetAvatar() {
    const accreditFlag = this.data.accreditFlag
    // 没授权手机号
    if (accreditFlag == 2) {
      wx.navigateTo({
        url: '/pages/getphoneInfo/index?go="setUserInfo"'
      })
      // 手机号已授权
    } else {
      wx.navigateTo({
        url: '/pages3/setUserInfo/index',
      })
    }
  },

  getCouponChannelList(key) {
    if (this.data.noDataFlag) {
      return
    }
    wx.showLoading({
      title: "加载中"
    });
    let param = {}
    if (key == 0) {
      param = {
        pageNum: this.data.businePageNum,
        pageSize: 6,
        targetAd: 1
      }
    } else {
      param = {
        pageNum: this.data.businePageNum,
        pageSize: 6,
        business: key,
        targetAd: 1

      }
    }

    Http.get({
      url: config.api.couponChannelList,
      data: param
    }).then(res => {
      if (res.data.list && res.data.list.length != 0) {

        let tempLsit = this.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 (this.data.businePageNum > 1) {
          this.setData({
            businessData: [...tempLsit, ...data]
          })
        } else {
          this.setData({
            businessData: data
          })
        }
      } else {
        this.setData({
          noDataFlag: true
        })
      }
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      wx.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 {

        wx.navigateTo({
          url: obj.linkUrl,

        })

      }
      //小程序内部跳转
    } else if (obj.linkType == 2) {
      //跳转到外部小程序
      wx.navigateToMiniProgram({
        appId: obj.outLinkAppid,
        path: obj.linkUrl ? obj.linkUrl : '',
        fail: err => {
          wx.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)
        wx.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 {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })
    }).catch(err => {
      if (err.code == 11004) { //未授权微信
        this.setData({
          accreditFlag: 1
        })
      } else {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000,
          mask: false
        });
      }
    })
  },

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

  },
  goLive() {
    wx.navigateTo({
      url: '/pages2/live/livelist/index',
    })
  },
  alphaClick1: function (even) {
    var animation = wx.createAnimation({})
    animation.opacity(0).step({
      duration: 2000
    })
    this.setData({
      alphaData: animation.export()
    })
  },
  alphaClick: function (even) {
    var animation = wx.createAnimation({})
    animation.opacity(0).step({
      duration: 2000
    })
    this.setData({
      alphaData1: animation.export()
    })
  },
  // 我的卡包
  mycard: function () {
    wx.navigateTo({
      url: '/pages/cardorder/index/index',
    })
  },
  //我的券包
  mycoupon: function () {
    wx.navigateTo({
      url: '/pages/couponorder/index/index',
    })
  },
  gotoSpellGroup: function () {
    wx.navigateTo({
      url: '/pages/spellGroup/spellGroup',
    })
  },
  qrcode: function () {
    var that = this;
    let memberId = that.data.memberId;
    if (memberId) {
      wx.navigateTo({
        url: '/pages/specialcourtesy/specialcourtesy'
      })
    }
  },
  //跳往限时秒杀
  gotoRushBuy: function () {
    wx.navigateTo({
      url: '/pages/rushToBuy/index',
    })
  },
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    });
  },
  gotogame: function () {
    let that = this;
    if (!that.data.showIf) {
      wx.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
            };
          }
          wx.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'
            wx.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) {
            // 用户手机已加密
            wx.redirectTo({
              url: "/pages/phoneinput/phoneinput?path=index&url=" + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
            });
          } else {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000,
              mask: false
            });
          }
        })
      }).catch(err => {
        if (err.code == 11004) { //未授权微信
          app.globalData.type = 'gm'
          wx.redirectTo({
            url: "/pages/getuserinfo/index?path=index&url=" + that.data.staticGamedata.url + "&id=" + that.data.staticGamedata.id + "&gameId=" + that.data.staticGamedata.gameId,
          });
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000,
            mask: false
          });
        }
      })

    }

  },
  mySpecial: function () {
    console.log("special");
    wx.navigateTo({
      url: '/pages/specialcourtesy/specialcourtesy',
    })
  },
  //是否属于集团
  ifShowSqare() {
    if (wx.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) {
    this.setData({
      mouldType: app.globalData.mouldType,
      marketName: app.globalData.marketName,
      activeColor: app.globalData.mouldType == 1 ? "#E9D0AA" : bgColor.colorFirst.main.activeColor
    })
    let that = this;
    let optionss;
    //获取首页按钮
    that.getModule()
    let openId = wx.getStorageSync('openId')
    if (wx.getStorageSync('options')) {
      optionss = JSON.parse(wx.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, "?")
    this.checkDialog()
  },

  goContinue() {
    this.goConfirm()
  },

  goExit() {
    wx.exitMiniProgram()
  },

  checkDialog() {
    const isAgreeProtocol = wx.getStorageSync('isAgreeProtocol')
    if (isAgreeProtocol) return
    Http.get({
      url: config.api.needAgreeProtocol,
    }).then(res => {
      console.log(res, 'res');
      if (res.data) {
        setTimeout(() => {
          this.setData({
            isModalVisible: true
          })
        }, 2000);
      }
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  goConfirm() {
    Http.post({
      url: config.api.agreementProtocol,
      data: {
        agreeProtocol: 1
      }
    }).then(res => {
      console.log(res, 'res');
      wx.setStorageSync("isAgreeProtocol", 1)
      this.setData({
        isModalVisible: false
      })
      wx.showToast({
        title: "提交成功！",
        icon: "success"
      })
    }).catch(err => {
      console.log(err, 'err');
      wx.showToast({
        title: err.data ? err.data : "网络错误，请稍后再试！",
        icon: "none"
      })
    })
  },

  // clickPrivacy(e) {

  // },

  // closePrivacy() {
  //   this.setData({
  //     showPrivacy: false
  //   })
  // },

  // getPrivacySetting() {
  //   const canIUsePrivacy = wx.canIUse('getPrivacySetting')
  //   console.log(canIUsePrivacy, 'canIUse getPrivacySetting')
  //   if (canIUsePrivacy) {
  //     wx.getPrivacySetting({
  //       success: res => {
  //         console.log(res, 'getPrivacySetting') // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
  //         if (res.needAuthorization) {
  //           // 需要弹出隐私协议
  //           this.setData({
  //             showPrivacy: true
  //           })
  //         } else {
  //           // this.setData({
  //           //   showPrivacy: true
  //           // })
  //           // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
  //           // wx.getUserProfile()
  //           // wx.chooseMedia()
  //           // wx.getClipboardData()
  //           // wx.startRecord()
  //           // this.setData({
  //           //   showPrivacy: true
  //           // })
  //         }
  //       },
  //       fail: () => { },
  //       complete: () => { }
  //     })
  //   }
  // },

  // handleAgreePrivacyAuthorization() {
  //   console.log('Privacy Agreed!');
  //   this.setData({
  //     showPrivacy: false
  //   })
  //   // 用户同意隐私协议事件回调
  //   // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
  //   // wx.getUserProfile()
  //   // wx.chooseMedia()
  //   // wx.getClipboardData()
  //   // wx.startRecord()
  // },

  // handleOpenPrivacyContract() {
  //   // 打开隐私协议页面
  //   wx.openPrivacyContract({
  //     success: () => {
  //       // this.setData({
  //       //   showPrivacy: false
  //       // })
  //     }, // 打开成功
  //     fail: () => { }, // 打开失败
  //     complete: () => { }
  //   })
  // },

  /**
   * 获得经纬度
   */
  // getLocation() {
  //   let that = this;
  //   wx.getLocation({
  //     type: "wgs84",
  //     success: function (res) {
  //       console.log(res, 9999)
  //       if (res && res.longitude && res.latitude) {
  //         Http.post({
  //           url: config.api.updateLBS,
  //           data: {
  //             latitude: res.latitude,
  //             longitude: res.longitude
  //           }
  //         }).then(res => {
  //           console.log(res, 9999)
  //         })
  //       }
  //     },
  //     fail: error => {
  //       console.log(error);
  //     }
  //   })
  // },
  onUnload() {
    // wx.removeStorageSync('squareList')

  },
  // 初始换底部导航栏
  setTabStyle: function () {

    Http.get({
      url: config.api.setType,
      data: {
        mouldType: app.globalData.mouldType
      }
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code == 200) {
        app.globalData.styleLsit = data
        this.getTabBar().setData({
          selectedColor: `${app.globalData.styleLsit.t_in_std.styleClass}`,
          list: [{
            "pagePath": "/pages/theme/index1/index",
            "iconPath": `${app.globalData.styleLsit.t_in.icon}`,
            "selectedIconPath": `${app.globalData.styleLsit.t_in_std.icon}`,
            "text": "首页"
          },
          {
            "pagePath": "/index/searchbar",
            "iconPath": `${app.globalData.styleLsit.t_md.icon}`,
            "selectedIconPath": `${app.globalData.styleLsit.t_md_std.icon}`,
            "text": "门店"
          },
          {
            "pagePath": "/index/passCar",
            "iconPath": `${app.globalData.styleLsit.t_tc.icon}`,
            "selectedIconPath": `${app.globalData.styleLsit.t_tc_std.icon}`,
            "text": "停车"
          },
          {
            "pagePath": "/index/user",
            "iconPath": `${app.globalData.styleLsit.t_uc.icon}`,
            "selectedIconPath": `${app.globalData.styleLsit.t_uc_std.icon}`,
            "text": "我的"
          }
          ],
        })
      }
      // console.log(this.data.list[0].selectedIconPath, '99999999999999999999999999999999999999999')
    })
  },
  onShow: function () {
    console.log(app.globalData.mouldType, "mouldType")
    this.setData({
      mouldType: app.globalData.mouldType,
      marketName: app.globalData.marketName,
      activeColor: app.globalData.mouldType == 1 ? "#E9D0AA" : bgColor.colorFirst.main.activeColor
    })
    // this.uesrInfo()
    if (businessSwitch) {
      let openId = wx.getStorageSync("openId")
      let member_status = 0
      myPluginInterface.getAuthStatus(openId, this.data.mch_id).then(res => {
        member_status = res.status
        console.log(res.status, 'member_status')
      })
      if (businessVersion) {
        console.log(this.data.mch_id, 'this.data.mch_id');
        console.log(openId, 'openId');
        this.setData({
          goUrl: `plugin://auto-points-plugin/index?openid=${openId}&mch_id=${this.data.mch_id}&member_status=${1}`
        })
      } else {
        this.setData({
          goUrl: `plugin://auto-points-plugin/index?openid=${openId}&mch_id=${this.data.mch_id}`
        })
      }
    }
    // console.log(JSON.stringify(app.globalData.styleLsit), "styleLsit")

    this.ifShowSqare();
    if (wx.getStorageSync("squareList") && wx.getStorageSync("selectedMall")) {
      var temp = wx.getStorageSync("squareList").filter(item => item.tenantId == wx.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 = wx.getStorageSync('couponNum');
    let num1 = wx.getStorageSync('couponNum2');

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

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

  },


  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.userAvatarUrl = res.data.avatarUrl,
          app.globalData.userName = 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 => {
        wx.showModal({
          title: '提示',
          content: err.message,
          showCancel: false
        })
      })
  },
  gotoChengzhangzhi: function () {
    wx.navigateTo({
      url: '/pages/czdetail/czdetail',
    })
  },
  goIntegralmall() {
    wx.navigateTo({
      url: '/pages/integralmall/index',
    })
  },
  gotoBargain: function () {
    wx.navigateTo({
      url: '/pages/bargain/bargain',
    })
  },
  gotoSpellGroup: function () {
    wx.navigateTo({
      url: '/pages/spellGroup/spellGroup',
    })
  },
  gotoCard: function () {
    wx.navigateTo({
      url: '/pages/discountCardList/discountCardList',
    })
  },
  // gotoGame: function () {
  //   wx.navigateTo({
  //     url: '/pages/game/index',
  //   })
  // },
  gotoJfsc: function () {
    wx.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.setTabStyle()
      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: config.weapp.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:'',
          })
          // that.getPrivacySetting()
        })
        .catch(err => {
          // that.getGameOne(app.globalData.token)
          that.getStaticGame(app.globalData.token)
          that.getGg(app.globalData.token)
          wx.showModal({
            title: "提示",
            content: err.message,
            showCancel: false
          });
        });

    } else {
      app.tokenCallback = token => {
        // 登录
        that.setTabStyle()
        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: config.weapp.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:'',
            })
            // that.getPrivacySetting()
          })
          .catch(err => {
            // that.getGameOne(app.globalData.token)
            that.getStaticGame(app.globalData.token)
            that.getGg(app.globalData.token)
            wx.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)
        wx.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
      }
    }).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 => {
      wx.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 => {
      wx.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() {
    wx.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() {
  //   // 获取用户信息
  //   wx.getSetting({
  //     success: res => {
  //       if (res.authSetting["scope.userInfo"]) {
  //         // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
  //         wx.getUserInfo({
  //           success: res => {
  //             // 可以将 res 发送给后台解码出 unionId
  //           }
  //         });
  //       }
  //     }
  //   });
  // },
  gotoBargain: function () {
    wx.navigateTo({
      url: '/pages/bargain/bargain'
    })
  },
  //限时抢购的详情页面
  gotodetail: function (e) {
    wx.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: config.weapp.AppId,
        openId: "" // wx.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: function (e) {
    this.setData({
      topicObj2: null, //欢乐城首页限时抢购
      topicObj3: null, //欢乐城首页砍价
      topicObj4: null, //欢乐城首页拼团
      topicObj5: null, //欢乐城首页消费卡
      topicObj6: null, //欢乐城首页积分商城
    })
    let that = this;
    // that.getWeapNote();
    that.setData({
      page: 1
    })
    if (this.data.optionsData != null && (this.data.optionsData.couponChannelId || this.data.optionsData.orderId)) {
      this.getWeapNote(this.data.optionsData.couponChannelId, this.data.optionsData.orderId);
    } else {
      this.getWeapNote()
    }
    if (that.selectComponent("#lists")) {
      if (that.data.code == 0 || that.data.code == undefined) {
        that.selectComponent("#lists").getList(0, 1, "refresh");
        wx.stopPullDownRefresh();
      } else {
        that.selectComponent("#lists").getList(that.data.code, 1, "refresh");
        wx.stopPullDownRefresh();
      };
      that.selectComponent("#hot").getList();
    }

    // 砍价下拉刷新
    // that.selectComponent("#bargain").getList();
    // that.selectComponent("#spellGroup").getList();
    // that.selectComponent("#rushtobyCard").getList();
    wx.stopPullDownRefresh();
    //爆款专区下拉刷新

    that.getxsList();
    that.topicShow();
  },
  //加载更多
  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) {
        wx.showToast({
          title: "分享成功",
          duration: 1000,
          icon: "success"
        });
      }
    };
  }
});