var app = getApp();
import * as echarts from '../../component/ec-canvas/echarts';

// 柱状图
function weekInitChart(chart, xdata, ydata) {
  var option = {
    color: ['#54585f'],
    tooltip: {
      show: false
    },
    grid: {
      left: 5,
      right: 5,
      bottom: 10,
      top: 10,
      // height: 150,
      // show: true,
      containLabel: true,
      // borderColor: '#c9f1ce'
    },
    xAxis: [
      {
        type: 'category',
        // data: ['周日\n5.11', '周一\n5.12', '周二\n5.13', '周三\n5.14', '周四\n5.15', '周五\n5.16', '周六\n5.17'],
        data: xdata,
        axisLine: {
          lineStyle: {
            color: '#10d9b8',
            width: 0.5
          }
        },
        axisTick:{
          length:0
        },
        axisLabel: {
          color: '#666',
          fontSize: 11,
          lineHeight: 15
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        interval: 10,//强制间隔
        axisTick: { show: false },
        axisLine: {
          show: false //是否显示轴线
        },
        splitLine:{
          lineStyle:{
            color: ['#10d9b8'],
            width: 0.5
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 11
        }
      }
    ],
    series: [
      {
        type: 'bar',
        // silent: true,//不响应和触发鼠标事件
        hoverAnimation: false,//是否开启 hover 在拐点标志上的提示动画效果。
        label: {
          normal: {
            show: true,
            position: 'top',
            // position: 'inside',
            // offset: [0,-6],
            color: '#10d9b8',
            // formatter: function (params) {
            //   if (params.value > 0) {
            //       return params.value;
            //   } else {
            //       return '';
            //   }
            // }
          }
        },
        itemStyle: {
          normal: {
            color: "#10d9b8",
            // color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
            //     offset: 0,
            //     color: "#60d4c6" // 0% 处的颜色
            // },{
            //     offset: 1,
            //     color: "#6be89b" // 100% 处的颜色
            // }], false),
            barBorderRadius: [3, 3, 0, 0] //（顺时针左上，右上，右下，左下）
          }
        },
        data: ydata
      }
    ]
  };

  chart.setOption(option)
}

// 饼状图
let itemGap = 15;
function pieInitChart(chart, legendList, ydata) {
  var option = {
    tooltip: {
      show: false
    },
    color:['#ffa16d','#ffd560','#33edcf','#4dc8f9','#7485f5','#d643f6','#ff6d6d'],
    legend: {
      left: 'center',
      top: 'center',
      orient: 'vertical',
      // top: 10,
      textStyle:{
        color: '#4f5051',
        fontSize: 11
      },
      icon: "circle",
      itemWidth: 8,
      itemHeight: 8,
      itemGap: itemGap,//图例间隔
      data: legendList
    },
    series: [
      {
        // silent: true,//不响应和触发鼠标事件
        hoverAnimation: false,//是否开启 hover 在拐点标志上的提示动画效果。
        type: 'pie',
        // radius : '80%',
        radius: ['52%', '100%'],
        // center: ['50%', '60%'],
        // data:[
        //   {value:48, name:'静态训练'},
        //   {value:28, name:'动态训练'},
        //   {value:24, name:'单词训练'}
        // ],
        data: ydata,
        label:{//饼图图形上的文本标签
          normal:{
            show: true,
            position: 'inner', //标签的位置
            textStyle : {
              fontWeight : 300 ,
              fontSize : 14//文字的字体大小
            },
            formatter: '{d}%'
          }
        }
      }
    ]
  };

  chart.setOption(option);
}

// 左眼视力图
function leftEyeInitChart(chart, dayList, leftVisionList, leftForecastVision) {
  var option = {
    tooltip: {
      show: false
    },
    grid: {
      bottom: 25,
      top: 20,
      right: 10
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#c9f1ce'
        }
      },
      axisTick:{
        length: 0,
      },
      axisLabel:{
        color: '#666',
        fontSize: 11
      },
      boundaryGap: true,
      // data: ["12.31", "1.1", "1.2", "1.3", "1.4", "1.5", "1.5", "1.1", "1.2", "1.3", "1.4", "1.5", "1.5"]
      data: dayList
    },
    yAxis: {
      type: 'value',
      interval: 0.2,//强制间隔
      axisTick: { show: false },
      axisLine: {
        show: false //是否显示轴线
      },
      splitLine:{//网格横线
        lineStyle:{
          color: ['#c9f1ce'],
          width: 1
        }
      },
      axisLabel: {
        color: '#666',
        fontSize: 10,
        showMinLabel: false //显示最小值
      },
      min: function(value) {
        return value.min - 0.2;
      },
      max: function(value) {
        return value.max + 0.2;
      }
    },
    series: [
      {
        name: '训练后',
        // silent: true,//不响应和触发鼠标事件
        hoverAnimation: false,//是否开启 hover 在拐点标志上的提示动画效果。
        type:'line',
        color:['#33D1C4'],
        symbolSize: 13,
        lineStyle: {
          width: 4
        },
        itemStyle:{
          borderWidth: 2//拐点圆边框
        },
        // data:[4.7, 4.7, 4.9, 4.9, 5.1, 5.1, 5.1, 4.7, 4.9, 4.9, 5.1, 5.1, 5.1]
        data:leftVisionList
      },
      {
        name: '未训练',
        symbol:'circle',//实心圆点
        // silent: true,//不响应和触发鼠标事件
        hoverAnimation: false,//是否开启 hover 在拐点标志上的提示动画效果。
        type:'line',
        color:['#f7b500'],
        symbolSize: 6,//拐点圆的大小
        lineStyle: {
          width: 2
        },
        itemStyle:{
          normal:{
            borderColor:'#f7b500',  //拐点边框颜色
          }
        },
        // data:[4.7, 4.5, 4.5, 4.3, 4.3, 4.1, 4.1, 4.5, 4.5, 4.3, 4.3, 4.1, 4.1]
        data: leftForecastVision
      }
    ]
  };

  chart.setOption(option);
}
// 右眼视力图
function rightEyeInitChart(chart, dayList, rightVisionList, rightForecastVision) {
  var option = {
    tooltip: {
      show: false
    },
    grid: {
      bottom: 25,
      top: 20,
      right: 10
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#c9f1ce'
        }
      },
      axisTick:{
        length:0,
      },
      axisLabel:{
        color: '#666',
        fontSize: 11
      },
      boundaryGap: true,
      data: dayList
    },
    yAxis: {
      type: 'value',
      interval: 0.2,//强制间隔
      axisTick: { show: false },
      axisLine: {
        show: false //是否显示轴线
      },
      splitLine:{//网格横线
        lineStyle:{
          color: ['#c9f1ce'],
          width: 1
        }
      },
      axisLabel: {
        color: '#333',
        fontSize: 10,
        showMinLabel: false //显示最小值
      },
      min: function(value) {
        return value.min - 0.2;
      },
      max: function(value) {
        return value.max + 0.2;
      }
    },
    series: [
      {
        name: '训练后',
        // silent: true,//不响应和触发鼠标事件
        hoverAnimation: false,//是否开启 hover 在拐点标志上的提示动画效果。
        type:'line',
        color:['#33D1C4'],
        symbolSize: 13,
        lineStyle: {
          width: 4
        },
        itemStyle:{
          borderWidth: 2
        },
        data: rightVisionList
      },
      {
        name: '未训练',
        symbol:'circle',//实心圆点
        // silent: true,//不响应和触发鼠标事件
        hoverAnimation: false,//是否开启 hover 在拐点标志上的提示动画效果。
        type:'line',
        color:['#f7b500'],
        symbolSize: 6,//拐点圆的大小
        lineStyle: {
          width: 2
        },
        itemStyle:{
          normal:{
            borderColor:'#f7b500',  //拐点边框颜色
          }
        },
        data: rightForecastVision
      }
    ]
  };

  chart.setOption(option);
}

Page({
  data: {
    teenageName: '',
    gender: '',
    age: '',
    avatar: '',
    rightEye: '',
    leftEye: '',
    imgUrls: [],
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    circular: true,
    weekChart: {
      // onInit: weekInitChart
      lazyLoad: true
    },
    pieChart: {
      // onInit: pieInitChart
      lazyLoad: true
    },
    leftEyeChart: {
      // onInit: leftEyeInitChart
      lazyLoad: true
    },
    rightEyeChart: {
      // onInit: rightEyeInitChart
      lazyLoad: true
    },
    trainSortList:[],
    userRanking: '',
    resultSortList:[],
    timerId: '',// 定时器id
    checkImg: '../../assets/indexDefault.png',

    mustUpdate: true,
    status: 1,

    currentSwiper: 0,

    isRun: false,//训练状态
    beginDay: '',
    endDay: '',
    weekDuration: '',//周训练时长
    continuousWeeks: '',//连续训练周数
    surpassRatio: '',//超过人数%
    finishedStatus: '',//训练报告完成状态
    visionAdvice: '',//训练建议

    beginYear: '',//训练成就年数
    totalTrainingDays: '',//训练成就天数
    lastVision: '',//训练成就旧视力
    nowVision: '',//训练成就新视力
  },
  onShow() {
  },
  swiperChange: function(e) {
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  onReady() {
    // setTimeout(function () {
    //   // 获取 chartWeek 实例的方式
    //   console.log(chartWeek)
    // }, 2000);
    let me = this;
    // 请求前加Loading
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: app.globalData.apiUrl + 'users/index',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token')
      },
      success: function (res) {
        // 请求成功后关闭Loading
        wx.hideLoading();
        if(res.data.errno==200){
          // 锁定设备警告状态
          // 1:正常使用设备;
          if(res.data.data.lockDeviceStatus==2){
          // 2:首日警告即将锁定设备提醒;
            me.setData({
              status: 2,
              mustUpdate: false
            })
          }else if(res.data.data.lockDeviceStatus==3) {
          // 3:锁定设备提醒
            me.setData({
              status: 3,
              mustUpdate: false
            })
          }
          if(res.data.data.gender=='2'){//女
            me.setData({
              avatar: '../../assets/head_girl.png',
              gender: '../../assets/icon_girl.png'
            })
          }else{
            me.setData({
              avatar: '../../assets/head_boy.png',
              gender: '../../assets/icon_boy.png'
            })
          }

          me.setData({
            imgUrls: res.data.data.focusMap,

            teenageName: res.data.data.teenageList[0].name,
            gender: res.data.data.teenageList[0].gender,
            age: res.data.data.teenageList[0].age,
            rightEye: res.data.data.teenageList[0].rightEye,
            leftEye: res.data.data.teenageList[0].leftEye,

            continuousWeeks: res.data.data.reports.continuousWeeks,//连续训练周数
            weekNumber: res.data.data.reports.weekNumber,//第几周
            beginDay: res.data.data.reports.beginDay,
            endDay: res.data.data.reports.endDay,
            weekDuration: res.data.data.reports.weekDuration,//周训练时长
            surpassRatio: res.data.data.reports.surpassRatio,//超过人数%
            finishedStatus: res.data.data.reports.finishedStatus,//训练报告完成状态，1：完成；0：未完成
            visionAdvice: res.data.data.reports.visionAdvice,//训练建议
            
            beginYear: res.data.data.achievements.beginYear,//训练成就年份
            totalTrainingDays: res.data.data.achievements.totalTrainingDays,//训练成就天数
            lastVision: res.data.data.achievements.lastVision,//训练成就旧视力
            nowVision: res.data.data.achievements.nowVision,//训练成就新视力

            trainSortList: res.data.data.trainRanking.rankList,//训练排行
            userRanking: res.data.data.trainRanking.userRanking,//训练排行本人

            resultSortList: res.data.data.effectedRanking,//光明之星

          })
          
          let dayTrainingDateList = []
          // let dayTrainingDurationList = [30, 3, 35, 45, 17, 22, 0]
          let dayTrainingDurationList = []
          res.data.data.reports.dayTrainingList.map((item)=>{
            dayTrainingDateList.push(item.title)
            dayTrainingDurationList.push(item.trainingDuration)
          })
          me.selectComponent('#reprotWeekChart').init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            weekInitChart(chart, dayTrainingDateList, dayTrainingDurationList)
            me.chart = chart;
            return chart;
          });

          let legendList = []
          let pieList = []
          res.data.data.reports.typeTrainingList.map((item)=>{
            legendList.push(item.title)
            pieList.push({value: item.trainingDuration,name: item.title})
          })

          if(legendList.length>5){
            itemGap = 5
          }else{
            itemGap = 15
          }
          me.selectComponent('#reprotPieChart').init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            pieInitChart(chart, legendList, pieList)
            me.chart = chart;
            return chart;
          });
          
          // 训练成就日期
          let dayList = res.data.data.achievements.dayList
          // 左眼
          let leftVisionList = res.data.data.achievements.leftVisionList
          let leftForecastVision = res.data.data.achievements.leftForecastVision
          me.selectComponent('#leftEyeChart').init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            leftEyeInitChart(chart, dayList, leftVisionList, leftForecastVision)
            me.chart = chart;
            return chart;
          });
          // 右眼
          let rightVisionList = res.data.data.achievements.rightVisionList
          let rightForecastVision = res.data.data.achievements.rightForecastVision
          me.selectComponent('#rightEyeChart').init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            rightEyeInitChart(chart, dayList, rightVisionList, rightForecastVision)
            me.chart = chart;
            return chart;
          });

        }else{
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg
          })
        }
      }
    })
  },
  onHide() {
  },
  // 权限设置
  set:function(){
    wx.navigateTo({
      url: '/pages/setting/setting'
    })
  },
  // 训练计划
  plan:function(){
    wx.navigateTo({
      url: '/pages/plan/plan'
    })
  },
  // 小目标
  target:function(){
    wx.navigateTo({
      url: '/pages/targetList/targetList'
    })
  },
  // 立即关机
  PowerOff: function () {
    wx.showModal({
      title: '控制提示',
      content: '关机后使用机器时需要再次开机，是否确认关机？',
      success (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          // 请求前加Loading
          wx.showLoading({
            title: '加载中',
            mask: true
          })
          wx.request({
            url: app.globalData.apiUrl + 'devices/close',
            method: 'POST',
            data: {
              token: wx.getStorageSync('token')
            },
            success: function (res) {
              // 请求成功后关闭Loading
              wx.hideLoading();
              if(res.data.errno==200){
                wx.showToast({
                  title: '关机成功！',
                  mask: true,
                  // icon: 'none',
                  duration: 2000
                });
              }else{
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: res.data.msg
                })
              }
            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },
  // 刷新获取设备屏幕图片
  refresh: function () {
    //获取当前时间戳
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);
    // 请求前加Loading
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: app.globalData.apiUrl + 'devices/watchingPic',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        nowTime: timestamp // 当前时间戳，服务端会获取大于当前时间戳的图片信息
      },
      success: function (res) {
        // // 请求成功后关闭Loading
        wx.hideLoading();
        if(res.data.errno==200){
          if(res.data.data){
            console.log(res.data.data.trainingStatus)//训练状态，1正在训练、0：未训练
            console.log(res.data.data.thumb)
            me.setData({
              checkImg: res.data.data.thumb
            })
          }
        }else{
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg
          })
        }
      }
    })
  },
  preventTouchMove() {},
  // 个人中心
  toMine() {
    wx.navigateTo({
      url: '/pages/mine/mine'
    })
  },
  // 训练报告
  trainReport() {
    wx.navigateTo({
      url: '/pages/trainReport/trainReport'
    })
  },
  // 训练排行
  toTrainSort() {
    wx.navigateTo({
      url: '/pages/trainSort/trainSort'
    })
  },
  // 光明之星
  toStarSort() {
    wx.navigateTo({
      url: '/pages/starSort/starSort'
    })
  },
  // 稍后前往
  lastGo: function () {
    // 关闭当前页面
    this.setData({
      mustUpdate: true
    })
  },
  // 一键前往
  nowGo: function () {
    // 关闭当前页面，跳转到 "训练计划"
    wx.navigateTo({
      url: '/pages/plan/plan'
    })
  },
})