var that;
var app = getApp();
var animation;
import { returnStr, setCache, getCache, _debounce, getRole } from '../../../utils/util'
Page({
  data: {
    param: {},//参数
    userInfo: {},
    userList: [],
    users: [],//沟通选择的人员
    textArea: '',//内容

    animationInfo: {},
    isShow: false,
    isShowText: false,
    has_finish: 0, //是否归档 0否 1是
    perfstepFlow: [], // 步骤
    smdsinsFlow: 0, // 当前绩效流程所在位置
    flowNow: {}, // 当前节点

    thecurrentFlow: '', // 当前节点
    ruleScore: 1, // 1-指标均要评分 2-评分总结
    mandatoryScore: false, // 指标说明是否必填

    weight: '',
    apList: [], // 执行计划数据
    planIndex: [], // 执行计划的下标，当点击表格查看时用到

    // 按钮显示隐藏
    targetConfirmed: false, // 目标确认
    gradeButShow: false, // 评分
    examineButShow: false, // 审批
    isAction: false, // 审批驳回
    resultButShow: false, // 结果值录入
    actionButShow: false, // 执行计划
    recordsManagement: false, // 管理记录
    feedbackBut: false, // 沟通反馈按钮

    transferBut: false, // 转交按钮
    careOfPeopleId: [], // 转交的 -- 转出ID
    selectZj: false,
    zjId: 0, // 转交用户ID

    revocationShow: false, //是否可以撤销
    revocationNodeId: 1, //撤销节点ID

    recordList: [], // 记录列表
    recordAllList: [], // 记录列表

    selectUser: false, // 沟通反馈@
    emtags: [], // 沟通反馈@选中人员

    selectpradio: '',
    selectpradio1: '',
    rejectList: [],
    rejectListIndex: -1,

    rejectList1: [],
    rejectList1Index: 0,
    rejectdlg: false, // 驳回选项弹窗
    rejectData: {}, // 驳回数据
    rejectProp: false, // 驳回--选人
    popupknowFrom: 0, // 0:沟通反馈，1：驳回，2审批，3目标确认，4.撤销
    gradeval: 0, // 评分总分
    graded: false, // 评分模块开关
    commFeedback: '', // 沟通弹窗反馈
    show_dept_selector: false, // 转交选人
    Information: {
      // 顶部员工信息
      name: '',
      deptList: []
    },

    // 执行中
    inExecution: [],
    scoreInfo: [], // 各个节点的人评的总分
    titList: [],
    bootBool: false, // 防止多次请求
    isCs: false, // 是否抄送人进入（抄送人能看到全部评分内容）
    com_height: '100%',

    isDisabled: false, //是否显示上下一条
    headuDown: [],
    pendingList: [],
    page: 1,
    isJz: true,
    activeName: '', //待办带进来的节点类型

    checked: false, //只看自己评分
    recordMemberIds: [],

    flexDialog: false,
    flexIndex: 0,

    // 评分确认列表
    pointList: [],
    pointData: {},
    isPoint: false,

    isShowPoint: true,
    publicity: 0,

    isShowText: false,
    logText: '执行计划',
    logList: [],
    apDetails: {},

    isShowCx: false,
    checked: false,//是否查看更多
    isSuperior: false,//判断当前登录者是否是该考核人的上级
    boxTop:0,
    ding_msg: false,//判断当前登录者是否是该考核人的上级
    recordIndex:5,
    recordStr:'全部记录',
  },
  onLoad(e) {
    that = this;
    // dd.alert({
    //   title: '亲',
    //   content: JSON.stringify(e),
    //   buttonText: '我知道了',
    //   success: () => {
    //   },
    // });
    dd.setNavigationBar({ title: e.tel });
    this.setData({
      param: e,
      userInfo: app.globalData.userData,
      userList: app.globalData.usersList
    });
    if (e.corpId) {
      that.setData({ corpId: e.corpId });
      app.globalData.corpId = e.corpId
    }
    if (this.data.param.paths && this.data.param.data) {
      let data = JSON.parse(this.data.param.data);
      data.employee_id_code = app.returnCode(data.employee_id)
      app.$post('api/per/package/msg/cc', data).then(res => {});
    }
  },
  onShow() {
    animation = dd.createAnimation({
      duration: 200,
      timeFunction: "linear",
    });
    if (app.globalData.userData) {
      that.employeeDet();
    } else {
      let corpId = that.data.corpId ? that.data.corpId : app.globalData.corpId
      app.login(corpId, function (is) {
        if (is) {
          that.setData({
            userInfo: app.globalData.userData,
          });
          that.getUserList(()=>{
            that.setData({
               userList: app.globalData.usersList
            });
            that.employeeDet();
          })
        } else {
          dd.reLaunch({
            url: '../../index/noJurisdiction/noJurisdiction'
          })
        }
      }, function () { })
    }
  },
  getUserList(fun=function(){}) {
    app.$get("api/per/user/employee_list", { page: 0, page_size: 0 }).then((res) => {
      let list = res.data.data.list
      let data = {}
      for (let i in list) {
        if (list[i].is_scope === 0||list[i].is_official ===0) {
					list[i].name = list[i].name + '(未启用)';
				}
        data[list[i].id] = list[i];
      }
      app.globalData.usersList = data;
      fun()
    })
  },
  showRecord(){
      if(this.data.recordIndex==5){
        this.setData({
            recordIndex:100000,
            recordStr:'收起',
        })
      }else{
        this.setData({
            recordIndex:5,
            recordStr:'全部记录',
        })
      }
  },
  onPageScroll(e) {
    if (e.scrollTop != 0) {
      this.setData({
        boxTop: e.scrollTop
      })
    }
  },
  onChangeC(e) {
    this.setData({
      checked: e.detail.value
    })
    this.isShowOneself();
  },
  onChangeC2(e) {
    this.setData({
      ding_msg: e.detail.value
    })
  },
  // 确认评分
  scorerveok(e) {
    let num = e.target.dataset.index
    let data = {
      id: this.data.employeeID, // 个人考核包ID
      is_submit: num, // 是否提交 0否（暂存） 1 是
      node_id: this.data.smdsinsFlow // 当前节点
    };
    let point_info = []; // 各项评分数据
    let sumData = {
      // 总分数据
      total_score: '',
      total_score_comment: ''
    };
    this.data.inExecution.forEach(item => {
      let resultInfo = {};
      if (this.data.ruleScore == 1 && !item.totalScore) {
        // 各项评分
        resultInfo = {
          // 评分信息--只评总分不需要
          score: item.resultval ? item.resultval : '', // 单项目结果值
          score_remark: item.remarks,
          dimension_key: item.dimension_key, // 维度索引
          index_key: item.index_key, // 指标索引
          index_id: item.id, // 指标ID
          name: item.name,
          // 用于计算分数
          d_weight: item.dimension_weight, // 维度权重
          weight: item.weight, // 指标权重
          type: item.type // 所属指标种类 1-量化指标 2-行为价值观指标 3-额外加分项 4-额外扣分项
        };
        point_info.push(resultInfo);
      } else {
        // 等于2：只评总分
        if (item.totalScore) {
          sumData = {
            total_score: item.resultval ? item.resultval : '',
            total_score_comment: item.remarks
          };
        }
      }
    });

    let isMust = true,isExplain = true; // isMust验证评分，isExplain验证说明
    if (num == 1) {
      // 提交验证必填
      if (this.data.ruleScore == 1) {
        // 各项评分
        point_info.forEach(item => {
          if (this.data.mandatoryScore) {
            // 评分说明必填
            if (!item.score_remark) {
              isExplain = false;
            }
          }
          if (!item.score) {
            isMust = false;
          }
        });
        if (!isMust) {
          app.globalData.showToast('请输入所有结果值');
          return false;
        }
        if (!isExplain) {
          app.globalData.showToast('请输入所有评分说明');
          return false;
        }
      } else {
        // 总分
        if (!sumData.total_score) {
          app.globalData.showToast('请输入评分总分');
          return false;
        }
        if (this.data.mandatoryScore) {
          if (!sumData.total_score_comment) {
            app.globalData.showToast('请输入总分说明');
            return false;
          }
        }
      }
    }
    if (this.data.ruleScore == 1) {
      data.total_score = this.fomatFloat(this.totalPointsCount(point_info), 2); // 计算的个人评出的总分（保留小数后两位）
    } else {
      data.total_score = this.fomatFloat(sumData.total_score, 2); // 计算的个人评出的总分（保留小数后两位）
      data.total_score_comment = sumData.total_score_comment;
    }
    data.point_info = JSON.stringify(point_info); // 评分信息 --  填所有评分时必须的字段（传入某指标的分数、说明、维度索引、制表索引、指标ID）
    if (this.data.bootBool) {
      return;
    }
    let pointList = JSON.parse(JSON.stringify(point_info));
    pointList.push({
      name: '总分',
      score: data.total_score,
      score_remark: data.total_score_comment
    });
    this.setData({
      pointList: pointList,
      pointData: data
    })
    if (this.data.ruleScore == 1&&num==1) {
      //只评总分不需要弹窗
      this.setData({
        isPoint: true,
      })
    } else {
      this.score();
    }
  },
  fomatFloat(src, pos) {
    return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
  },
  // 计算总分
  totalPointsCount(data) {
    let ct = this.data.empDetList.calc_type; // 1-加和计算 2-加权计算
    let cd = this.data.empDetList.calc_dimension; // 是否维度权重参与计算 1-是 0-否
    let num = 0;
    data.forEach(item => {
      if (item.score) {
        if (item.type == 3) {
          // 3-额外加分项
          num += Number(item.score);
        } else if (item.type == 4) {
          // 4-额外扣分项    不计算
          num -= Number(item.score);
        } else {
          if (ct == 1 && cd == 0) {
            // 加和
            num += Number(item.score);
          } else if (ct == 1 && cd == 1) {
            // 加和--维度权重参与计算
            num += Number(item.score) * Number(item.d_weight / 100);
          } else if (ct == 2 && cd == 0) {
            // 加权
            num += Number(item.score) * Number(item.weight / 100);
          } else if (ct == 2 && cd == 1) {
            // 加权--维度权重参与计算
            num += Number(item.score) * Number(item.d_weight / 100) * Number(item.weight / 100);
          }
        }
      }
    });
    return num;
  },
  // 评分-文本框失去焦点时触发
  watresultval(e) {
    let item = e.target.dataset.item
    let val = item.resultval;
    let totalScore = item.totalScore ? item.totalScore : false;
    if (totalScore) {
      this.setData({
        gradeval: this.fomatFloat(val, 2)
      })
    } else {
      let tPoints = [];
      this.data.inExecution.forEach(item => {
        if (item.resultval) {
          tPoints.push({
            score: item.resultval, // 分值
            d_weight: item.dimension_weight, // 维度权重
            weight: item.weight, // 指标权重
            type: item.type // 所属指标种类 1-量化指标 2-行为价值观指标 3-额外加分项 4-额外扣分项
          });
        }
      });
      this.setData({
        gradeval: this.fomatFloat(this.totalPointsCount(tPoints), 2)
      })
    }
    this.setData({
      isShowPoint: true
    })
  },
  // e当前行 ,item用于判断当前输入是否超过评分上限  
  sgradeInp(e) {
    let item = e.target.dataset.item;
    let index = e.target.dataset.index;
    // item.resultval = item.resultval.match(/\d+(\.\d{0,2})?/) ? item.resultval.match(/\d+(\.\d{0,2})?/)[0] : '';
    this.setData({
      [`inExecution[${index}].resultval`]: e.detail.value
    })
    if (item) {
      if (item.type == 3 || item.type == 4) {
        if (item.point_limit) {
          if (this.data.inExecution[index].resultval > Number(item.point_limit)) {
            app.globalData.showToast('评分超过上限');
            this.setData({
              [`inExecution[${index}].resultval`]: ''
            })
            return false;
          }
        }
      }
    }
  },
  bindText: _debounce(function (e) {
    let index = e.target.dataset.index;
    this.setData({
      [`inExecution[${index}].remarks`]: e.detail.value
    })
  }),
  score() {
    app.$post('api/per/package/submit_score', this.data.pointData).then(res => {
      app.globalData.showToast('提交成功');
      this.setData({
        bootBool: false,
        isPoint: false,
        graded: false,
      })
      this.employeeDet();
    });
  },
  // 显示评分
  gradeClick() {
    that.setData({
      graded: true
    });
    let dnsion = [];
    this.data.inExecution.forEach(item => {
      if (item.employee_id == this.data.userInfo.id && item.flowId == this.data.smdsinsFlow) {
        dnsion.push(item);
      }
    });
    let totalScore = {
      theDimension: '总分',
      wdLeg: 0,
      totalScore: true
    };
    this.data.perfstepFlow.forEach(item => {
      if (item.code == 'score_supervisor' && item.status == 1) {
        this.setData({
          ruleScore: item.rule == 2 ? 2 : 1, // 1-指标均要评分 2-评分总结
          thecurrentFlow: 'score_supervisor'
        });
        totalScore.codeId = item.id;
      } else if (item.code == 'special_scorer' && item.status == 1) {
        this.setData({
          ruleScore: 1, // 1-指标均要评分 2-评分总结
        });
      }
      if ((item.code == 'score_supervisor' && item.status == 1) || (item.code == 'special_scorer' && item.status == 1)) {
        // 上级评分，特定评分     评分人必填项
        item.action.forEach(arr => {
          this.setData({
            mandatoryScore: arr == 'comment', // 指标说明是否必填
          });
        });
      }
    });
    // 总分
    this.data.scoreInfo.forEach(item => {
      item.employees.forEach(arr => {
        if (arr.employee_id == this.data.userInfo.id) {
          this.setData({
            gradeval: arr.point ? arr.point : 0,
          });
          if (item.id == totalScore.codeId && this.data.ruleScore == 2) {
            totalScore.resultval = arr.point;
            totalScore.remarks = arr.comment ? arr.comment : '';
          }
        }
      });
    });
    let dimenList = [];
    let users = []; // 当前节点的自己的信息
    this.data.perfstepFlow.forEach(item => {
      // 根据流程当前节点，找节点的人员中的登陆者
      if (item.status == 1) {
        item.target.some(arr => {
          if (arr.employee_id == this.data.userInfo.id) {
            arr.flowStatusId = item.id; // 当前节点的ID
            users = arr;
            return true;
          }
        });
      }
    });
    users.list.forEach(att => {
      // 获取当前节点审批人员中的登陆者
      dnsion.forEach(add => {
        if (att.index_id == add.id && att.dimension_key == add.planIndex[0] && att.index_key == add.planIndex[1]) {
          add.dimension_key = att.dimension_key; // 维度索引
          add.index_key = att.index_key; // 指标索引
          add.score_infos.forEach(user => {
            // 显示的文案，找到当前登录人
            if (user.id == users.flowStatusId) {
              if (user.employee_id == this.data.userInfo.id) {
                this.setData({
                  [`scoreTab.title`]: user.title,
                  [`scoreTab.explain`]: user.title.split('：')[0] + '说明',
                })
              }
            }
          });
          dimenList.push(add);
        }
      });
    });
    this.data.scoreInfo.forEach(item => {
      item.employees.forEach(arr => {
        if (arr.employee_id == this.data.userInfo.id) {
          this.setData({
            gradeval: arr.point ? arr.point : 0
          })
          if (item.id == totalScore.codeId && this.data.ruleScore == 2) {
            totalScore.resultval = arr.point;
            totalScore.remarks = arr.comment ? arr.comment : '';
          }
        }
      });
    });
    this.data.perfstepFlow.forEach(item => {
      if (item.code == 'score_supervisor' && item.status == 1 && this.data.ruleScore == 2) {
        dimenList.push(totalScore);
      }
    });
    this.setData({
      inExecution: dimenList
    })
  },
  // 评分取消
  scorerveno() {
    this.setData({
      graded: false,
      skeletonLoad: false,
    })
    this.employeeDet();
  },
  confirmBh() {
    if (!this.data.textArea) {
      app.globalData.showToast('请输入沟通内容');
      return false;
    }
    let target_id = this.data.users.map(item => {
      return item.id;
    });
    app.$post('api/per/package/negotiation', {
      id: this.data.employeeID,
      content: this.data.textArea,
      target_id: JSON.stringify(target_id),
	    ding_msg:this.data.ding_msg? 1:0
    }).then(res => {
      app.globalData.showToast('已沟通');
      this.employeeDet();
      this.showGt();
      this.setData({
        content:'',
        ding_msg:false
      })
    });
  },
  // 沟通@人员
  onSelectUser(item) {
    that.setData({
      users: item
    });
  },
  //转交
  openSelectUser(e) {
    if (this.data.careOfPeopleId.length == 1) {
      this.openSelect(e)
    } else {
      let items = this.data.careOfPeopleId.map(item => {
        return item.employee_name
      })
      dd.showActionSheet({
        title: '请选择被转交人员',
        items: items,
        cancelButtonText: '取消',
        success: (res) => {
          if (res.index !== -1) {
            this.setData({
              zjId: this.data.careOfPeopleId[res.index].employee_id, //被转出人ID
            })
            this.openSelect(e)
          }
        },
      });
    }
  },
  //选择
  openSelect(e) {
    let index = e.target.dataset.index
    animation.translateY(0).step();
    that.setData({
      // users:[],
      // textArea:'',
      isShowstaff: index,
      animationInfo: animation.export(),
      popupCx: 'container__mask',
    });
  },
  //转交人员
  confirm(data) {
    that.setData({
      employeeObj: data
    });
    let item = data[0];
    dd.confirm({
      title: '温馨提示',
      content: '确认转交:' + item.name + '?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          let employeeId = this.data.careOfPeopleId.length == 1 ? this.data.careOfPeopleId[0].employee_id : this.data.zjId;
          let data = {
            id: this.data.employeeID, // 个人考核记录ID
            node_id: this.data.flowNow.id, // 节点ID
            to_employee_id_code: item.code, // 接收用户ID
            from_employee_id_code: app.returnCode(employeeId) // 转出用户ID
          };
          app.$post('api/per/package/transfer', data).then(res => {
            if (res.data.code == 1) {
              app.globalData.showToast('转交成功');
              this.employeeDet();
              this.closeWindows();
            }
          });
        }
      },
    });

  },
  showGt() {
    that.setData({
      users: [],
      isShowGt: !this.data.isShowGt
    });
  },
  showCx() {
    that.setData({
      isShowCx: true
    });
  },
  //关闭规则
  onClose() {
    animation.translateY(1200).step();
    that.setData({
      animationInfo: animation.export(),
      isShowstaff: false,
      popupCx: '',
    });
    setTimeout(() => {
      dd.pageScrollTo({
        scrollTop: that.data.boxTop
      })
    }, 100)
  },
  showImg(e) {
    let item = e.target.dataset.item
    app.$get('api/drive/grant', { file_id: item.fileId }).then(res => {
      dd.previewFileInDingTalk({
        corpId: app.globalData.corpId,
        spaceId: item.spaceId,
        fileId: item.fileId,
        fileName: item.fileName,
        fileSize: item.fileSize,
        fileType: item.fileType,
      })
    })
  },
  openVas(e) {
    let index = e.target.dataset.index
    let item = e.target.dataset.item
    if(index=="2"){
      item.mamage_record.forEach(item=>{
        item.userName=app.globalData.usersList[item.employee_id].name
      })
    }
    this.setData({
      logText: index == '1' ? '执行计划' : '管理记录',
      logList: index == '1' ? item.schedule : item.mamage_record,
      apDetails: item,
      isShowText: true,
    });
  },
  rotateAndScale() {
    this.setData({
      isShow: !this.data.isShow
    });
  },
  //关闭所有弹窗
  closeWindows() {
    this.setData({
      // 目标确认
      rejectdlg: false,
      commFeedback: '',
      // 转交
      employeeObj: [],
      users: [],
      textArea: '',

      isShowGt: false,
      isPoint: false,
      isShowText: false,
      isShow: false,
      isShowCx: false,
    })
  },
  // 录入结果值
  enteringResult() {
    dd.navigateTo({
      url: `../resultValueEntry/resultValueEntry?id=${this.data.employeeID}&packageName=${this.data.param.tel}`
    })
  },
  agree0Prop(e) {
    let num = e.target.dataset.num
    let data = {
      id: this.data.employeeID, // 个人考核包ID
      agree: num, // 同意1    驳回0
      c_node_id: this.data.flowNow.id // 当前节点ID
    };
    if (num == 0) {
      if (!this.data.commFeedback) {
        app.globalData.showToast('请输入驳回内容');
        return false;
      }
      if (!this.data.rejectData.node_id) {
        app.globalData.showToast('请选择驳回节点!');
        return false;
      }
      if (!this.data.rejectData.employee_id) {
        app.globalData.showToast('至少选择一名重置人员!');
        return false;
      }
      data.employee_id_code = app.returnCode(this.data.rejectData.employee_id);
      data.node_id = this.data.rejectData.node_id;
    }
    if (this.data.commFeedback) {
      data.comment = this.data.commFeedback; // 审核意见
    }
    // console.log(data);
    // return false
    app.$post('api/per/package/review', data).then(res => {
      app.globalData.showToast('提交成功');
      this.employeeDet();
      this.closeWindows();
    });
  },
  isShowOneself() {
    let inExecution = this.data.inExecution
    inExecution.forEach((e, index) => {
      e.scoreList.forEach(item => {
        if (!this.data.checked) {
          if (item.employee_id == this.data.userInfo.id) {
            item.isShow = true;
          } else {
            item.isShow = false;
          }
        } else {
          item.isShow = true;
        }
      })
    })
    this.setData({
      inExecution: inExecution
    })
  },
  // 驳回选择节点
  clickreject(e) {
    this.setData({
      rejectListIndex: e.detail.value,
      rejectList1: [],
      rejectData: {},
    })
    let item = this.data.rejectList[this.data.rejectListIndex]
    let rejectList1 = [];
    if (item.staff.length > 1) {
      rejectList1.push({ employee_id: 0, employee_name: '选择人员' });
      item.staff.forEach(item => {
        if (item.status == 2) {
          rejectList1.push(item);
        }
      });
      this.setData({
        rejectProp: true,
        rejectList1: rejectList1,
      })
    } else {
      this.setData({
        rejectProp: false,
        [`rejectData.employee_id`]: [item.staff[0].employee_id],
      })
    }
    this.setData({
      [`rejectData.node_id`]: item.id,
    })
  },
  //驳回选择人员
  clickreject1(e) {
    this.setData({
      rejectList1Index: e.detail.value,
    })
    let item = this.data.rejectList1[this.data.rejectList1Index]
    if (item.employee_id == 0) {
      let arr = [];
      this.data.rejectList1.forEach(aoo => {
        if (aoo.employee_id && aoo.employee_id != 0) {
          arr.push(aoo.employee_id);
        }
      });
      this.setData({
        [`rejectData.employee_id`]: arr,
      })
    } else {
      this.setData({
        [`rejectData.employee_id`]: [item.employee_id],
      })
    }
  },
  bindFeedback: function (e) {
    this.setData({
      commFeedback: e.detail.value,
    });
  },
  bindTextAreaBlur: function (e) {
    this.setData({
      textArea: e.detail.value,
    });
  },
  employeeDet() {
    let params = {};
    if (this.data.param.id) {
      params.id = this.data.param.id;
    } else if (this.data.param.assId && this.data.param.staffId) {
      params.package_id = this.data.param.assId;
      params.employee_id_code = app.returnCode(this.data.param.staffId);
    }
    this.skeletonLoad = true;
    app.$get('api/per/package/employee/info', params).then(res => {
      if (res.data.code == 1) {
        let data = res.data.data;
        if (this.data.pendingList.length > 0) { //上下考核人
          this.setUpD();
        }
        data.flow.map(item => {
          if (item.target && item.target.length > 0) {
            item.target.map(item2 => {
              item2.employee_name =app.globalData.usersList[item2.employee_id].name;
            });
          }
        });
        this.setData({
          has_finish: data.has_finish,
          recordMemberIds: data.record_member_ids || [],
          empDetList: data,
          employeeID: data.id, // 考核记录id
          Information: app.globalData.usersList[data.relevance_employee.id], // 考核人员信息

          [`Information.deptList`]: data.relevance_employee.dept_list, // 部门
          perfstepFlow: data.flow, // 流程
          apList: JSON.stringify(data.dimension),
          scoreInfo: data.score_info, // 各个节点的人评的总分
          feedbackBut: data.config.assessment.feedback == '1', // 沟通反馈是否启用
          resultButShow: false, // 录入结果值
          gradeButShow: false, // 评分按钮
          examineButShow: false, // 审批按钮
          transferBut: false, // 转交按钮
          targetConfirmed: false, // 目标确认
          publicity: data.publicity,
          actionButShow: false, // 执行计划按钮
          recordsManagement: false, // 管理记录按钮
          revocationShow: false,
          smdsinsFlow: 0,
          flexIndex: 0,
        })
        this.buttonIf2(); //判断管理记录/执行计划按钮是否显示

        let executor = {}; // 与当前登录账号相同的执行人
        let review = {}; // 与当前登录账号相同的审批人
        data.flow.forEach((item, index) => {
          if (item.code == 'execution') {
            // 查找 已开始或已结束的执行节点中有无当前账号
            if (item.status != 0) {
              item.target.forEach(tar => {
                if (tar.employee_id == this.data.userInfo.id) {
                  executor = tar; // 存入与当前登录账号相同的执行人
                  executor.newCode = 'employee'; // 保存执行人节点code
                }
              });
            }
          }
          if (item.code == 'review') {
            // 查找 已开始或已结束的审批节点中有无当前账号
            if (item.status != 0) {
              item.target.forEach(tar => {
                if (tar.employee_id == this.data.userInfo.id) {
                  review = tar; // 存入与当前登录账号相同的审批人
                  review.newCode = 'reviewer'; // 保存审批人节点code
                }
              });
            }
          }
          this.buttonIf(item);
          if (item.status == 1) {
            if (item.code != 'cc') {
              this.isRevocation(item, data.flow[index - 1]);
            }
            data.flow.push({ id: data.flow.length + 1, remark: '结束', status: 0, target: [] });
            this.setData({
              flowNow: item,
              smdsinsFlow: item.id,
              flexIndex: index + 1,
            })
          }
        });
        if (this.data.flexIndex == 0) {
          data.flow.push({ id: data.flow.length + 1, remark: '结束', status: 2, target: [] });
          this.setData({
            flexIndex: data.flow.length,
            perfstepFlow: data.flow, // 流程
          })
        }

        if (this.data.smdsinsFlow == 0) {
          // 如果当前节点id为0，代表此考核详情已完毕，把最后一个节点作为当前节点
          this.setData({
            smdsinsFlow: data.flow[data.flow.length - 1].id
          })
          let cs
          data.flow.forEach(item=>{
            if(item.code=='cc'){
                cs = item;
            }
          })
          if(cs){
          cs.target.some(item => {
            if (item.employee_id == this.data.userInfo.id) {
              this.setData({
                isCs: true
              })
              return true;
            }
          });
          }
        }
        // 整合表格格式
        let dimension = data.dimension;
        let dimeTab = [];
        let weight = 0; // 权重统计
        // poiSco    评分权限
        // poicom    说明权限
        let poiSco = data.config.assessment.point_scope; // 评分可见权限
        let poicom = data.config.assessment.point_comment; // 说明可见权限
        dimension.forEach((item, keys) => {
          item.index.forEach((arr, index) => {
            weight += Number(arr.weight);
            arr.theDimension = item.name + '(' + Number(index + 1) + ')';
            arr.dimension_weight = item.dimension_weight; // 维度权重
            arr.score_infos = [];
            arr.planIndex = [keys, index]; // 当打开执行计划时的下标
            let tar = null;
            if (this.initData(arr.result)) {
              tar = this.initData(arr.result) + arr.unit;
            }
            arr.tabList = [
              {
                lab: '指标类型',
                prop: this.indexType(this.initData(arr.type))
              },
              {
                lab: '指标权重（%）',
                prop: this.initData(arr.weight) ? '指标权重：' + this.initData(arr.weight) + '%' : null
              }
            ];
            arr.details = [
              // {
              //   lab: '指标类型',
              //   prop: this.indexType(this.initData(arr.type))
              // },
              { lab: '目标值', prop: this.initData(arr.target) ? + this.initData(arr.target) + arr.unit : '' },
              { lab: '结果值', prop: tar },
              { lab: '加扣分上限', prop: this.initData(arr.point_limit) },
              // { lab: '考核标准', prop: this.initData(arr.per_remark) },
              // {
              //   lab: '指标权重（%）',
              //   prop: this.initData(arr.weight) ? this.initData(arr.weight) + '%' : null
              // },
              { lab: '备注', prop: this.initData(arr.remark) }
            ];
            // 权限区分
            arr.scoreList = [];
            arr.score_info.forEach((list, auto) => {
              if (list.id <= this.data.smdsinsFlow) {
                // smdsinsFlow为当前节点id。。数据-id <= 当前节点id .   :筛选出当前节点及之前的评分节点的数据
                list.employees.forEach(emplo => {
                  if (emplo.employee_id == this.data.userInfo.id && list.id == this.data.smdsinsFlow) {
                    arr.resultval = emplo.point;
                    arr.remarks = emplo.remark;
                    arr.employee_id = emplo.employee_id;
                    arr.flowId = list.id;
                  }
                  // 获取code
                  data.flow.forEach(codes => {
                    if (codes.id == list.id) {
                      if (codes.code == 'review') {
                        // 审批
                        emplo.newCode = 'reviewer';
                      } else if (codes.code == 'execution') {
                        // 执行中
                        emplo.newCode = 'employee';
                      } else if (codes.code == 'score_supervisor') {
                        // 指定上级
                        emplo.newCode = 'manager';
                      } else if (codes.code == 'special_scorer') {
                        // 特定上级
                        emplo.newCode = 'special';
                      }
                      codes.target.some(tar => {
                        //找到每个评分人获取评分状态
                        if (tar.employee_id == emplo.employee_id) {
                          emplo.status = tar.status;
                          return true;
                        }
                      });
                    }
                  });
                  // item为评分数据，数据内只有两个节点：指定（score_supervisor，权限名：manager）  特定上级（special_scorer，权限名：special）
                  // executor  执行人中的当前登陆账号
                  // review    审批人中的当前登陆账号
                  if (executor.employee_id) {
                    // 若有数据，那么当前登录账号必定在执行人中并且执行节点正在执行或已结束（哪怕正在执行也无所谓，前方已经过滤评分数据，会得到[]）
                    if (poiSco[executor.newCode] == '2') {
                      // 已有数据并且为2 ‘查看所有的’ ，那就可以将所有的评分权限都改为 ‘2’
                      for (let i in poiSco) {
                        poiSco[i] = '2';
                      }
                    }
                    if (poicom[executor.newCode] == '2') {
                      // 说明同上
                      for (let i in poicom) {
                        poicom[i] = '2';
                      }
                    }
                  }
                  if (review.employee_id) {
                    // 审批节点--同上  （审批节点默认为2，可以直接全部变成2）
                    if (poiSco[review.newCode] == '2') {
                      for (let i in poiSco) {
                        poiSco[i] = '2';
                      }
                    }
                    if (poicom[review.newCode] == '2') {
                      // 说明同上
                      for (let i in poicom) {
                        poicom[i] = '2';
                      }
                    }
                  }
                  if (item.employee_id == executor.employee_id) {
                    // 判断当前评分数据是否 与 执行节点的当前帐号一致
                    if (poiSco[executor.newCode] == '2') {
                      // 如果一致并且执行节点为‘2’即查看所有，那么就修改当前 评分数据 的权限也为‘2’
                      poiSco[item.newCode] = '2';
                    }
                    if (poicom[executor.newCode] == '2') {
                      // 执行中的 -- 说明权限-同上
                      poicom[item.newCode] = '2';
                    }
                  }
                  if (item.employee_id == review.employee_id) {
                    // 判断当前评分数据是否 与 审批节点的当前帐号一致
                    if (poiSco[review.newCode] == '2') {
                      poiSco[item.newCode] = '2';
                    }
                    if (poicom[review.newCode] == '2') {
                      // 审批的 -- 说明权限-同上
                      poicom[item.newCode] = '2';
                    }
                  }
                  let scoredata = {
                    // 评分&&说明
                    lab: emplo.title,
                    prop: emplo.point,
                    newCode: emplo.newCode,
                    employee_id: emplo.employee_id,
                    level: emplo.level,
                    remark: emplo.remark,
                    knowFrom: 0,
                    status: emplo.status
                  };
                  arr.scoreList.push(scoredata);
                  // 单项总分显示
                  if (this.retrunFs(list.id, emplo).length > 0 && !emplo.point) {  //单项指标评分不显示总分，只评总分显示，要去掉，请把!emplo.point判断去掉
                    arr.scoreList.push(...this.retrunFs(list.id, emplo));
                  }
                });
              }
            });
            dimeTab.push(arr);
          });
        });
        this.setData({
          weight: weight + '%',
        })
        let poiSOk = false; // 评分--为true时所有评分可看
        let poiCOk = false; // 说明--为true时所有说明可看
        dimeTab.forEach(arr => {
          arr.scoreList.forEach(item => {
            // 判断评分
            if (poiSco[item.newCode] == '1' && item.employee_id == this.data.userInfo.id) {
              item.pointShow = true; //是否显示评分
            } else if (poiSco[item.newCode] == '2') {
              // 当前 评分 数据权限等于2时并且（当前数据id为登陆账号  或  执行中权限等于2（代表当前登陆账号为执行中的一员） 或  审批权限等于2（代表当前登陆账号为审批中的一员）） 时，所有评分都可见
              if (item.employee_id == this.data.userInfo.id || poiSco[executor.newCode] == '2' || poiSco[review.newCode] == '2') {
                poiSOk = true;
              }
            }
            // 判断说明
            if (poicom[item.newCode] == '1' && item.employee_id == this.data.userInfo.id) {
              item.textShow = true; //是否显示说明
            } else if (poicom[item.newCode] == '2') {
              if (item.employee_id == this.data.userInfo.id || poicom[executor.newCode] == '2' || poicom[review.newCode] == '2') {
                poiCOk = true;
              }
            }
          });
        });
        dimeTab.forEach(arr => {
          arr.returnStr = returnStr(arr.update_time)
          let points = []; //最终显示评分
          arr.scoreList.forEach(item => {
            item.isShow = false;//控制是否显示更多
            if(item.employee_id==this.data.userInfo.id){
              item.isShow = true;//控制是否显示更多
            }
            if (poiSOk || getRole(1) || this.data.isCs) {
              item.pointShow = true;
            }
            if (poiCOk || getRole(1) || this.data.isCs) {
              item.textShow = true;
            }

            if (item.status != 2 && item.id != this.data.smdsinsFlow) {
              // delete duplicat[index]
            } else {
              points.push(item);
            }
          });
          arr.scoreList = points;
        });
        this.setData({
          inExecution: dimeTab,
        })

        this.pdLc(); //流程结束后的判断
        let titDatas = [];
        if (data.publicity == 1 && (!this.data.flowNow.code || this.data.flowNow.code == 'review')) {
          // 判断是否公开，并且是审批节点或者流程结束，（流程结束flowNow为空）
          if (this.initData(data.final_point)) {
            titDatas.push({ lab: '考核结果', prop: data.final_point });
          }
          if (this.initData(data.final_level)) {
            titDatas.push({ lab: '绩效等级', prop: data.final_level });
          }
        }
        this.setData({
          titList: titDatas,// 顶部数据
          recordList: []
        })
        let recordList = [];
        // 记录

        let record = res.data.data.record;
        record.forEach((item, index) => {
          if (this.data.userList[item.employee_id]) {
            item.name = this.data.userList[item.employee_id].name;
          }
          // if (index < 3) {
          recordList.push(item);
          // }
        });
        this.setData({
          recordAllList: record,// 顶部数据
          recordList: recordList
        })
        this.skeletonLoad = false;
      } else if (res.data.code == 0) {
        dd.reLaunch({
          url: '../../index/noPage/noPage'
        })
      }
    }).catch((err) => {
      console.log(err)
      if (err.data.code == 0) {
        dd.reLaunch({
          url: '../../index/noPage/noPage'
        })
      }
    })
  },
  pdLc() {
    let flow = JSON.parse(JSON.stringify(this.data.perfstepFlow)).reverse(); //反转流程，找第一个评分节点
    //流程结束，但是最后一个“评分”节点里有自己显示撤销
    if (this.data.publicity == 1) {
      flow.some(item => {
        if (item.code == 'review' || item.code == 'cc') {
          return true;
        }
        if (item.code == 'score_supervisor' || item.code == 'special_scorer') {
          item.target.some(e => {
            if (e.employee_id == this.data.userInfo.id && e.status == 2) {
              this.setData({
                revocationNodeId: item.id,
                revocationShow: true
              })
              return true;
            }
          });
          return true;
        }
      });
    }
  },
  buttonIf2() {
    if (this.data.Information.id == this.data.userInfo.id) {
      this.setData({
        actionButShow: true
      })
    }
    // 指定管理记录人是否包含自己
    this.data.recordMemberIds.some(item => {
      if (item == this.data.userInfo.id) {
        this.setData({
          recordsManagement: true
        })
        return true;
      }
    });
    this.getSuperior(this.data.Information.id)//判断是否当前被考核人的上级
    if (this.data.userInfo.is_creator == 1) {
      // 如果是创始人也可以操作
      this.setData({
        recordsManagement: true
      })
    }
    if (app.getPermis(3)) {
      // 如果是子管理员并且管理范围权限为“全公司”
      this.setData({
        recordsManagement: true
      })
    }
  },
  buttonIf(item) {
    // 按钮控制
    if (item.status == 1) {
      // 目标确认
      if (item.code == 'confirm') {
        item.target.forEach(tar => {
          if (tar.employee_id == this.data.userInfo.id && tar.status == 1) {
            this.setData({
              targetConfirmed: true
            })
          }
        });
      }
      // 评分按钮
      if (item.code == 'score_self' || item.code == 'score_mutual' || item.code == 'score_supervisor' || item.code == 'special_scorer') {
        item.target.forEach(tar => {
          if (tar.employee_id == this.data.userInfo.id && tar.status == 1) {
            this.setData({
              gradeButShow: true
            })
          }
        });
      }
      // 结果值录入按钮
      if (item.code == 'result_value') {
        item.target.forEach(tar => {
          if (tar.employee_id == this.data.userInfo.id) {
            this.setData({
              resultButShow: true
            })
          }
        });
      }
      // 审批按钮
      if (item.code == 'review') {
        let reviewif = false;
        item.target.forEach(tar => {
          if (tar.employee_id == this.data.userInfo.id && tar.status == 1) {
            reviewif = true;
          }
        });
        this.setData({
          examineButShow: !!reviewif,
          isAction: item.action.indexOf('refuse') >= 0
        })
      }
      this.setData({
        careOfPeopleId: [],
      })
      let careOfPeopleId = [], transferBut = false;
      // 当是结果值录入，上级评分，指定人评分，审批时显示转交按钮
      if (
        item.code == 'target' ||
        item.code == 'score_supervisor' ||
        item.code == 'special_scorer' ||
        item.code == 'result_value' ||
        item.code == 'review' ||
        item.code == 'confirm'
      ) {
        item.target.forEach(add => {
          if ((add.employee_id == this.data.userInfo.id || getRole(1)) && add.status == 1) {
            if (item.code == 'review' || item.code == 'confirm') {
              if (item.action.indexOf('transfer') >= 0 || getRole(1)) {

                careOfPeopleId.push(add);
                transferBut = true
              }
            } else if (item.code == 'score_supervisor') {
              if (item.transfer || getRole(1)) {
                careOfPeopleId.push(add);
                transferBut = true
              }
            } else {
              careOfPeopleId.push(add);
              transferBut = true
            }
            this.setData({
              careOfPeopleId: careOfPeopleId,
              transferBut: transferBut
            })
          }
        });
      }
    }
  },
  // 管理记录||执行计划
  openTrackPath(e) {
    let add = e.target.dataset.str
    let data = {
      know: add,
      apList: this.data.apList,
      packId: this.data.employeeID,
      assessID: this.data.Information.id,
      planIndex: this.data.planIndex,
      recordMemberIds: this.data.recordMemberIds
    };
    setCache('actionplanList', data);
    dd.navigateTo({
      url: `../actionplanList/actionplanList`
    })
  },
  // 判断是否当前被考核人的上级
  getSuperior(id) {
    app.$get('api/per/user/manager_list', { id_code: app.returnCode(id) }).then(res => {
      let superiorList = res.data.data; //被考核人上级
      superiorList.some(item => {
        if (item.id == this.data.userInfo.id) {
          this.setData({
            recordsManagement: true
          })
          return true
        }
      })
    });
  },
  // 撤销
  revocation() {
    let params = {
      id: this.data.employeeID,
      node_id: this.data.revocationNodeId,
      comment: this.data.textArea
    };
    app.$post('api/per/package/revoke', params)
      .then(res => {
        if (res.data.code == 1) {
          app.globalData.showToast('撤销成功');
          this.employeeDet();
        }
		    this.closeWindows();
      })
  },
  // 判断是否显示撤销按钮
  isRevocation(dqItem, upItem) {
    // 当前只需要评分节点需要撤回
    //当前节点包含自己并且其他任意一人未完成的显示按钮
    if (dqItem.code == 'score_supervisor' || dqItem.code == 'special_scorer') {
      dqItem.target.some((item, index) => {
        if (item.employee_id == this.data.userInfo.id && item.status == 2) {
          dqItem.target.some((item2, index2) => {
            if (item2.status == 1) {
              this.setData({
                revocationNodeId: dqItem.id,
                revocationShow: true
              })
              return true;
            }
          });
        }
      });
    }
    let is = true; //判断当前节点人员是否有完成的
    //上一节点中包含登录者并且是完成的状态显示按钮
    if (upItem) {
      dqItem.target.some((item, index) => {
        if (item.status == 2) {
          is = false;
        }
      });
      if (upItem.code == 'score_supervisor' || upItem.code == 'special_scorer') {
        upItem.target.some((item, index) => {
          if (item.employee_id == this.data.userInfo.id && item.status == 2 && is) {
            this.setData({
              revocationNodeId: upItem.id,
              revocationShow: true
            })
            return true;
          }
        });
      }
    }
  },
  // 数据初始化，没有值或者空数组的显示-
  initData(str) {
    if (str == null) {
      return str || null;
    }
    if (typeof str === 'object') {
      return str.length > 0 ? str : null;
    } else {
      return str || null;
    }
  },
  indexType(item) {
    return item == 1 ? '量化指标' : item == 2 ? '非量化指标' : item == 3 ? '额外加分项' : item == 4 ? '额外扣分项' : '';
  },
  // 返回节点评分是只评总分的
  retrunFs(eid, e) {
    let arr = [];
    this.data.scoreInfo.forEach(item => {
      if (item.id == eid) {
        item.employees.forEach(u => {
          if (u.point && u.employee_id == e.employee_id) {
            let scoredata = {
              // 评分
              lab: e.title,
              prop: u.point + '(总分)',
              newCode: e.newCode,
              knowFrom: 0,
              employee_id: e.employee_id,
              level: '',
              remark: u.comment,
              status: 2
            };
            arr.push(scoredata);
          }
        });
      }
    });
    return arr;
  },
  gradeTurn() {
    this.setData({
      selectpradio: '',
      selectpradio1: '',
      rejectProp: false,
      rejectData: {},
    })
    let list = [];
    this.data.perfstepFlow.forEach((item, index) => {
      if (item.status == 2 && item.code != 'execution' && item.code != 'cc' && item.target.length != 0) {
        let arr = {};
        arr.id = item.id;
        arr.name = item.remark;
        item.target.forEach((att, aoo) => {
          arr.name += att.employee_name;
          arr.name += item.target.length - aoo > 1 ? ',' : '';
        });
        arr.staff = item.target;
        list.push(arr);
      }
    });
    this.setData({
      rejectList: list,
      popupknowFrom: 1,
      rejectdlg: true,
    })
  },
  // 审批同意
  gradeOk() {
    if (this.data.flowNow.code == 'confirm') {
      // 驳回
      this.setData({
        popupknowFrom: 3
      })
      this.popupknowFrom = 3;
    } else if (this.data.flowNow.code == 'review') {
      // 审批
      this.setData({
        popupknowFrom: 2
      })
    }
    this.setData({
      rejectdlg: true,
    })
  },
});
