// nova-werun/components/home/index.js
const Parse = getApp().Parse;
const company = getApp().globalData.company;
let getSportData = require('../../service/getSportData')
const uid = Parse.User.current()?.id


Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    //屏幕高度
    statusBarHeight: 0, // 状态栏高度
    screenHeight: 0, // 屏幕高度
    customHeight: 0, // 自定义导航栏高度(如小程序右上角胶囊按钮)
    bottomNavHeight: 0, // 底部导航栏高度
    contentHeight: 0, // 可用内容高度
    contentpadding: 0, //顶部padding高度
    navheight: 0,
    percentage: 0,
    //选择
    rows: [{
        image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241225/r5j1uc041211788.png',
        text: '签到打卡',
        url: '../../pages/home/signin/index'
      },
      {
        image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241225/n1pin1040819673.png',
        text: '实时步行',
        url: '../../pages/home/sport/sport-home/index',

      },
      {
        image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241225/9vfr1l040831635.png',
        text: '转发分享',
        url: '../../pages/home/share/index'

      },
      {
        image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241225/it1rna040843179.png',
        text: '我的勋章',
        url: '../../pages/home/medal/index'
      },
      {
        image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241225/r5193r040853498.png',
        text: '我的统计',
        url: '../../pages/home/statistics/index'
      },
      // {
      //     image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/v6p4fm041343296.png?imageView2/1/w/200/h/200',
      //     text: '排行榜',
      //     url: '../../pages/home/ranking/index'
      // },


      // {
      //     image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241102/71svpg041343669.png?imageView2/1/w/200/h/200',
      //     text: '跑步',
      //     url: '../../pages/home/sport/sport-home/index',
      //     active: 1
      // },

      // {
      //     image: 'https://file-cloud.fmode.cn/qpFbRRSZrO/20241104/k1q4no034958681.png?imageView2/1/w/200/h/200',
      //     text: '积分',
      //     url: '../../pages/home/integral/index'
      // },
    ],
    target: 0,
    sharList: [],

    address: "",
    //排行榜
    todayList: [],
    changetitle: 0,
    changetitleMap: {
      0: '历史',
      'today': '本日',
      'toweek': '本周',
      'tomonth': '本月',

    },
    steps: 0,
    //正序
    rank: 'DESC',
    meContinuousChick: 0, //当前用户连续打卡数
    sportTotal: 0, //当前用户累计运动
    notice: '', //公告
  },
  lifetimes: {

    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
    attached: async function () {
      // getSportData.setEndSport("NwzxcVxCV1")
      // 在组件实例进入页面节点树时执行
      // 计算
      const systemInfo = wx.getSystemInfoSync();
      const statusBarHeight = systemInfo.statusBarHeight || 0;
      const screenHeight = systemInfo.screenHeight || 0;
      const custom = wx.getMenuButtonBoundingClientRect();
      const customHeight = custom.height + 10 + 2 || 0;
      const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;

      const contentpadding = (statusBarHeight + customHeight) * 750 / systemInfo.windowWidth;
      const contentHeight = (screenHeight - bottomNavHeight - 50 - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
      const navheight = (statusBarHeight + customHeight) * 750 / systemInfo.windowWidth;
      this.setData({
        statusBarHeight,
        screenHeight: (screenHeight - 50 - bottomNavHeight) * 750 / systemInfo.windowWidth,
        customHeight,
        bottomNavHeight,
        contentHeight,
        contentpadding,
        navheight,
      });
      this.Getlocation()
      this.refersh()
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async refersh() {

      await this.gettarget()
      this.order()
      this.gettoday()
      this.getMeChick()
      let sportTotal = await getSportData.getChickCount(uid, 'ActivityData')
      this.setData({
        sportTotal
      })
      this.getNotice()
    },
    async getNotice() {
      let query = new Parse.Query('Notice');
      query.equalTo('company', company);
      query.notEqualTo('isDeleted', true)
      let n = await query.first();
      this.setData({
        notice: n?.get('content') || '欢迎加入儒乐湖健身~'
      })
    },
    /**当前用户连续打卡数 */
    async getMeChick() {
      let meContinuousChick = await getSportData.getContinuousCount(uid, 'ActivityData') || 0
      this.setData({
        meContinuousChick
      })
    },
    //跳转
    gourl(e) {
      const url = e.currentTarget.dataset.url
      const active = e.currentTarget.dataset.active
      if (active) {
        wx.navigateTo({
          url: `${url}?id=` + active // 目标页面的路径
        });
        console.log(active);
      } else {
        wx.navigateTo({
          url: `${url}` // 目标页面的路径
        });
      }

    },
    //获取目标步数
    async gettarget() {
      const currentUser = Parse.User.current();
      let userquery = new Parse.Query('_User');
      userquery.equalTo('company', company);
      userquery.equalTo('objectId', currentUser?.id);
      userquery.notEqualTo('isDeleted', true)
      let user = await userquery.first();
      let num = user?.toJSON()
      if (num?.num) {
        this.setData({
          target: num?.num
        })
        console.log('当前步数', this.data.target);
      } else {
        const currentUser2 = Parse.User.current();
        let userquery2 = new Parse.Query('_User');
        userquery2.equalTo('company', company);
        userquery2.equalTo('objectId', currentUser2?.id);
        userquery2.notEqualTo('isDeleted', true)
        let user2 = await userquery2.first();
        user2.set('num', 5000)
        try {
          let saveDate2 = await user2.save();
          console.log(saveDate2);
          this.setData({
            target: 5000
          })
          console.log("目标步数更改成功");
        } catch (error) {
          console.error("保存数据时出现错误:", error);
        }
      }
    },

    /** 获取当天运动数据*/
    async order() {
      let steps = await getSportData.getwalk('steps')
      this.setData({
        steps,
      })
      this.getBackgroundColor()
      // console.log('sharList', steps);
    },
    /** 修改进度条*/
    getBackgroundColor() {
      console.log(this.data.steps, this.data.target)
      let percentage = (this.data.steps / this.data.target) * 100;
      if (percentage > 100) {
        percentage = 100;
      }
      this.setData({
        percentage: `conic-gradient(from 0deg, #015EEA ${percentage}%, white 0%)`,
      })
      console.log('百分比', this.data.percentage);
    },
    /** 获取当前位置信息*/
    Getlocation() {
      // 获取当前位置信息
      wx.getLocation({
        type: 'wgs84',
        success: (res) => {
          const {
            latitude,
            longitude
          } = res;
          //调用api解析地址
          wx.request({
            url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=sHZTomd7grslfP7sPKB8tRgT49FK9TEu&output=json&coordtype=gcj02&location=' + latitude + ',' + longitude,
            data: {},
            header: {
              'Content-Type': 'application/json'
            },
            success: (ops) => { // 使用箭头函数
              console.log(ops);
              // const address = ops.data.result.formatted_address;//详细地址
              const address = ops.data.result.addressComponent.city; //市
              this.setData({
                address: address,
              });
              console.log(this.data.address);
            },
            fail: function (resq) {
              wx.showModal({
                title: '信息提示',
                content: '请求失败',
                showCancel: false,
                confirmColor: '#f37938'
              });
            },
            complete: function () {}
          })

        },
        fail: (err) => {
          console.error(err);
          wx.showToast({
            title: '获取位置失败',
            icon: 'none'
          });
        }
      });
    },

    /** 切换 历史/本日/本周/本月*/
    change() {
      // 使用数组来简化切换逻辑
      const titles = [0, 'today', 'toweek', 'tomonth'];
      const currentIndex = titles.indexOf(this.data.changetitle); //获取index
      const nextIndex = (currentIndex + 1) % titles.length; // 循环切换
      this.setData({
        changetitle: titles[nextIndex]
      });
      this.gettoday()
    },
    /**获取排行榜 */
    async gettoday() {
      let {
        rank,
        changetitle
      } = this.data
      let data = await getSportData.getRanking('', changetitle, '', '', rank)
      let todayList = []
      for (let i in data) {
        let obj = data[i]
        obj.count = await getSportData.getChickCount(obj.user, 'ActivityData')
        todayList.push(obj)
      }
      this.setData({
        todayList
      });
    },
    /** 正序逆序*/
    async changeup() {
      if (this.data.rank == 'DESC') {
        await this.setData({
          rank: 'ASC'
        })
      } else {
        await this.setData({
          rank: 'DESC'
        })
      }
      this.gettoday()
    },

  }
})