var app = getApp();
var that;
var animation;
var chart1;
var chart2;
import { setCache, getCache } from '../../../utils/util'
Page({
  data: {
    tabIndex: 1,
    isShowType: false,
    defaultRuleId: '',
    jxName: '',

    theProgressOf: {
      complete: 0,
      theTotalNum: 0
    },
    currentRate: 0,
    rate: 0,

    page: 1,
    isVal: false,
    keyword: '',
    list: [],
    statementHnList: [
      { tit: '参与人数', num: 0, key: 0 },
      { tit: '目标制定', num: 0, key: 1 },
      { tit: '目标确认', num: 0, key: 2 },
      { tit: '执行中', num: 0, key: 3 },
      { tit: '结果值录入', num: 0, key: 4 },
      { tit: '评分', num: 0, key: 5 },
      { tit: '审批', num: 0, key: 9 },
      { tit: '考核结束', num: 0, key: 11 }
    ],
    // 部门筛选
    department_list: [],
    department_index: 0,
    // 部门筛选
    levels_list: [],
    levels_index: 0,

    statementperson: [],

    jxUserList: [],//结果分析人员列表
    selectPftiData: {},//选择的绩效
  },
  onLoad() {
    that = this;
    chart1, chart2 = '';
    dd.setNavigationBar({ title: "报表统计" });
    this.getRange();
  },
  onShow() {
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
  },
  personnel_detailsPath(e) {
    let index = e.target.dataset.index
    let data = {
      paths: 'personnelDetail',
      asslist: this.data.selectPftiData,
      index: index,
    }
    setCache('statementDetails', data)
    dd.navigateTo({
      url: `../statementDetails/statementDetails`
    })
  },
  cellDept(e) {
    let item = e.target.dataset.item
    let data = {
      paths: 'statdeEcharts',
      dept_o: item,
      asslist: this.data.selectPftiData,
      index: 0,
    }
    setCache('statementDetails', data)
    dd.navigateTo({
      url: `../statementDetails/statementDetails`
    })
  },
  openDetail(e) {
    let item = e.target.dataset.item
    let str = `../performanceDetails/performanceDetails?assId=${this.data.selectPftiData.id}&staffId=${item.id}&tel=${this.data.selectPftiData.name}`
    dd.navigateTo({
      url: str
    })
  },
  // 结果分析人员列表
  isShow() {
    let arr = [];
    this.setData({
      jxUserList: []
    })
    this.data.allStatementResult.map(item => {
      if (this.isQualified(item)) {
        item.name = app.globalData.usersList[item.id].name
        arr.push(item);
      }
    });
    setTimeout(() => {
      this.setData({
        jxUserList: arr
      })
    }, 200)
  },
  isQualified(item) {
    let deptId = this.data.department_list[this.data.department_index].value
    let level = this.data.levels_list[this.data.levels_index].value
    if (deptId == 0 && level == '-') {
      return true;
    }
    let isDept = false,
      isLevel = false;
    if (deptId != 0) {
      item.departments.some(e => {
        if (e.id == deptId) {
          isDept = true;
          return true;
        }
      });
    }
    if (item.level == level || level == '-') {
      isLevel = true;
    }
    if (deptId == 0) {
      isDept = true;
    }
    return isDept && isLevel;
  },

  statisticalPeople() {
    this.setData({
      department_index: 0,
      levels_index: 0,
    })
    let params = {
      package_id: this.data.defaultRuleId,
    };
    app.$get('api/per/package/info_v3_aid', params).then(res => {
      if (res.data.code == 1) {
        this.skeletonLoad = false;
        let data = res.data.data.statistics;
        let list = this.data.statementHnList;
        let theOf = this.data.theProgressOf;
        let all = 0
        for (let i in data) {
          all += data[i]
        }
        list[0].num = all; // 参与人数
        list[1].num = data[1]; // 目标制定
        list[2].num = data[2]; // 目标确认
        list[3].num = data[3]; // 执行中
        list[4].num = data[4]; // 结果值录入
        list[5].num = data[5]; // 评分
        list[6].num = data[9]; // 审批
        list[7].num = data[11]; // 结束
        theOf.complete = data[11]; // 已完成人数
        theOf.theTotalNum = all; // 总人数
        let rate = (theOf.complete / theOf.theTotalNum) * 100; // 进度条百分比
        if (!isNaN(rate)) {
          this.setData({// 进度条百分比
            rate: rate.toFixed(2),
          })
        }
        this.setData({// 进度条百分比
          theProgressOf: theOf, //考核进度
          statementHnList: list
        })
        //部门筛选
        let other = res.data.data.other
        let department_list = other.department_list;
        department_list.forEach(item => {
          item.text = item.dep_name;
          item.value = item.id;
        });
        department_list.unshift({ text: '全部部门', value: 0 });
        this.setData({// 部门筛选
          department_list: department_list,
        })

        //等级筛选
        let levels = other.levels;
        if (levels.indexOf('无等级') == -1) {
          levels.push('无等级')
        }
        levels = levels.map(item => {
          return { text: item, value: item };
        });
        levels.unshift({ text: '全部等级', value: '-' });
        this.setData({// 等级筛选
          levels_list: levels,
        })
        let departMent = other.department;
        // this.deptMentList = departMent;

        // 考核人数分析
        let deptList = [];
        let assPeopleFx = [];
        departMent.forEach(item => {
          // echarts数据
          assPeopleFx.push({
            year: item[0].dep_name,
            sales: item.length
          })
          // 列表
          let arr = {};
          arr.name = item[0].dep_name;
          arr.tak = item.length;
          arr.id = [item[0].id]
          let employ = [];
          item.forEach(arr => {
            employ.push(arr.employee_id);
          });
          deptList.push(arr);
        });
        this.setData({// 考核人数列表
          statementperson: deptList,
          assPeopleFx: assPeopleFx,
        })

        // 结果分析
        let statistics = other.statistics;
        let theResultsOfNum = [];
        let PieProps = 0;
        for (let i in statistics) {
          theResultsOfNum.push({
            name: i == 'empty' ? '无等级' : i,
            percent: '',
            num: statistics[i].length,
            a: '1'
          })
          PieProps += statistics[i].length;
        }
        theResultsOfNum.forEach(item => {//设置百分比
          let bfb = (Math.round(item.num / PieProps * 10000) / 100.00);
          if (bfb !== bfb) { bfb = 0; };
          item.percent = bfb
        })
        this.setData({// 总人数
          PieProps: PieProps,
          theResultsOfNum: theResultsOfNum
        })

        if (this.data.tabIndex == 1) {
          this.statmentAnalysesPie();
        } else {
          this.statmentAnalysesBar()
        }

        let theResultsOfList = [];
        res.data.data.employees.forEach(item => {
          let data = {
            id: item.id,
            name: item.name,
            level: item.final_level == '' ? '无等级' : item.final_level,
            point: item.final_point,
            departments: []
          }
          res.data.data.other.department.forEach(x => {
            let arr = x.filter(y => item.id == y.employee_id)
            if (arr[0]) {
              data.departments.push(arr[0])
            }
          })
          theResultsOfList.push(data)
        })
        theResultsOfList.sort(function (a, b) {
          if (Number(a.point) < Number(b.point)) {
            return 1;
          } else {
            return -1;
          }
        });
        this.setData({
          allStatementResult: theResultsOfList,
        })
        this.isShow();
      }
    })
  },
  // 柱状图
  statmentAnalysesBar() {
    chart2.changeData(this.data.assPeopleFx)
  },
  // 饼图
  statmentAnalysesPie() {
    const data = this.data.theResultsOfNum;
    const map = [];
    data.forEach(function (obj) {
      map[obj.name] = obj.num + '人 ' + obj.percent + '%'
    });
    chart1.legend({
      position: 'right',
      itemFormatter: function itemFormatter(val) {
        return val + '    ' + map[val];
      }
    });
    chart1.changeData(data)
  },
  getRange() {
    app.$get("api/per/package/list", { page: 0, is_manage_scope: 1 }).then((res) => {
      let obj = res.data.data.list;
      let arr = [
        { name: '月度', id: 2, list: [] },
        { name: '日', id: 1, list: [] },
        { name: '季度', id: 3, list: [] },
        { name: '半年度', id: 4, list: [] },
        { name: '年度', id: 5, list: [] },
        { name: '自定义', id: 6, list: [] }
      ];
      obj.forEach(item => {
        arr.forEach(item2 => {
          if (item2.id == item.cycle_type) {
            item2.list.push(item);
          }
        });
      });
      let data = arr;
      let list = [];
      data.forEach(item => {
        if (item.list.length > 0) {
          list.push(item);
        }
      });
      list.some(item => {
        if (item.list.length > 0) {
          obj = item.list
          return true;
        }
      });
      that.setData({
        selectPftiData: obj.length>0 ? obj[0] : '',
        defaultRuleId: obj.length>0 ? obj[0].id : '',
        jxName: obj.length>0 ? obj[0].name : '',
      })
      if (obj.length>0) {
        this.statisticalPeople();
      }
    })
  },
  onInitChart2(F2, config) {
    const data = [];
    chart2 = new F2.Chart(config);
    chart2.source(data);
    // chart2.tooltip({
    //   showItemMarker: false,
    //   onShow: function onShow(ev) {
    //     const items = ev.items;
    //     items[0].name = null;
    //     items[0].name = items[0].title;
    //     items[0].value = '¥ ' + items[0].value;
    //   }
    // });
    chart2.interval().position('year*sales').size(30).color('l(90) 0:#4ECFFF 1:#26A2FF'); // 定义柱状图渐变色
    chart2.render();
  },
  // 饼图
  onInitChart(F2, config) {
    const data = [];
    const map = [];
    data.forEach(function (obj) {
      map[obj.name] = obj.num + '项    ' + obj.percent + '%';
    });
    chart1 = new F2.Chart(config);
    chart1.source(data, {
      percent: {
        formatter: function formatter(val) {
          return val * 100 + '%';
        }
      }
    });
    chart1.tooltip(false);
    chart1.coord('polar', {
      transposed: true,
      radius: 0.85
    });
    chart1.axis(false);
    chart1.interval()
      .position('a*percent')
      .color('name', ['#1890FF', '#F56C6C', '#2FC25B', '#FACC14', '#F04864', '#8543E0'])
      .adjust('stack')
      .style({
        lineWidth: 1,
        stroke: '#fff',
        lineJoin: 'round',
        lineCap: 'round'
      })
      .animate({
        appear: {
          duration: 1200,
          easing: 'bounceOut'
        }
      });
    chart1.render();
  },
  getPrizeList(is) {
    let data = {
      page: this.data.page,
      page_size: 20,
      package_id: this.data.defaultRuleId,
      name: this.data.keyword,
      range: this.data.minuteArray[this.data.minuteIndex].value,
    }
    let str = 'api/per/package/management_record';
    app.$get(str, data).then((res) => {
      var data = res.data.data.list;
      if (that.data.page == 1) { this.setData({ list: [] }) }
      var list = that.data.list;
      if (is) {
        if (data.length < 20) {
          this.setData({ list: list.concat(data), isData: true })
        } else {
          this.setData({ list: list.concat(data) })
        }
      } else {
        this.setData({
          list: data,
          isData: false
        })
      }
    })
  },
  activeItem(e) {
    this.setData({ department_index: e.detail.value })
    this.isShow()
  },
  activeItem2(e) {
    this.setData({ levels_index: e.detail.value })
    this.isShow()
  },
  tabAction(e) {
    this.setData({
      tabIndex: e.target.dataset.index
    })
    if (e.target.dataset.index == 1) {
      setTimeout(() => {
        this.statmentAnalysesPie();
      }, 500)
    } else {
      setTimeout(() => {
        this.statmentAnalysesBar();
      }, 500)
    }
  },
  onChange(e) {
    console.log(e.detail.value);
  },
  //选择弹窗
  openSelect(e) {
    animation.translateY(0).step();
    that.setData({
      isShowType: true,
      animationInfo: animation.export(),
      popupCx: 'container__mask',
    });
  },
  //关闭规则
  onClose() {
    animation.translateY(1200).step();
    that.setData({
      isShowType: false,
      animationInfo: animation.export(),
      popupCx: '',
    });
  },
  onSelectItem(e) {
    that.setData({
      defaultRuleId: e.id,
      jxName: e.name,
      selectPftiData: e
    });
    this.statisticalPeople();
  },
});
