// app.js
const ald = require('./utils/ald-stat.js')
import { post, get, login } from './utils/http'
App({
  globalData: {
    navBarData: {
      navBarHeight: 0, // 导航栏高度
      menuBotton: 0, // 胶囊距底部间距（保持底部间距一致）
      menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
      menuHeight: 0 // 胶囊高度（自定义内容可与胶囊高度保证一致）
    },
    userInfo: null, 
    couponPopup: false,
    coupon: null,
    systemInfo: {},
    sceneData: {},
    memberRules: '', // 会员守则
    storeData: {},
    showGoods:false, //点击商品或者按钮跳转到下单页面是否直接显示美妆产品
    toViewIndex:'', //记录首页跳转到项目页面的滚动下标
    shareUserID:'',//分享人ID
    isH5:false, //是否是h5商城进来的
    isSkinPlan:false, //测肤推荐方案标识
    isTestSkin:false,//肤质下单标识
    isCardBag:false, //卡包更多次卡跳转
  },
  invite_id:"null",//邀请人id
  //记录登录状态相关的配置
  loginConfig: {
    code: '',
    codeTime: ''
  },
  address:{},
  onLaunch(options) {
    // 肤质 测肤方案埋点
    let RECORD_WHITE = ['pages/projectDetail/projectDetail','pages/reserveCar/reserveCar','pages/orderBy/orderBy']
    wx.onAppRoute((route) => {
    if(this.globalData.isSkinPlan||this.globalData.isTestSkin){
        if(!RECORD_WHITE.includes(route.path)){
          this.globalData.isSkinPlan = false
          this.globalData.isTestSkin = false
        }
      }
      });
    let WHITE_LIST=['pages/login/login','pages/home/home']
    if(!WHITE_LIST.includes(options.path)){
      if(wx.getStorageSync('userInfo')==''){
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    }
    let that = this
    this.getPermission(that); //获取当前定位  
    that.setNavBarInfo()
    // 查询是否首次购买
    if (wx.getStorageSync('token')) {
      get('api/order/check_first', {}, (res) => {
        if (res.data.order_status == 1) {
          wx.setStorageSync('agree', true)
        }
      })
    }
    that.initData()
    // this.getPermission()
  },
  onShow(opts) {
    this.globalData.sceneData = {
      path: opts.path,
      query: opts.query
    }
    if (!this.globalData.userInfo) {
      this.initData()
    }
    if (opts.path == 'pages/deviceLogin/deviceLogin') {
      return
    }
    // if (!wx.getStorageSync('token') || !wx.getStorageSync('userInfo')) {
    //   login(opts)
    // }
  },

  /**
   * 初始化数据
   */
  initData() {
    let that = this
    // 获取用户信息
    if (wx.getStorageSync('token')) {
      get('api/user', {}, (res) => {
        if (res.data) {
          that.globalData.userInfo = res.data
          wx.setStorageSync('userInfo', res.data)
        }
      })
    }

    return
    // 获取店铺信息
    let storeId = wx.getStorageSync('store_id')
    if (storeId) {
      get(
        'api/store/info',
        {
          store_id: storeId
        },
        (res) => {
          this.globalData.storeData = res.data
        }
      )
    }
  },

  /**
   * @description 设置导航栏信息
   */
  setNavBarInfo() {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync()
    this.globalData.systemInfo = systemInfo
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
    this.systemInfo = systemInfo
    // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
    let navBarData = {
      navBarHeight:
        (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 +
        menuButtonInfo.height +
        systemInfo.statusBarHeight,
      menuBotton: menuButtonInfo.top - systemInfo.statusBarHeight,
      menuRight: systemInfo.screenWidth - menuButtonInfo.right,
      menuHeight: menuButtonInfo.height
    }
    this.globalData.navBarData = navBarData
  },
    /**
   * 获取当前定位
   * @param {*} obj 
   */
  getPermission: function (obj) {
    let that = this
    wx.getLocation({
      success: function (res) {
        that.getStore()
        that.globalData.address = res
        // console.log(that.address, 'that.addressthat.address', res);
      },
      fail: function () {
        wx.getSetting({
          success: function (res) {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置，请确认授权，否则无法定位最近店铺',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //授权成功之后，再调用chooseLocation选择地方
                          wx.getLocation({
                            success: function (res) {
                              that.getStore()
                              app.address = res
                            },
                          })
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '调用授权窗口失败',
              icon: 'success',
              duration: 1000
            })
          }
        })
      }
    })
  },
    /**
   * 获取店铺接口
   * /api/store
   */
  getStore() {
    get(
      'api/store', {
        page: 1,
        limit: 100,
        keyword: ""
      },
      (res) => {
        let lat1 = this.globalData.address.latitude,
          lng1 = this.globalData.address.longitude,
          storeList = res.data.list,
          distanceList = []
        //循环遍历计算获取当前定位到各门店的距离
        storeList.forEach(item => {
          let distanceInfo = {}
          distanceInfo["id"] = item.id
          distanceInfo["dist"] = this.getDistance(lat1, lng1, item.latitude, item.longitude)
          distanceList.push(distanceInfo)
        })
        //近到远排序
        let _distanceList = distanceList.sort(function (a, b) {
          return a.dist - b.dist
        })
        // //切换门店
        // this.getStoreInfo(String(_distanceList[0].id))
        wx.setStorageSync('store_id', String(_distanceList[0].id))
      }
    )
  },
    /**
   * 两点之间距离计算
   * @param {*} lat1 
   * @param {*} lng1 
   * @param {*} lat2 
   * @param {*} lng2 
   */
  getDistance(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

    return distance;
  },
})
