var app = getApp();
var that;
var chart1;
var chart2;
Page({
  data: {
    userData: {},
    isBh: false,
    chartData: [],//折线图数据
    pieData: [1],//饼型图数据
  },
  onLoad() {
    that = this;
    chart1, chart2 = '';
  },
  onShow(query) {
    // that.getUserData();
    // that.getIncidentLsit();
    // that.getIncidentNum();
    if (app.globalData.userData) {
      that.getUserData();
      that.getIncidentLsit();
      that.getIncidentNum();
    } else {
      app.login(app.globalData.corpId, function (is) {
        if (is) {
          that.getUserData();
          that.getIncidentLsit();
          that.getIncidentNum();
        } else {
          dd.reLaunch({
            url: '../noJurisdiction/noJurisdiction'
          })
        }
      })
    }
  },
  showText() {
    this.setData({ isBh: !this.data.isBh })
  },
  //跳转
  openView(e) {
    var index = e.target.dataset.index - 1;
    var urls;
    if (e.target.dataset.item) {
      urls = [
        { url: '../statistics_B/statistics_B', query: '' },
        { url: '../statistics_A/statistics_A', query: '' },
        { url: '../jk_B/jk_B', query: 'type=B' },
        { url: '../jk_B/jk_B', query: 'type=A' },
        { url: '../apply/apply', query: '' },
        { url: '../my_approve/my_approve', query: '' },
        { url: '../prize_buckle/prize_buckle', query: '' },
        { url: '../../statistics/prizeBuckleDetail/prizeBuckleDetail', query: 'id=' + e.target.dataset.item.id },
        { url: '../../statistics/integralEvent/integralEvent', query: '' },
      ];
    } else {
      urls = [
        { url: '../statistics_B/statistics_B', query: '' },
        { url: '../statistics_A/statistics_A', query: '' },
        { url: '../jk_B/jk_B', query: 'type=B' },
        { url: '../jk_B/jk_B', query: 'type=A' },
        { url: '../apply/apply', query: '' },
        { url: '../my_approve/my_approve', query: '' },
        { url: '../prize_buckle/prize_buckle', query: '' },
        { url: '../../statistics/prizeBuckleDetail/prizeBuckleDetail', query: '' },
        { url: '../../statistics/integralEvent/integralEvent', query: '' },
      ];
    }
    dd.navigateTo({
      url: urls[index].url + '?' + urls[index].query
    })
  },
  //则线图
  onInitChart(F2, config) {
    chart1 = new F2.Chart(config);
    chart1.source(that.data.chartData, {
      date: {
        // range: [0, 1],
        tickCount: 5
      }
    });
    chart1.tooltip({
      showCrosshairs: true,
      showItemMarker: false,
      onShow: function onShow(ev) {
        const items = ev.items;
        items[0].name = "月份:" + items[0].origin.date;
        items[0].value = "分值:" + items[0].value;
      }
    });
    chart1.line().position('date*value');
    chart1.point().position('date*value').style({
      stroke: '#fff',
      lineWidth: 1
    });
    chart1.render();
    return chart1;
  },
  //饼型图
  onInitChart2(F2, config) {
    chart2 = new F2.Chart(config);
    chart2.source(that.data.pieData, {
      percent: {
        formatter: function formatter(val) {
          return val * 100 + '%';
        }
      }
    });
    chart2.legend({
      position: 'right',
      itemFormatter: function itemFormatter(val, index) {
        var str = '';
        that.data.pieData.forEach(item => {
          if (item.name == val) {
            str = val + '  ' + item.point + '分';
          }
        })
        return str;
      }
    });
    chart2.tooltip(false);
    chart2.coord('polar', {
      transposed: true,
      radius: 0.85
    });
    chart2.axis(false);
    chart2.interval()
      .position('a*percent')
      .color('name', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0'])
      .adjust('stack')
      .style({ lineWidth: 1, stroke: '#fff', lineJoin: 'round', lineCap: 'round' }).animate({
        appear: { duration: 1200, easing: 'bounceOut' }
      });
    chart2.render();
    // 注意：需要把chart return 出来
    // that.getLsit();
    return chart2;
  },
  //获取统计数据
  getLsit() {
    var date1 = new Date();
    var date2 = new Date(date1);
    date2.setDate(date1.getDate() - 30);
    var start_date= date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();

    var incident = app.$get("api/integral/statistics/b", { employee_id: 0, start_date: start_date, end_date: app.globalData.day, show_type: '1' });
    var pei = app.$get("api/integral/statistics/pie/b", { employee_id: 0, month: that.data.date });
    Promise.all([incident, pei]).then(resArr => {
      if (resArr[0].data.code == 1) {
        const { b, chart, good, bad } = resArr[0].data.data
        const points = chart.reward.map((rewardItem, index) => {
          return { date: rewardItem.date, value: rewardItem.point - (chart.deduction[index].point || 0) }
        })
        chart1.changeData(points);
        that.setData({
          data_b: b,
          data_good: good,
          data_bad: bad,
        });
      }
      if (resArr[1].data.code == 1) {
        const pieData = resArr[1].data.data.list.map((item) => {
          return { name: item.name, percent: item.point < 0 ? 0 : item.point, a: '1',point:item.point }
        })
        var isData=pieData.every(itme=>{
            return itme.percent == 0;
         })
        that.setData({
          pieData:isData?[]:pieData
        });
        chart2.changeData(pieData);
      }
    }).catch(e => {
      console.error(e)
    })
  },

  //获取个人统计
  getUserData() {
    app.$get("api/integral/statistics", { employee_id: 0, month: app.globalData.month }).then((res) => {
      var data = res.data.data;
      var task = data.task;
      dd.setNavigationBar({ title: data.name });
      var ratio = task.reward.point === 0 || task.deduction.point === 0 ? '-' : `${task.ratio.ratio}:1`
      var target_ratio = task.ratio.target_ratio <= 0 ? '0:0' : `${task.ratio.target_ratio}:1`
      data.ratio = {
        ratio: ratio,
        target_ratio: target_ratio
      }
       that.getLsit();
      this.setData({
        userData: data
      })
    }, (err) => { })
  },
  //获取积分事件
  getIncidentLsit() {
    app.$get("api/integral/statistics/integral", { month: app.globalData.month, page: 1, page_size: 5,employee_ids:app.globalData.userData.id }).then((res) => {
      var data = res.data.data.list;
      data.map((item) => {
        item.ptObj = app.getTypesItem(item.pt_id);
      })
      this.setData({
        incidentLsit: data,
        incidentLsitTotal: res.data.data.total
      })
    }, (err) => { })
  },

  getIncidentNum() {
    app.$get("api/integral/review/list", { type: 'waiting', page: 1, pt_id: 0 }).then((res) => {
      var data = res.data.data;
      this.setData({
        total: data.total
      })
    }, (err) => { })
  },
});
