// parents//pages/growth_track/growth_track.js
import F2 from '../../../utils/f2-canvas/lib/f2';
const wxCharts = require("../../../utils/wxcharts-min.js");
let chart;
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { DayCount, MonthCount } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, hasLibraryService, hasVipService } = getApp()
const { baseImgUrl, qrcodeInvalidToastText } = globalData
/**
 * 进度条颜色RGB 
 */
const colorRGB = '255,215,108'
const colorRGB1 = '255,128,168'
const colorRGB2 = '0,183,255'
const colorRGB3 = '255,97,97'
const colorRGB4 = '121,189,232'
const colorRGB5 = '250,202,106'
const colorRGB6 = '143,232,121'
const colorRGB7 = '117,227,243'
const colorRGB8 = '255,145,128'
const colorRGB9 = '119,143,242'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    isLoaded: 1,
    date: '',
    month:'',
    ec: {
      lazyLoad: true // 延迟加载组件
    },
    pageNo: 1,
    pageSize: 5,
    isAll: 0,
    opts: {
      lazyLoad: true // 延迟加载组件
    },
    dayInfo:[],
    monthInfo:[],
    themeSelect:false,
    rankList:[
    ],
    messarr: [
    {
      color: '#f7c11b', 
      flownum: '0',
    },
  
    {
      color: '#17d0bc',
      flownum: '0',
    }
    ],
    footerData: {
      actIndex:1,
      list: [
        {
          text: '找好书',
          icon: '../../../assets/book_gray.png',
          actIcon: '../../../assets/book_blue.png',
          url: 'parents/pages/main/main',
          zindex: 3,
        },
        {
          text: '成长轨迹',
          icon: '../../../assets/wish_gray.png',
          actIcon: '../../../assets/wish_blue.png',
          url: 'parents/pages/growth_track/growth_track',
          zindex: 3,
        },
        {
          text: '我的',
          icon: '../../../assets/me_gray.png',
          actIcon: '../../../assets/me_blue.png',
          url: 'parents/pages/me/me',
          zindex: 3,
        }
      ]
    },
    nodataArray: {
      text: "暂无阅读计划",
      margin: '140rpx auto'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.GetDate()
    this.GetMonthDate()
    options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`)
    options.libId = getGlobalVal('list').length > 0 ? getGlobalVal('list')[0].libId : ''
    this.setData(options)
    this.getData(res => {
      this.setData({ isLoaded: 1 })
    })
    this.getMonthData(res => {
      this.setData({ isLoaded: 1 })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
    },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData()
    // this.nearTwentyEight()
    // this.everyReading()
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData(() => {
      wx.stopPullDownRefresh()
    })
  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },
  /**
   * 选择跳转进入页
   */
  selectNavCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { date, month } = this.data
    if (index == 1) {
      wx.setStorageSync('date', date);
      navigateTo({
        url: 'president/pages/library_sign_num/library_sign_num?isMonthData=1',
      })
    }
    if (index == 2) {
      wx.setStorageSync('monthValue', month);
      navigateTo({
        url: 'president/pages/library_sign_num/library_sign_num?isMonthData=2',
      })
    }
  },
  /**
 * 好书推荐图表
 */
  goodBooksPicture: function () {
    const { messarr } = this.data
    // console.log(themeInfoList)
    var that = this
    if (messarr.length === 0) return
    this.selectComponent('#pieSelect').init(function (canvas, width, height) {
      // 数据

      const data = (list => {
        const arr = []
        for (const v of list) {
          const { themeName = '', percentage = 0, } = v
          arr.push({
            const: 'const',
            type: themeName,
            percent: ~~(+percentage * 100)
          })
        }
        return arr
      })(messarr)
      // console.log(data)
      // 生成画布
      const chart = new F2.Chart({
        el: canvas,
        width,
        height
      })
      chart.source(data)
      chart.coord('polar', {
        transposed: true,
        radius: 0.75,
        innerRadius: 0.48
      })
      chart.axis(false)
      chart.legend(false)
      chart.tooltip(false)
      chart.interval().position('const*percent').adjust('stack').color('type', [
        `rgba(${colorRGB}, 1)`,
        `rgba(${colorRGB9}, 1)`,
      ])
    
      chart.interaction('pie-select', {
        cancelable: false,
        animate: {
          duration: 300,
          easing: 'backOut'
        },
        onEnd: res => {
          const { data } = res
          that.setData({
            pageNo: 1,
            themeSelect: true
          })
        }
      });
      chart.pieLabel({
        sidePadding: 30,
        sidePadding: 70,
        adjustOffset:1000,
        activeShape: false,
        label1: function label1(data) {
          return {
            text: data.percent + '%',
            fill: '#333333',
            fontWeight: 'bold'
          };
        },
        label2: function label2(data) {
          return {
            text:  data.type,
            fill: '#cccccc',
          };
        },
        // onClick: function onClick(e) {
        //   const { data = {} } = e
        //   console.log(data)
        // }
      });
      chart.render()
      return chart
    })
  },
  /**
 * 日统计数据
 */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { libId, date} = this.data
    DayCount({ data: { date, libId }, continuousFn }).then(res => {
      const { dayInfo } = res.data
      console.log(dayInfo)
      this.setData({ dayInfo })
      // debugger
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },
  GetDate: function(){
    const now = new Date();
    const year = now.getFullYear();         //年
    const month = now.getMonth() + 1;     //月
    const day = now.getDate();              //日
    const nowdate = year + '-' + month.toString().padStart(2, '0') + '-' + day.toString().padStart(2, '0')   //月 
    this.setData({ date: nowdate })

  },
  GetMonthDate: function () {
    const now = new Date();
    const year = now.getFullYear();         //年
    const month = now.getMonth() + 1;  
    const nowdate = year + '-' + month.toString().padStart(2, '0')   //月 
    this.setData({ month: nowdate })

  },
  /** 
 * 获取月统计数据
 */
  getMonthData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { libId, month, messarr } = this.data
    MonthCount({ data: { month: month,libId }, continuousFn }).then(res => {
      const { monthInfo } = res.data
    
      messarr[0].percentage = Math.round(monthInfo.activeCount / monthInfo.allCount * 100) / 100
      messarr[1].percentage = (1 - Math.round(monthInfo.activeCount / monthInfo.allCount * 100) / 100)
      messarr[0].themeName = "活跃用户"
      messarr[1].themeName = "沉默用户"
      console.log(messarr)
      this.setData({ monthInfo })
      console.log(monthInfo)
      this.goodBooksPicture()
      if (isFn(cb)) cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      if (isFn(cb)) cb()
    })
  },
  /**
 * 选择日期
 */
  changeDate: function (e) {
    const { value } = e.detail;
    this.setData({ date: value })
    this.getData()
  },
    /**
 * 选择月
 */
  changeMonthDate: function (e) {
    const { value } = e.detail;
    this.setData({ month: value })
    this.getMonthData()
  },
})