const util = require("../../../utils/util.js");
import * as echarts from '../../../components/ec-canvas/echarts.js';
const app = getApp();
Page({
  data: {
    childs:[],
    activity:[],
    actives: [],
    childIndex : 0,
    index : 0,
    ec: {
      lazyLoad: true // 延迟加载
    },
    months : [],
    info : [],
    datas : {
      dtype: 0,
      dayType: 1,
      monthIndex:0,
      deadline: ""
    },
    scrollLeft : 0,
    npsOptons: {},
    npsStatus: false,//nps组件是否显示
    isGet: true,
    edition:2,  //1--旧版本 2--新版本
  },
  onShow() {
    let that = this;
    if (this.data.isGet) {
      if (getCurrentPages().length == 1) {
        // var getLocation = util.promise();
        // getLocation.then(function (value) {
          that.getChild();
          that.setData({ currentPages: getCurrentPages().length })
        // }, function (error) {
        // });
      } else {
        that.getChild();
      }
    }
  },
  // 折线图绘制
  chartInit(type,idname,dataX,dataY){
    this.data.info.xarr=dataX;
    if (util.isObjEmpty(this.data.info.xarr)) return false;
    let columns = [], that = this;
    for (let i in this.data.info.xarr){
      columns.push({
        value: this.data.info.xarr[i],
        textStyle: {
          color: '#908f90'
        }
      });
    }
    this.selectComponent(idname).init((canvas, width, height) => {
      // 初始化图表
      var Chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      Chart.clear();
      let options = {
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            interval:0,
            rotate: dataX.length>6?40:0
          },
          data: columns
        },
        yAxis: {
          show: true,
          type: 'value'
        },
        grid: {
          left: '0',
          right: '0',
          bottom: '10%'
        },
        series: [{
          name:"喝水",
          type: 'line',
          // barWidth: 38,
          stack: '总量',
          label: {
            show: true,
            position: 'top',
            formatter: idname=='#mychart'?'{c}瓶':'{c}度',
            color: '#ee3a43'
          },
          itemStyle: {
            color:'#ffccd3'
          },
          data: dataY
        }]
      };
      if(type == 0){
        options.grid = {
          left: '8%',
          right: '5%',
          bottom: '40%'
        };
        options.dataZoom = [{
          type:'inside',
          start: 0,
          end: 100
        },{
          type: 'slider',
          showDetail:false,
          showDataShadow:true,
          handleStyle:{
            borderColor:'#ee3a43',
            borderWidth:0
          },
          backgroundColor:'#fff0f3',
          handleSize:'60%',
          // handleIcon:'path://M30.9,53.2c-14.1,0-25.6-11.5-25.6-25.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z'
        }];
      }
      Chart.setOption(options);
      return Chart;
    });
  },
  
  selectImage(e) {
    this.setData({ isGet: e.detail.isGet });
  },
  close(e) {//关闭nps
    this.setData({ npsStatus: false });
  },
  getChild(){
    let that = this;
    util.ajax({
      func: "user/childs",
      load: false
    }, function (res) {
      if (res.code == 0) {
        that.setData({ childs : res.data });
        if(!util.isObjEmpty(that.data.childs)){
          that.getActivity();
          wx.setNavigationBarTitle({
            title: that.data.childs[that.data.childIndex].name
          });
        }
      }
    });
  },
  getActivity(){
    let that = this;
    util.ajax({
      func: "daily/activity_list",
      data: {"idcard": that.data.childs[that.data.childIndex].cardNo, "cardType": that.data.childs[that.data.childIndex].cardType},
      load: false
    }, function (res) {
      if (res.code == 0) {
        that.setData({ activity: res.data });
        that.jsonDataArr();
        that.getDate();
      }else
        util.showTips(res.reason);
    });
  },
  jsonDataArr() {
    let self = this, arr = [];
    for (var i = 0; i < self.data.activity.length; i++) {
      arr.push(self.data.activity[i].sname + " " + self.data.activity[i].pstitle);
      // arr.push(self.data.activity[i].text)
    }
    this.setData({ actives: arr });
  },
  getInfo(){
    let that = this,sendData = {},deadlineStart='',deadlineEnd='';
    if (that.data.datas.dtype==1&&that.data.months.length>0) {
      deadlineStart = util.formatDate(util.formatUnixtimestamp(that.data.months[0].value), "MM月dd日", false);
      deadlineEnd = util.formatDate(util.formatUnixtimestamp(that.data.months[that.data.months.length-1].value), "dd日", false);
    }
    sendData['teamId'] = that.data.activity[that.data.index].teamId || '';
    sendData['dtype'] = that.data.datas.dtype;
    sendData['sid'] = that.data.activity[that.data.index].sid;
    sendData['childId']= that.data.activity[that.data.index].childId;
    sendData['deadline'] = that.data.datas.deadline;
    sendData['summary'] = 1;
    util.ajax({
      func: that.data.datas.dtype == 1 ? "v2/daily/summary/info" : "v2/daily/info", //v2/daily/summary/info ——总结记录 v2/daily/info ——每日记录
      data: sendData
    },function(res){
      if(res.code == 0){
        if (res.data) {
          if(that.data.datas.dtype == 0 && res.data.id){
            res.data.deadlineText = util.formatDate(res.data.deadline, "MM月dd日", false);
            res.data.remark = res.data.fight == 0 && res.data.hurt == 0 && res.data.illness == 0 ? '活动中和小朋友和睦相处，身体无受伤并没有不适情况' + res.data.remark : res.data.remark;
            res.data.score = res.data.score.toFixed(1);
          }
          if (that.data.datas.dtype == 1) {
            if (!res.data.versionNum || res.data.versionNum==2) {
              let dateArr=[];
              if (res.data.xdeadlineArr && res.data.xdeadlineArr.length>0) {
                res.data.xdeadlineArr.forEach(el => {
                  let arr = el.split('-')
                  dateArr.push(arr[1]+'-'+arr[2])
                });
              }
              setTimeout(() => {
                if (res.data.ydrinkArr.length>0) {
                that.chartInit(dateArr.length>4?0:1,'#mychart',dateArr,res.data.ydrinkArr)
                }
                if (res.data.ytemperatureArr.length>0) {
                that.chartInit(dateArr.length>4?0:1,'#mychart1',dateArr,res.data.ytemperatureArr)
                }
              }, 500);
            }
              res.data.deadlineStart = deadlineStart;
              res.data.deadlineEnd = deadlineEnd;
          }
        }
        that.setData({ info : res.data,edition:res.data? (res.data.versionNum || 2):2});
      }else{
        util.showTips(res.reason);
      }
    });
  },
  getDate(){
    let that = this, months = [];
    if (!util.isObjEmpty(that.data.activity[that.data.index])){
      that.data.datas.dayType = that.data.activity[that.data.index].single;
      if (that.data.activity[that.data.index].single == 1) {
        if (that.data.activity[that.data.index].start != undefined) {
          that.data.datas.deadline = util.formatDate(util.formatUnixtimestamp(that.data.activity[that.data.index].start.time), "yyyy-MM-dd", false);
        }else{
          that.data.datas.deadline = "";
        }
      } else {
        if (that.data.activity[that.data.index].start != undefined && that.data.activity[that.data.index].end != undefined) {
          months = util.formatMonth(that.data.activity[that.data.index].start.time, that.data.activity[that.data.index].end.time);
          that.data.datas.monthIndex = 0;
          for (let i in months){
            if(months[i].active == 1){
              that.data.datas.monthIndex = i;
            }
          }
          that.data.datas.deadline = months[that.data.datas.monthIndex].value;
        }else{
          that.data.datas.deadline = "";
        }
      }
      that.setData({
        months: months,
        datas: that.data.datas
      });
      if (!util.isEmpty(that.data.datas.deadline)) that.getInfo();
    }
  },
  bindPickerChange(e){
    this.data.datas.dtype = 0;
    this.data.datas.dayType = 1;
    this.data.datas.deadline = "";
    this.data.datas.monthIndex = 0;
    this.setData({ childIndex: e.detail.value, index: 0, datas: this.data.datas, scrollLeft: 0, info: {}, months:[] });
    wx.setNavigationBarTitle({
      title: this.data.childs[this.data.childIndex].name
    })
    this.getActivity();
  },
  bindPickerActivity(e){
    this.data.datas.dtype = 0;
    this.data.datas.dayType = 1;
    this.data.datas.deadline = "";
    this.data.datas.monthIndex = 0;
    this.setData({ index: e.detail.value, datas: this.data.datas, scrollLeft: 0 });
    this.getDate();
  },
  copy(e){
    let self = this, s_type = e.currentTarget.dataset.type, data = "";
    switch (s_type){
      case "remark":
        data = self.data.info.remark;
      break;
      case "expression":
        data = self.data.info.expression;
      break;
      case "s_remark":
        data = self.data.info.s_remark || "";
      break;
      case "s_expression":
        for (let i in self.data.info.expressionList) {
          data += self.data.info.expressionList[i].deadline + "：" + self.data.info.expressionList[i].expression+"\n";
        }
        if (self.data.info.s_expression) data += "总结：" + self.data.info.s_expression;
      break;
    }
    wx.setClipboardData({
      data: data,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        });
      }
    });
  },
  showTab(e){
    let data = e.currentTarget.dataset;
    this.data.datas.dtype = data.dtype;
    this.data.datas.deadline = data.deadline;
    this.data.datas.monthIndex = data.monthindex;
    this.setData({ datas: this.data.datas, scrollLeft: e.currentTarget.offsetLeft });
    this.getInfo();
  },
  onShareAppMessage() {
    return {
      title: '儿童参加活动的生活记录',
      path: '/pages/account/take/take'
    }
  }
})