const Parse = getApp().Parse;
const login = require("../../../utils/login");
const getTabs = require("../../../utils/getTabs")
const company = getApp().globalData.company
const tabName = getApp().globalData.moduleTab
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabbarList: [],
    tabbarOption: null,
    active: 0,
    isInit: false,
    botHeight: 0,
    template: getApp().globalData.styleTemplate,
    bottomHeight: getApp().globalData.screenHeight - getApp().globalData.safeArea?.bottom
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    getApp().globalData.styleTemplate = {
      style: '1',
      themeColor: '',
    }
    this.setData({
      template: getApp().globalData.styleTemplate
    })
    let str = decodeURIComponent(options.q)
    let obj = this.getParaName(str)
    let tabbarOption = await getTabs.getDiyTabs(tabName ? tabName : null)
    this.setData({
      tabbarList: tabbarOption.list,
      tabbarOption: tabbarOption,
    })
    let active = options.active
    if (this.data.tabbarOption.activeColor) {
      getApp().globalData.activeColor = this.data.tabbarOption.activeColor
    }
    if (this.data.tabbarOption.activeColor == '#000000') {
      getApp().globalData.titleColor = "#999999"
    }
    let event = {
      detail: options.active || 0,
      currentTarget: {
        dataset: 1
      }
    }

    await this.onChange(event)
    this.getUserLocation()
    this.getScreenHeight()
    if (obj && obj.tableid && obj.storeid) {
      wx.navigateTo({
        url: `/nova-tourism/pages/gourmet/store-package/meal-order/index?storeid=${obj.storeid}&tableid=${obj.tableid}`,
      })
    }
  },
  getUserLocation: async function () {
    let _this = this
    await wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '逛一逛需要你的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      _this.getLocation();
                      //再次授权，调用wx.getLocation的API
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
          return res.authSetting['scope.userLocation']
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          this.getLocation();
        } else {
          //调用wx.getLocation的API
          this.getLocation();
        }
      }
    })
  },
  //授权后调用百度地图接口获取当前城市
  getLocation: function () {
    // 微信获得经纬度
    let _this = this;
    wx.getLocation({
      type: 'wgs84', //gcj02 // wgs84
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        let speed = res.speed
        let accuracy = res.accuracy
      },
      fail(err) {

      }
    })
  },


  getParaName(url) {
    if (!url || url.indexOf('?') == -1) {
      return
    }
    let paraname = url.split('?')[1]
    return this.setObject(paraname) //封装成对象
  },
  setObject(paraArr) {
    let obj = {}
    let arr1 = paraArr.split('&')
    arr1.forEach(item => {
      let str = item.split('=')
      let key = str[0]
      let val = str[1]
      obj[key] = val
    })
    return obj
  },
  async isLocal() {
    let that = this
    return await new Promise((resolve, reject) => {
      wx.getSetting({
        success: function (res) {
          let localtion = res.authSetting['scope.userLocation']
          if (!localtion) {
            that.getUserLocation()
            resolve(localtion)
          } else {
            resolve(localtion)
          }
        }
      })
    })
  },


  async onChange(event, id) {
    let currentIndex = event.detail;
    console.log(event);
    // let currentIndex = event.currentTarget.dataset.index
    let currentComp = this.selectComponent("#comp" + String(currentIndex));
    let tab = this.data.tabbarList[currentIndex];
    if (tab && tab.auth) { // auth设置有值时，校验登录
      let userLogin = wx.getStorageSync("userLogin");
      if (userLogin == "") {
        login.loginNow('/nova-tourism/pages/app-auth/index');
        return;
      }
    }
    if (currentIndex == 0) {
      currentComp.getData()
    }
    if (currentIndex == 1) {
      currentComp.setData({
        showTab: true
      })
      currentComp.getLocation()
      currentComp.getData()
      currentComp.getShopStore()
    }
    if (currentIndex == 2) {
      currentComp.setData({
        showTab: true,
        searchVal: ''
      })
      // currentComp.getRooms()/**！！！！ */

    }
    if (currentIndex == 3) {
      currentComp.setData({
        goods: []
      })
      // currentComp.getmy()/**！！！！ */
      // currentComp.getBindStore()/****** */
      // currentComp.getCategory()/****** */
      currentComp.getGoods()
    }
    if (currentIndex == 4) {
      // currentComp.getmy() /**！！！！！ */

    }

    wx.pageScrollTo({ // 滚动至页面顶部
      scrollTop: 0,
    });
    this.setData({ // 切换Tab参数
      active: currentIndex,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: async function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    let component = this.selectComponent("#comp" + this.data.active);
    console.log(component);
    switch (Number(this.data.active)) {
      // case 0:
      //   component.refresh()
      //   break;
      // case 1:
      //   component.refresh()
      //   break;
      case 3:
        component.setData({
          goods: []
        })
        component.refresh()
        break;
      // default:
      //   break;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作传递给子组件
   */
  onPullDownRefresh: function () {
    // 根据tab当前index，查询组件并触发组件内下拉刷新函数
    let comp = this.selectComponent("#comp" + this.data.active);
    if (comp) {
      comp.onPullDownRefresh && comp.onPullDownRefresh();
    }
    return
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      // title: '畅游山坡',
    }
  },

  onShareTimeline: async function (res) {
    await this.getTask('share')
    return {
      title: '转发到朋友圈',
      query: '我是携带的参数'
    }
  },
  //获取底部安全距离
  getScreenHeight() {
    let that = this
    wx.getSystemInfo({
      success: (res) => {
        let {
          screenHeight,
          safeArea
        } = res
        let botHeight = screenHeight - safeArea.bottom
        that.setData({
          botHeight
        })
        wx.setStorageSync('botHeight', botHeight);
      },
      fail: () => { },
      complete: () => { }
    });
  },
  async getTask(type) {
    let userid = Parse.User.current().id
    let Task = new Parse.Query('Task')
    Task.equalTo('company', company)
    Task.equalTo('taskType', type)
    Task.equalTo('isOpen', true)
    let task = await Task.first()
    if (task && task.id) {
      let start = new Date(new Date(new Date().toLocaleDateString()).getTime())
      let TaskLog = new Parse.Query('TaskLog')
      TaskLog.equalTo('user', userid)
      TaskLog.equalTo('task', task.id)
      TaskLog.equalTo('company', company)
      if (task.type == 'daily') {
        TaskLog.greaterThan('createdAt', start)
      }
      let log = await TaskLog.first()
      if (log && log.id) {
        return
      } else {
        this.createdLog(userid, task.id, task.get('credit'))
      }
    }
  },
  async createdLog(uid, tid, credit) {
    let TaskLog = Parse.Object.extend('TaskLog')
    let tasklog = new TaskLog()
    tasklog.set('user', {
      __type: "Pointer",
      className: '_User',
      objectId: uid
    })
    tasklog.set('task', {
      __type: "Pointer",
      className: 'Task',
      objectId: tid
    })
    tasklog.set('company', {
      __type: "Pointer",
      className: 'Company',
      objectId: company
    })
    tasklog.set('isReceive', false)
    tasklog.set('credit', credit)
    await tasklog.save()
  },
})