var app = getApp();
var that;
var chart1;
var chart2;
var chart3;
var AParse = require('../../../Component/aParse/aParse.js');
Page({
  data: {
    userData: {},
    isBh: false,
    chartData: [],//折线图数据
    pieData: [1],//饼型图数据
    isAdministrator: app.globalData.isAdministrator,//是否管理员角色
    rankingTotal: 0,
    rankingList: [],
    getRole_four: app.globalData.isCreator,//是否创始人
    setECharts: [],//柱形图数据
    pieTotal: 1,
    total:'',
    menuList: [
      { name: '审批', imgUrl: '../../../image/sp.png', url: '../my_approve/my_approve', code: 'creator admin' },
      { name: '任务', imgUrl: '../../../image/a7.png', url: '../../statistics/my_task/my_task', code: 'admin employee' },
      { name: '奖扣B分', imgUrl: '../../../image/point_entry.png', url: '../jk_B/jk_B?type=B', code: 'creator admin' },
      { name: '指派任务', imgUrl: '../../../image/my_publish.png', url: '../../statistics/assaign/assaign', code: 'creator admin' },
      { name: '申请积分', imgUrl: '../../../image/a_apply.png', url: '../apply/apply', code: 'admin employee' },
      { name: '奖扣A分', imgUrl: '../../../image/a_entry.png', url: '../jk_B/jk_B?type=A', code: 'creator admin' },
      { name: '领任务', imgUrl: '../../../image/task_hall.png', url: '../../statistics/getTask/getTask', code: 'admin employee' },
      { name: '发布悬赏', imgUrl: '../../../image/caback6.png', url: '../../statistics/offerAreward/offerAreward', code: 'creator admin' },
      { name: '发放奖票', imgUrl: '../../../image/add_ticket.png', url: '../../statistics/grant/grant', code: 'creator admin' },
      { name: '全部', imgUrl: '../../../image/all2.png', url: 'all', code: 'creator admin employee' },
    ],
    isUpdate:false,
    title:'',//系统消息标题
    textId:''//系统消息ID
  },
  onLoad() {
    that = this;
    chart1, chart2, chart3 = '';
  },
  onShow() {
    if (app.globalData.userData) {
      that.getUserData();
      that.getGg();
      that.setData({ isAdministrator: app.globalData.isAdministrator, getRole_four: app.globalData.isCreator })
    } else {
      app.login(app.globalData.corpId, function (is) {
        if (is) {
          if(app.globalData.isCreator){
            that.setMenuList("creator");
          }else if(app.globalData.isAdministrator){
            that.setMenuList("admin");
          }else if(!app.globalData.isCreator&&!app.globalData.isAdministrator){
            that.setMenuList("employee");
          }
          that.getGg();
          that.getUserData();
          that.setData({ isAdministrator: app.globalData.isAdministrator, getRole_four: app.globalData.isCreator })
        } else {
          dd.reLaunch({
            url: '../noJurisdiction/noJurisdiction'
          })
        }
      })
    }
  },
  openUrl(e){
    var url = e.target.dataset.url;
    if(url=='all'){
      dd.switchTab({
        url: '../../statistics/index/index'
      })
      return
    }
    dd.navigateTo({
      url: url
    })
  },
  openText(){
    that.colseText();
    dd.navigateTo({
      url: '../../deploy/upgradeDetail/upgradeDetail?id='+that.data.textId
    })
  },
  //获取缓存的公告
  getReviewerObj(fuc) {
    dd.getStorage({
      key: 'isShowMessage',
      success: function (res) {
        if (res.data) {
          fuc(res.data);
        } else {
          fuc({});
        }
      }
    });
  },
  // 获取公告
  getGg(){
    if(that.data.title){
      return
    }
    app.$get("api/announcement/list", {page: 1, page_size: 1}).then((res) => {
      var data = res.data.data.list[0];
      AParse.aParse('article', 'html', data.focus, that, 5); 
      that.setData({
        title:data.title,
        textId:data.id
      });
      that.getReviewerObj(function(res){
          if(res!=data.id){
              that.colseText();
              dd.setStorage({
                    key: 'isShowMessage',
                    data: data.id,
              });
          }
      })
    })
  },
  setMenuList(str){
      var arr=[];
      that.data.menuList.forEach(item=>{
        if(item.code.indexOf(str)>=0){
            arr.push(item)
        }
      })
      that.setData({
        menuList:arr
      })
  },
  colseText(){
    this.setData({isUpdate: !this.data.isUpdate })
  },
  showText() {
    this.setData({ isBh: !this.data.isBh })
  },
  openViewRanking(e) {
    var item = e.target.dataset.item;
    var url = '';
    if (item.type == 'normal') {
      url = '../../statistics/sectionRanking/sectionRanking';
    } else if (item.type == 'all') {
      url = '../../statistics/B_ranking/B_ranking';
    } else {
      url = '../../statistics/C_ranking/C_ranking?id=' + item.target_id + '&name=' + item.group_name + '&date_interval=' + item.date_interval;
    }
    dd.navigateTo({
      url: url
    })
  },
  //跳转
  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: '' },
        { url: '../../statistics/userRamking/userRamking', query: '' },
        { url: '../../statistics/glz_execute/glz_execute', 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: '' },
        { url: '../../statistics/userRamking/userRamking', query: '' },
         { url: '../../statistics/glz_execute/glz_execute', query: '' },
      ];
    }
    dd.navigateTo({
      url: urls[index].url + '?' + urls[index].query
    })
  },
  //则线图
  onInitChart(F2, config) {
    chart1 = new F2.Chart(config);
    chart1.source(that.data.chartData, {
      date: { tickCount: 4 }
    });
    chart1.tooltip({
      showCrosshairs: true,
      showItemMarker: true,
      onShow: function onShow(ev) {
        const items = ev.items;
        items[0].name = "月份:" + items[0].origin.date;
        items[0].value = "分值:" + items[0].value;
      }
    });
    chart1.axis('date', {
      label: function label(text, index, total) {
        const textCfg = {};
        if (index === 0) {
          textCfg.textAlign = 'left';
        } else if (index === total - 1) {
          textCfg.textAlign = 'right';
        }
        return textCfg;
      }
    });
    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;
  },
  //柱形图
  onInitChart3(F2, config) {
    chart3 = new F2.Chart(config);
    chart3.source(that.data.setECharts, {
      date: { tickCount: 5 }
    });
    chart3.axis('field', {
      grid: {
        lineDash: null,
        stroke: '#e8e8e8',
        lineWidth: 1
      }
    });
    chart3.legend(false);
    chart3.interval().position('name*val').color('type', (type) => { // 通过回调函数
      if (type === '奖分') {
        return 'l(90) 0:#4ECFFF 1:#26A2FF';
      }
      return 'l(90) 0:#F8C748 1:#F2A640';
    }).adjust({
      type: 'dodge',
      marginRatio: 0.05 // 设置分组间柱子的间距
    });
    chart3.render()
    return chart3;
  },
  //获取统计数据
  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.$get2("api/integral/statistics/b", { employee_id: 0, start_date: start_date, end_date: app.globalData.day, show_type: '1' });
    Promise.all([incident]).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,
        });
      }
    }).catch(e => {
      console.error(e)
    })
  },

  //获取个人统计
  getUserData() {
    var http1 = app.$get2("api/integral/statistics", { employee_id: 0, month: app.globalData.month })
    var http2 = app.$get2("api/integral/statistics/integral", { month: app.globalData.month, page: 1, page_size: 5, employee_ids: app.globalData.userData.id })
    var http3 = app.$get2("api/integral/review/list", { type: 'waiting',source_type:0, page: 1, pt_id: 0 })
    var ranking = app.$get('api/integral/statistics/ranking/list', { page: 1, page_size: 5 })// 获取排行榜
    var task = app.$get('api/integral/statistics/task/pie', { month: app.globalData.month })// 管理者奖扣任务柱状图
    var work = app.$get('api/integral/work/list', { status: 'running',page: 1,pt_id: 0, source_type: 0})// 管理者奖扣任务柱状图
    Promise.all([http1, http2, http3, ranking, task,work]).then(function (values) {
      if (values[0]) {
        let data = values[0].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();
        that.setData({
          userData: data
        })
      }
      if (values[1]) {
        let data = values[1].data.data.list;
        data.map((item) => {
          item.ptObj = app.getTypesItem(item.pt_id);
        })
        that.setData({
          incidentLsit: data,
          incidentLsitTotal: values[1].data.data.total
        })
      }
      if (values[2]) {
        let data = values[2].data.data;
        that.setData({
          total: data.total
        })
      }
      if (values[3]) {
        that.setData({
          rankingList: values[3].data.data.list,
          rankingTotal: values[3].data.data.total
        })
      }
      if (values[4]) {
        if (that.data.isAdministrator) {
          var data = values[4].data.data.list
          if (data.length > 5) {
            data.pop()
          }
          that.setData({
            pieTotal: values[4].data.data.total
          })
          if (that.data.pieTotal != 0) {
            var employees = [];
            data.forEach((item) => {
              var obj = [{
                type: '奖分',
                name: item.employee_name,
                val: item.deduction
              }, {
                type: '扣分',
                name: item.employee_name,
                val: item.reward
              }]
              employees.push(...obj)
            })
            chart3.changeData(employees);
          }
        }
      }
      if (values[5]) {
        let data = values[5].data.data;
        that.setData({
          workTotal: data.total
        })
      }
    })
  },
  //获取积分事件
  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) => { })
  },
});
