// nova-werun/pages/home/statistics/index.js
import * as echarts from "../../../components/ec-canvas/echarts"
const Parse = getApp().Parse;
const company = getApp().globalData.company;
const getSportData = require("../../../service/getSportData.js");
const uid = Parse.User.current()?.id
const user = Parse.User.current()
const dateF = require("../../../../utils/date")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //屏幕高度
    statusBarHeight: 0, // 状态栏高度
    screenHeight: 0, // 屏幕高度
    customHeight: 0, // 自定义导航栏高度（如小程序右上角胶囊按钮）
    bottomNavHeight: 0, // 底部导航栏高度
    contentHeight: 0, // 可用内容高度
    contentHeight2: 0,
    contentpadding: 0, //顶部padding高度

    active: 0,
    sportsDate: null, //运动数据 卡路里/时间/公里/步数
    option: null, //图表数据
    careerData: null, //生涯数据 注册日/卡路里/时间/公里/步数
    rankOfAll: null, //全网排名
    rece: 7, //近期趋势 7天/30天
    receDate: null, //趋势数据 每日平均/总计



    //
    day: '7',
    target: '',
    sharList: [],
    //生涯数据
    stardate: '',
    daysDifference: "",
    totalSteps: 0,
    totalDistance: 0,
    totalBurnCalories: 0,
    totalsportDate: 0,


    resultList: [],
    stepsData: [], //统计图柱状
    xAxis: [], //x轴

    percentage: '',
    percent: '',

    //排名百分比
    percebtage: 0,
    //
    average: 0,
    totle: 0,

    //显示日历
    todatDate: null,
    minDate: null,
    maxDate: null,
    formatter(day) {
      day.topInfo = '11111'
      return day;
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let that = this


    // 计算
    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 - 50 - bottomNavHeight - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
    this.setData({
      statusBarHeight,
      screenHeight,
      customHeight,
      bottomNavHeight,
      contentpadding,
      contentHeight
    });

    this.refersh01()
  },
  /** 底部tab栏修改*/
  async onChange(event) {
    if (event.detail == 0) {
      this.refersh01()
    } else {
      this.refersh02()
    }
    await this.setData({
      active: event.detail
    });
  },
  /**今日步数页面刷新 */
  async refersh01() {
    let that = this
    await this.getSportDate()
    this.gettarget()
    await this.getWeekData()
    this.setData({
      ec: {
        onInit: that.initChart
      },
    })
  },
  /**周期统计页面刷新 */
  async refersh02() {
    this.getCareer()
    this.getRankingOfAll()
    this.getTrend()
    this.getTrendSum()
  },

  /**获取运动数据 */
  async getSportDate() {
    let burnCalories = await getSportData.getwalk('burnCalories') || 0
    let sportDate = await getSportData.getwalk('sportDate') || 0
    let distance = await getSportData.getwalk('distance') || 0
    let steps = await getSportData.getwalk('steps') || 0
    this.setData({
      sportsDate: {
        burnCalories,
        sportDate,
        distance,
        steps
      }
    })
  },
  /** 获取目标步数*/
  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) {
      await this.setData({
        target: num.num
      })
      this.getBackgroundColor()
    }
  },
  /** 修改光圈*/
  getBackgroundColor() {
    const steps = this.data.sportsDate.steps || 0;
    let percent = (steps / this.data.target) * 100;
    if (percent > 100) {
      percent = 100;
    }
    percent = parseFloat(percent.toFixed(2));
    this.setData({
      percent,
      percentage: `conic-gradient(from 0deg, #015EEA ${percent}%, white 0%)`,
    })
  },
  /**获取本周步数 */
  async getWeekData() {
    let dates = [];
    let now = new Date();
    let currentDate = now.getDate();
    let currentDay = now.getDay();
    let monday = new Date(now);
    monday.setDate(currentDate - currentDay + 1);
    for (let i = 0; i < 7; i++) {
      let date = new Date(monday);
      date.setDate(monday.getDate() + i);
      date.setHours(0, 0, 0, 0);
      let nextDate = new Date(monday);
      nextDate.setDate(monday.getDate() + i + 1);
      nextDate.setHours(0, 0, 0, 0);
      let fromto = {
        from: date,
        to: nextDate
      }
      let d = await getSportData.getwalk('steps', '', fromto) || 0
      let item = {
        value: d,
        itemStyle: {
          color: '#4F9AF7'
        }
      }
      dates.push(item);
    }
    let option = {
      graphic: {
        z: -1
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: dates,
        type: 'bar'
      }]
    }
    this.setData({
      option
    })
  },

  /**获取生涯合计 */
  async getCareer() {
    let startDate = dateF.formatTime("YYYY年mm月dd日", user?.get('createdAt'))
    let fromTo = {
      from: user?.get('createdAt'),
      to: new Date()
    }
    let diff = Math.abs(fromTo.from.getTime() - fromTo.to.getTime());
    let days = 1000 * 60 * 60 * 24;
    let difDays = parseInt(Math.floor(diff / days))
    let steps = await getSportData.getwalk('steps', '', fromTo) || 0
    let burnCalories = await getSportData.getwalk('burnCalories', '', fromTo) || 0
    let sportDate = await getSportData.getwalk('sportDate', '', fromTo) || 0
    let distance = await getSportData.getwalk('distance', '', fromTo) / 1000 || 0
    sportDate = this.convertSeconds(sportDate)
    distance = distance.toFixed(2)
    this.setData({
      careerData: {
        startDate,
        difDays,
        steps,
        burnCalories,
        sportDate,
        distance
      }
    })
  },
  /**秒换算天小时 */
  convertSeconds(seconds) {
    let secondsInAnHour = 3600;
    let hours = Math.floor(seconds / secondsInAnHour);
    let days = Math.floor(hours / 24);
    return {
      days: days,
      hours: hours % 24 // 计算剩余的小时数
    };
  },
  /**获取全网排名 */
  async getRankingOfAll() {
    let steps = await getSportData.getwalk('steps', '')
    let rd = await getSportData.getUserRank(uid, '', 'today')
    let rank = rd[0]?.rank || 0
    // console.log(steps, rd, rank)
    let percent = 0
    if (rank > 0) {
      let query = new Parse.Query('_User')
      query.equalTo('company', company)
      query.equalTo('type', 'user')
      query.notEqualTo('isDeleted', true)
      let uCount = await query.count()
      percent = (100 * ((uCount - parseInt(rank) + 1) / uCount)).toFixed(2)
    }
    let rankOfAll = {
      steps,
      percent
    }
    this.setData({
      rankOfAll
    })
  },
  /**获取近期趋势 平均/总计 */
  async getTrendSum() {
    let {
      rece
    } = this.data
    rece = parseInt(rece)
    let to = new Date();
    let from = new Date(to);
    from.setDate(to.getDate() - rece);
    from.setHours(0, 0, 0, 0);
    let count = await getSportData.getwalk('steps', '', {from,to}) || 0
    let svg = parseInt(count / rece)
    this.setData({
      receDate: {
        count,
        svg
      }
    })
  },
  /**获取近期趋势 */
  async getTrend() {
    this.setData({
      option: null
    })
    let {
      rece
    } = this.data
    let dates = [];
    let xList = []
    let today = new Date();
    today.setHours(0, 0, 0, 0);
    let tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);
    for (let i = 0; i < rece; i++) {
      let from = new Date(today);
      from.setDate(today.getDate() - i)
      let to = new Date(tomorrow);
      to.setDate(tomorrow.getDate() - i)
      let fromTo = {
        from,
        to
      }
      let d = await getSportData.getwalk('steps', '', fromTo) || 0
      let item = {
        value: d,
        itemStyle: {
          color: '#4F9AF7'
        }
      }
      xList.push(dateF.formatTime("mm-dd", from))
      dates.push(item);
    }
    let option = {
      xAxis: {
        type: 'category',
        data: xList
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: dates,
        type: 'bar'
      }]
    }
    await this.setData({
      option
    })
    let that = this
    this.setData({
      ec: {
        onInit: that.initChart
      },
    })
  },
  /**修改近期7/30 天 */
  async changeTrend(e) {
    let {
      rece
    } = this.data
    let {
      t
    } = e.currentTarget.dataset
    t = parseInt(t)
    // console.log(t, rece)
    if (t == rece) return
    await this.setData({
      rece: t
    })
    this.getTrendSum()
    this.getTrend()
  },

  /**设置图表 */
  initChart(canvas, width, height, dpr) {
    let {
      option
    } = this.data
    let chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr
    });
    canvas.setChart(chart);
    chart.setOption(option);
    return chart;
  },


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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})