// pages/sleepReport/sleepReport.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    show: false,
    minDate: new Date(2024, 4, 1).getTime(),
    maxDate: new Date().getTime(),
    defaultDate: [new Date().getTime(), new Date().getTime()],
    mData: [],
    formatter(day) {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();

      if (month === 5) {
        if (date === 1) {
          day.topInfo = '劳动节';
        } else if (date === 4) {
          day.topInfo = '五四青年节';
        } else if (date === 11) {
          day.text = '今天';
        }
      }

      if (day.type === 'start') {
        day.bottomInfo = '开始';
      } else if (day.type === 'end') {
        day.bottomInfo = '结束';
      }
      // else if (day.type === 'start-end') {
      //   return '开始/结束';
      // }

      return day;
    },
  },

  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  // formatDate(date) {
  //   date = new Date(date);
  //   return `${date.getMonth() + 1}/${date.getDate()}`;
  // },
  formatDate(date) {
    if (!date || date == null) {
      return "";
    }
    date = new Date(date);
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以要+1  
    let day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  onConfirm(event) {
    console.log(event.detail);
    var dateArr = event.detail || [];
    if (!dateArr[1] || dateArr[1] == null) {
      console.log("单选");
    } else {
      console.log("多选");
    }
    this.setData({
      show: false,
      page: 1,
      startdateStr: this.formatDate(event.detail[0]),
      enddateStr: this.formatDate(event.detail[1]),
    });
    this.getList(this.data.startdateStr, this.data.enddateStr || this.data.startdateStr);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getList()
  },
  toDetails(e) {
    console.log(e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/subpages/data/data?rpids=${item.rpids}`
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // const app = getApp();
    // app.globalData.selectedTabIndex = 2;
    // this.getTabBar().setData({
    //   selected: 2
    // })
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 1
    })
    this.getList(this.data.startdateStr, this.data.enddateStr || this.data.startdateStr);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log("上拉加载更多");
    // if (this.data.startdateStr) {
    //   return
    // }
    var page = this.data.page;
    page += 1;
    this.setData({
      page: page
    })
    this.getList(this.data.startdateStr, this.data.enddateStr || this.data.startdateStr);

  },
  checkTime(timeStr) {
    let hours = 0;
    let minutes = 0;
    if (timeStr && timeStr.indexOf("小时") != -1) {
      let parts = timeStr.split("小时");
      hours = parseInt(parts[0], 10); // 将小时部分转换为整数
    }
    if (timeStr && timeStr.indexOf("分钟") != -1) {
      let parts = timeStr.split("小时");
      let minutesStr = parts[1].split("分钟")[0]; // 获取分钟部分的字符串
      minutes = parseInt(minutesStr, 10); // 将分钟部分转换为整数
    }
    // console.log("小时:", hours); // 输出小时
    // console.log("分钟:", minutes); // 输出分钟
    return {
      hours: hours || 0,
      minutes: minutes || 0
    }
  },
  checkRScoreValueColor(value) {
    var checkList = [{
      title: "极好",
      titleColor: "#0BC3AA",
      startColor: "#0AB1C3",
      centerColor: "#0BC3AA",
      endColor: "#36E1CA",
    }, {
      title: "良好",
      titleColor: "#9C43FF",
      startColor: "#8D25FF",
      centerColor: "#A631FF",
      endColor: "#FF8FF0",
    }, {
      title: "较差",
      titleColor: "#FF8F4E",
      startColor: "#EE8B52",
      centerColor: "#FAA472",
      endColor: "#FAA472",
    }, {
      title: "很差",
      titleColor: "#FB717B",
      startColor: "#FB717B",
      centerColor: "#FB717B",
      endColor: "#FF98A0",
      }];

    var color = checkList[0].titleColor;
    var rscore_value = value - 0;
    if (rscore_value >= 90 && rscore_value <= 100) {
      color = checkList[0].titleColor;
    } else if (rscore_value >= 75 && rscore_value < 90) {
      color = checkList[1].titleColor;
    } else if (rscore_value >= 60 && rscore_value < 75) {
      color = checkList[2].titleColor;
    } else {
      color = checkList[3].titleColor;
    }

    return color;
    
  },
  getList(startdateStr, enddateStr) {
    const that = this;
    wx.request({
      url: 'https://aipush.aidsleep.cn/srpwithrange',
      method: 'POST',
      data: {
        startdate: startdateStr,
        enddate: enddateStr,
        token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
        udi: wx.getStorageSync('unionid') ,
        pg: that.data.page,
        lm: 20
      },
      success: (res) => {

        var mDataTemp = that.data.page == 1 ? [] : that.data.mData || [];
        var loadData = res.data.data;

        if ((loadData && !Array.isArray(loadData))) {
          for (const key in loadData) {
            if (Object.prototype.hasOwnProperty.call(loadData, key)) {
              const element = loadData[key];
              let subItems = [];
              for (const k in element) {
                if (Object.prototype.hasOwnProperty.call(element, k)) {
                  const subElement = element[k];
                  for (let i = 0; i < subElement.length; i++) {
                    var item = subElement[i];
                    var dateItem = that.checkTime(item.rinbed_duration);
                    var color = that.checkRScoreValueColor(item.rscore_value);
                    item.hours = dateItem.hours;
                    item.minutes = dateItem.minutes;
                    item.color = color;
                  }
                  subItems = subItems.concat(subElement);
                }
              }
              var isChange = false;
              for (let i = 0; i < mDataTemp.length; i++) {
                const elementOld = mDataTemp[i];
                if (elementOld.dateTitle == key) {
                  elementOld.subItem = elementOld.subItem.concat(subItems);
                  isChange = true;
                  break;
                }
              }
              if (!isChange) {
                var data = {
                  dateTitle: key,
                  subItem: subItems
                }
                mDataTemp.push(data)
              }
            }
          }
          console.log(mDataTemp);
          that.setData({
            mData: mDataTemp
          })

        } else {
        }
      },
      fail: () => {
      }
    });
  },

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

  }
})