package com.sys.bus.jx.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.sys.bus.hr.model.Person;
import com.sys.bus.hr.service.HrService;
import com.sys.bus.model.*;
import com.sys.bus.sys.model.DtBean;
import com.sys.bus.sys.wx.WxMsgType;
import com.sys.bus.syscode.service.SysCodeService;
import com.sys.core.model.PageBean;
import com.sys.core.utils.Conditions;
import com.sys.core.utils.SessionUtil;
import com.sys.core.utils.Tool;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

public class PerformanceService {
    static JxCommonService jxCommonService = Enhancer.enhance(JxCommonService.class);
    static KpilibService kpilibService = new KpilibService();
    static WflogService wflogService =  Enhancer.enhance(WflogService.class);
    static HrService hrService = Enhancer.enhance(HrService.class);
    //static RatingService ratingService = Enhancer.enhance(RatingService.class);
    static MailService mailService = new MailService();
    static SysCodeService codeService = Enhancer.enhance(SysCodeService.class);
    static WxMsgService wxMsgService = new WxMsgService();
    static PersonManagerService personManagerService = Enhancer.enhance(PersonManagerService.class);
    Log log = LogFactory.getLog(this.getClass());
//    /**
//     *  获取评分待处理的数据
//     * @param person
//     * @return
//     */
//    public List<DtBean> myGradingInToDoList(Person person) {
//        String sql =
//                "select entry_cycleid,entry_cyclename,entry_orgname,entry_orgid " +
//                        "    from ct_jx_kpi kpi left  join ct_jx_entry entry on kpi.kpi_entryid = entry.entry_id where kpi.kpi_wf='1' and kpi_graderid =? " +
//                        "group by entry_cycleid,entry_cyclename,entry_orgname,entry_orgid" ;
//        List<DtBean> dtBeanList = new DtBean().dao().find(sql, person.getId());
//        return dtBeanList;
//    }

    /**
     * 获取待办中所有的数据
     * @param person
     * @return
     */
    public List<DtBean> getMyToDoList(Person person) {
        List<DtBean> dtBeanList = new ArrayList<DtBean>();
        // 2 评分待处理的
        String sql = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,2 as type,case when entry_appmanagerlv=1 then eno.entryno_lv1time when entry_appmanagerlv=2 then eno.entryno_lv2time  when entry_appmanagerlv=3 then eno.entryno_lv3time  end entry_requiretime from ct_jx_entry e left join ct_jx_entryno eno on entry_no = eno.entryno_id where e.entry_apppersonid = ? and e.entry_apptype = '2'  ";

        // 1 自评待处理的
        String  sql1  = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,1 as type,eno.entryno_zptime entry_requiretime from ct_jx_entry e left join ct_jx_entryno eno on entry_no = eno.entryno_id where e.entry_apptype = '1' and entry_khpersonid= ? ";

        // 3 绩效经理待处理 只要有人提交了自评就可以在待处理里面看到这个考核周期的数据
       /* String sql2 =  "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,3 as type " +
                " from ( "+
                "        select *, row_number() over (partition by entry_no order by entry_orgid) as group_idx "+
                "        from " +
                " (select * from ct_jx_entry where (entry_apptype = '4' or entry_apptype = '2') and entry_creatorid = ? ) t"+
                " ) s "+
                "where s.group_idx = 1";*/
        //3 获取上级领导审批kpi申请修改
        String sql2 = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,41 as type,eno.entryno_kpiapptime entry_requiretime from ct_jx_entry e left join ct_jx_entryno eno on entry_no = eno.entryno_id where e.entry_apppersonid = ? and  e.entry_apptype = '61' ";

        //4 获取上级领导审批kpi待处理
        String sql3 = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,4 as type,eno.entryno_kpiapptime entry_requiretime from ct_jx_entry e left join ct_jx_entryno eno on entry_no = eno.entryno_id where e.entry_apppersonid = ? and e.entry_apptype = '6'  ";
        //6 考核人填写kpi待处理
        String sql4  = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,6 as type,eno.entryno_kpitime entry_requiretime from ct_jx_entry e left join ct_jx_entryno eno on entry_no = eno.entryno_id where e.entry_apptype = '5' and entry_khpersonid= ?";

        //获取待绩效面谈数据
        //4 获取上级领导审批kpi待处理
        String sql5 = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,9 as type,eno.entryno_interviewtime entry_requiretime from ct_jx_entry e left join ct_jx_entryno eno on entry_no = eno.entryno_id where e.entry_superid = ? and e.entry_interviewdate is null and e.entry_apptype = '9' and entry_offline is null ";

        String sql6 = "select * from  (" + sql + " union all " + sql1   + " union all " +   sql2+" union all " +   sql3 +" union all " +sql4  +" union all " +sql5  +"  ) t   order by t.entry_apptime desc ";
        dtBeanList.addAll(new DtBean().dao().find(sql6, person.getId(),person.getId(),person.getId(),person.getId(),person.getId(),person.getId()));



        return dtBeanList;
    }
    public boolean isQuickManager(){
        Person person = SessionUtil.getCurrentPerson();

        String value = codeService.getSysCodeName("是否开启组长快速审核").getSyscodeValue();
        if("是".equals(value) || "Y".equals(value)){
            return true;
        }
        String sql ="select  count(1) count from ct_jx_personmanager where personmanager_pid2=? or personmanager_pid3 =?";
        DtBean  bean = new DtBean().dao().findFirst(sql, person.getId(),person.getId());
        if(bean.getInt("count") ==0){//没有总监或总经理的配置
            return false;
        }
        return true;
    }
    /**
     * 获取待办中待评分的数据
     * @param person
     * @return
     */
    public List<Entry> getMyToGrading(Person person,String entryNo) {
        // 2 评分待处理的
        String sql = "select entry_cyclename,entry_khpersonname,entry_khdeptname,entry_appmanagerlv,entry_zpscore," +
                "entry_scorelv1,entry_ratinglv1,entry_infolv1,entry_scorelv2,entry_ratinglv2,entry_infolv2,entry_scorelv3,entry_ratinglv3,entry_infolv3," +
                "entry_apptype,entry_id,entry_no from ct_jx_entry e where e.entry_apppersonid = ? and e.entry_no=? and e.entry_apptype = '2'  ";

        List<Entry> entryList = new Entry().dao().find(sql,person.getId(),entryNo);
        return entryList;
    }

    /**
     * 获取自评页面数据
     * @param entryid
     * @param person
     * @return
     */
    public List<Kpi> getSelfEvaluationKpiList(String entryid, Person person) {
//        String sql =
//                " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid = k.kpi_id ) attachmentCnt from ct_jx_kpi k left join ct_jx_entry e on k.kpi_entryid = e.entry_id where " +
//                " e.entry_khpersonid = ? and e.entry_id = ?  order by kpi_type,kpi_index";
        String sql =
                " select k.*,0 attachmentCnt from ct_jx_kpi k left join ct_jx_entry e on k.kpi_entryid = e.entry_id where " +
                        " e.entry_khpersonid = ? and e.entry_id = ?  order by kpi_type,kpi_index";
        return Kpi.dao.find(sql,person.getId(),entryid);
    }

    /**
     * 保存自评
     * @param jsonObj
     */
    @Before(Tx.class)
    public void saveSelfEvaluation(JSONObject jsonObj) {
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        String entryId = null;
        //批次号
        for(int i=0; i<kpis.size(); i++){
            JSONObject json = kpis.getJSONObject(i);
            String kpiid = json.getString("kpiid");
            Kpi kpi = Kpi.dao.findById(kpiid);
            entryId = kpi.getKpiEntryid();
            kpi.setKpiZpscore(json.getBigDecimal("zpscore"));
            kpi.setKpiZp(json.getString("zp"));
            kpi.update();
        }
        jxCommonService.updateJxEntryZpScore(entryId);

        Entry entry = Entry.dao.findById(entryId);
        if(!"1".equals(entry.getEntryApptype())){
            throw new RuntimeException("状态异常 ，请刷新后重试");
        }
        Person person = SessionUtil.getCurrentPerson();
        if(!person.getId().equals(entry.getEntryKhpersonid())){
            throw new RuntimeException("不能保存他们数据 ，请刷新后重试");
        }
    }
    /**
     * 提交改进计划
     * @param jsonObj
     */
    @Before(Tx.class)
    public void submitMakeBetter(JSONObject jsonObj) {
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        String entryId = null;

        //批次号
        for(int i=0; i<kpis.size(); i++){
            JSONObject json = kpis.getJSONObject(i);
            String kpiid = json.getString("kpiid");
            Kpi kpi = Kpi.dao.findById(kpiid);
            entryId = kpi.getKpiEntryid();
            kpi.setKpiMakeBatter(json.getString("kpi_makebetter"));
            kpi.update();
        }
        Entry entry = Entry.dao.findById(entryId);

        Person person = SessionUtil.getCurrentPerson();
        if(!person.getId().equals(entry.getEntryKhpersonid())){
            throw new RuntimeException("不能提交他人改进计划 ，请刷新后重试");
        }

        entry.setEntryMbstatus("1");
        entry.setEntryMbtime(Tool.getCurrTime());
        entry.update();
        wflogService.addWfLog(person,person.getName() + "提交改进计划","92",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"1","");
    }


    /**
     * 提交自评
     * @param jsonObj
     * @param person
     */
    @Before(Tx.class)
    public void submitSelfEvaluation(JSONObject jsonObj, Person person) {
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        // 当jxEntryAppType=1 表示正常自评提交  当jxEntryAppType=2 表示是打回后自评提交
        String jxEntryAppType = jsonObj.getString("jxEntryAppType");
        String entryid = null;
        //保存数据
        saveSelfEvaluation(jsonObj);
        JSONObject json = kpis.getJSONObject(0);
        String kpiid = json.getString("kpiid");
        entryid = Kpi.dao.findById(kpiid).getKpiEntryid();


        Entry entry = Entry.dao.findById(entryid);

        //更新上级领导
        //获取考核人上级
        Object[] managerAndLv = personManagerService.getManagerAndLv(entry.getEntryKhpersonid(), 1);
        if(managerAndLv == null || managerAndLv[0] ==null ){
            throw new RuntimeException("获取员工:"+entry.getEntryKhpersonname()+"的上级失败！");
        }
        Person superPerson = (Person)managerAndLv[0];
        Integer lv = (Integer)managerAndLv[1];

        entry.setEntryAppManagerLv(lv);
        entry.setEntryApptype("2");//节点类型为审批\
        entry.setEntryWfstatus("1");
        entry.setEntryAppname("评分");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntrySuperId(superPerson.getId());
        entry.setEntrySuperName(superPerson.getName());
        entry.setEntryApppersonname(entry.getEntrySuperName());
        entry.setEntryApppersonid(entry.getEntrySuperId());
        entry.update();
        wflogService.addWfLog(person,person.getName() + "提交自评,待"+getManagerName(lv)+entry.getEntrySuperName()+"评分！","3",entry.getEntryCycleid(),entryid,entry.getEntryNo(),"1","");
        wxMsgService.sendEntryWxMsg(entry, WxMsgType.LDPF,superPerson);
    }

    /**
     * 打回自评
     * @param entryId
     * @param backReason
     * @param person
     * @return
     */
    @Before(Tx.class)
    public void backSelfEvaluation(String entryId, String backReason, Person person) {
       // String[] kpis = kpiIds.split(",");
        Entry jxEntry = Entry.dao.findById(entryId);
        if(!person.getId().equals(jxEntry.getEntryApppersonid()) ){
            throw new RuntimeException("审批人错误，请刷新后重试");
        }
        if(!"2".equals(jxEntry.getEntryApptype()) && !"4".equals(jxEntry.getEntryApptype())){
            throw new RuntimeException("状态不匹配，请刷新后重试！");
        }
        jxEntry.setEntryApptype("1");
        jxEntry.setEntryApptime(Tool.getCurrTime());
        jxEntry.setEntryWfstatus("3");
        jxEntry.update();
        wflogService.addWfLog(person,"上级领导("+person.getName()+")打回自评","4",jxEntry.getEntryCycleid(),jxEntry.getEntryId(),jxEntry.getEntryNo(),"2",backReason);

        try{
            //mailService.sendJxEmail(entryId,"1","30");
            wxMsgService.sendEntryWxMsg(jxEntry,WxMsgType.GRZPDH,jxEntry.getEntryKhpersonid(),jxEntry.getEntryKhpersonname());
        }catch (Exception e){
            log.error("提醒员工自评邮件发送失败："+e.getMessage()+",员工："+jxEntry.getEntryKhpersonname());
        }
    }

    /**
     * 保存评分结果
     * @param jsonObj
     */
    @Before(Tx.class)
    public void saveGradingResults(JSONObject jsonObj, Person person) {
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        String rating = jsonObj.getString("ratinglv");
        String entryInfo = jsonObj.getString("entryInfolv");
        String entryId = jsonObj.getString("entryId");;
        Entry entry = Entry.dao.findById(entryId);
        Integer entryAppManagerLv = entry.getEntryAppManagerLv();
        BigDecimal sumScore = new BigDecimal("0");
        if(!person.getId().equals(entry.getEntryApppersonid())){
            throw new RuntimeException("审批人错误 ，请刷新后重试");
        }
        //批次号
        for(int i=0; i<kpis.size(); i++){
            JSONObject json = kpis.getJSONObject(i);
            String kpiid = json.getString("kpiid");
            BigDecimal score = json.getBigDecimal("score");
            String info = json.getString("info");
            Kpi kpi = Kpi.dao.findById(kpiid);
            BigDecimal kpiWeight = kpi.getKpiWeight();
            if(kpi.getKpiType().equals("3") && score == null) {//附加项
               score = new BigDecimal(0);
            }

            kpi.setKpiInfo(info);
            kpi.setKpiScore(score);
            kpi.setKpiInfolv(info,entryAppManagerLv);
            kpi.setKpiScorelv(score,entryAppManagerLv);

            BigDecimal realScore = null;
            if(score != null){
                if(kpi.getKpiType().equals("3")){//附加项
                    realScore = score;
                }else{
                    realScore = score.multiply(kpiWeight).divide(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                sumScore = sumScore.add(realScore);
            }

            kpi.setKpiRealscore(realScore);
            kpi.update();
        }
        String newRating = getRating(sumScore);
        if(!newRating.equals(rating)){
            log.error("评级提交和评级计算结果不一致："+newRating+"》"+rating+","+entry.getEntryId()+","+person.getId());
        }
        entry.setEntryInfo(entryInfo,entryAppManagerLv);
        entry.setEntryRating(newRating,entryAppManagerLv);
        entry.setEntryScore(sumScore,entryAppManagerLv);
        entry.setEntryRating(newRating);
        entry.setEntryScore(sumScore);
        entry.update();
       // jxCommonService.updateJxEntryScoreAndRating(entry,rating);
    }
    private String getRating(BigDecimal sumScore){   //评级算法
        if(sumScore.compareTo(new BigDecimal("95")) >=0){
            return "S";
        }else if(sumScore.compareTo(new BigDecimal("90")) >=0){
            return "A";
        }else if(sumScore.compareTo(new BigDecimal("80")) >=0){
            return "B";
        }else if(sumScore.compareTo(new BigDecimal("70")) >=0){
            return "C";
        }
        return "D";
    }

    /**
     * 提交评分结果
     * @param jsonObj
     * @param person
     */
    @Before(Tx.class)
    public void submitGradingResults(JSONObject jsonObj, Person person) {
        HashSet<String> entryList = new HashSet<String>();
        //保存数据
        saveGradingResults(jsonObj,person);
        //提交流程
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        //批次号
        for(int i=0; i<kpis.size(); i++){
            JSONObject json = kpis.getJSONObject(i);
            String kpiid = json.getString("kpiid");
            Kpi kpi = Kpi.dao.findById(kpiid);
            if(kpi.getKpiScore() ==null){
                throw new RuntimeException("<"+kpi.getKpiName()+">未打分！");
            }
            //获取任意一条kpi中的entryid
            entryList.add(kpi.getKpiEntryid());
        }
        String entryNo = null;
        for(String entryid :entryList){
            Entry entry = Entry.dao.findById(entryid);
            //boolean isBack = "3".equals(entry.getEntryWfstatus());//是否为流程打回的节点
            Integer entryAppManagerLv = entry.getEntryAppManagerLv();
            String managerName = getManagerName(entryAppManagerLv);
            Object[] managerAndLv = null;
            if(entryAppManagerLv<3){
                managerAndLv = personManagerService.getManagerAndLv(entry.getEntryKhpersonid(), entryAppManagerLv + 1);
            }
            if(managerAndLv!=null && managerAndLv.length==2 && managerAndLv[0]!=null){
                Person manager = (Person)managerAndLv[0];
                String nextManagerName = getManagerName((Integer) managerAndLv[1]);
                entry.setEntryWfstatus("1");
                entry.setEntryAppManagerLv((Integer) managerAndLv[1]);
                entry.setEntryApptime(Tool.getCurrTime());
                entry.setEntryApppersonname(manager.getName());
                entry.setEntryApppersonid(manager.getId());
                wflogService.addWfLog(person,managerName+person.getName() + "提交评分,待"+nextManagerName+manager.getName()+"评分","4",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"1","");

            }else{
                entry.setEntryApptype("4");//节点类型绩效经理
                entry.setEntryWfstatus("1");
                entry.setEntryAppname("");
                entry.setEntryApptime(Tool.getCurrTime());
                entry.setEntryApppersonname("");
                entry.setEntryApppersonid("");

                wflogService.addWfLog(person,managerName+person.getName() + "提交评分","4",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"1","");

            }
            entry.update();
            copyLvGrading(entry,entryAppManagerLv,person);
            entryNo = entry.getEntryNo();
          //            List<Entry> list = Entry.dao.find("select * from ct_jx_entry where entry_apptype<>'4' and entry_no=?", entry.getEntryNo());
//            if(list.size() ==0){
//                EntryNo eno = jxCommonService.getEntryNoById(entry.getEntryNo());
//                wxMsgService.sendWxMsg(entry.getEntryNo(),"4",eno.getEntrynoCreatorid(),"6");
//            }
        }//2
        if(jxCommonService.isAllEntryStatus(entryNo,"4","9")){
            EntryNo eno = EntryNo.dao.findById(entryNo);
            eno.setEntrynoAppnode("2");
            eno.update();
        }

    }

    /**
     * 复制评分信息 （不同层级上级为同一人时）
     * @param entry
     * @param currLv  当前审批层级
     * @param person  当前审批人
     */
    public void copyLvGrading(Entry entry,int currLv,Person person){
        if(currLv<=1)return;
        PersonManager personManager = PersonManager.dao.findById(entry.getEntryKhpersonid());
        String pid = person.getId();
        for (int i = 1; i <=2 ; i++) {
            int lv = currLv-i;
            if(lv<1)break;
            String lvPid = personManager.getPersonManagerPid(lv);
            if(!pid.equals(lvPid))break;
            if(entry.getEntryScorelv(lv)!=null || StringUtils.isNotBlank(entry.getEntryRatinglv(lv))){
                //break;  可能会有各种打回的情况 250306
                log.info("评分数据被刷新,id:"+entry.getEntryId()+",被考核人："+entry.getEntryKhpersonname()+",层级："+lv+",原等级："+entry.getEntryRatinglv(lv)+",原分数："+entry.getEntryScorelv(lv)+",原评价："+entry.getEntryInfolv(lv));
            }

            entry.setEntryRatinglv(entry.getEntryRatinglv(currLv),lv);
            entry.setEntryScorelv(entry.getEntryScorelv(currLv),lv);
            entry.setEntryInfolv(entry.getEntryInfolv(currLv),lv);
            entry.update();

            List<Kpi> kpiList = jxCommonService.getKpiList(entry.getEntryId());
            for(Kpi kpi : kpiList){
                kpi.setKpiScorelv(kpi.getKpiScorelv(currLv),lv);
                kpi.setKpiInfolv(kpi.getKpiInfolv(currLv),lv);
                kpi.update();
            }

        }
    }
    /**
     * 提交快速批量评分结果
     * @param jsonObj
     * @param person
     */
    @Before(Tx.class)
    public void submitQuickGrading(JSONObject jsonObj, Person person) {
        HashSet<String> entryList = new HashSet<String>();
        //提交流程
        JSONArray entrys = (JSONArray)jsonObj.get("entrys");
        String currTime = Tool.getCurrTime();
        String entryNo = null;
        //批次号
        for(int i=0; i<entrys.size(); i++) {
            JSONObject json = entrys.getJSONObject(i);

            String entryId = json.getString("entryId");
            String info = json.getString("info");
            BigDecimal score = json.getBigDecimal("score");
            String rating = json.getString("rating");
            if(StringUtils.isBlank(entryId)){
                throw new RuntimeException("提交数据异常，请刷新后重试！");
            }
            if(StringUtils.isBlank(rating) ||score==null){
                throw new RuntimeException("评分评级数据不能为空！");
            }
            Entry entry = Entry.dao.findById(entryId);
            if(!person.getId().equals(entry.getEntryApppersonid()) ){
                throw new RuntimeException("被考核人："+entry.getEntryKhpersonname()+"的审批人错误，请刷新后重试");
            }
            entryNo = entry.getEntryNo();
            Integer entryAppManagerLv = entry.getEntryAppManagerLv();
            String managerName = getManagerName(entryAppManagerLv);

            Object[] managerAndLv = null;
            if(entryAppManagerLv<3){
                managerAndLv = personManagerService.getManagerAndLv(entry.getEntryKhpersonid(), entryAppManagerLv + 1);
            }
            if(managerAndLv!=null && managerAndLv.length==2 && managerAndLv[0]!=null){
                Person manager = (Person)managerAndLv[0];
                String nextManagerName = getManagerName((Integer) managerAndLv[1]);
                entry.setEntryWfstatus("1");
                entry.setEntryAppManagerLv((Integer) managerAndLv[1]);
                entry.setEntryApptime(currTime);
                entry.setEntryApppersonname(manager.getName());
                entry.setEntryApppersonid(manager.getId());
                wflogService.addWfLog(person,managerName+person.getName() + "提交评分,待"+nextManagerName+manager.getName()+"评分","4",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"1","");
            }else{
                entry.setEntryApptype("4");//节点类型绩效经理
                entry.setEntryWfstatus("1");
                entry.setEntryAppname("");
                entry.setEntryApptime(currTime);
                entry.setEntryApppersonname("");
                entry.setEntryApppersonid("");
                wflogService.addWfLog(person,managerName+person.getName() + "提交评分","4",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"1","");

            }
            String newRating = getRating(score);
            if(!newRating.equals(rating)){
                log.error("评级提交和评级计算结果不一致："+newRating+"》"+rating+","+entry.getEntryId()+","+person.getId());
            }
            entry.setEntryInfo(info,entryAppManagerLv);
            entry.setEntryRating(newRating,entryAppManagerLv);
            entry.setEntryScore(score,entryAppManagerLv);
            entry.setEntryRating(newRating);
            entry.setEntryScore(score);
            entry.update();

            List<Kpi> kpiList = jxCommonService.getKpiList(entryId);
            for(Kpi kpi:kpiList){
                BigDecimal kpiWeight = kpi.getKpiWeight();
                if(kpi.getKpiType().equals("3")) {//附加项
                    score = new BigDecimal(0);
                }
                kpi.setKpiInfo(info);
                kpi.setKpiScore(score);
                kpi.setKpiInfolv(info,entryAppManagerLv);
                kpi.setKpiScorelv(score,entryAppManagerLv);

                BigDecimal realScore = null;
                if(score != null){
                    if(kpi.getKpiType().equals("3")){//附加项
                        realScore = new BigDecimal(0);
                    }else{
                        realScore = score.multiply(kpiWeight).divide(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                }
                kpi.setKpiRealscore(realScore);
                kpi.update();
            }
            copyLvGrading(entry,entryAppManagerLv,person);
        }
        if(jxCommonService.isAllEntryStatus(entryNo,"4","9")){
            EntryNo eno = EntryNo.dao.findById(entryNo);
            eno.setEntrynoAppnode("2");
            eno.update();
        }

    }
    private String getManagerName(int level){
        String managerName = "上级";
        if(level == 1)managerName = "组长";
        if(level == 2)managerName = "总监";
        if(level == 3)managerName = "总经理";
        return managerName;
    }

    /**
     * 保存快速批量评分结果
     * @param jsonObj
     * @param person
     */
    @Before(Tx.class)
    public void saveQuickGrading(JSONObject jsonObj, Person person) {
        HashSet<String> entryList = new HashSet<String>();
        //提交流程
        JSONArray entrys = (JSONArray)jsonObj.get("entrys");
        //批次号
        for(int i=0; i<entrys.size(); i++) {
            JSONObject json = entrys.getJSONObject(i);

            String entryId = json.getString("entryId");
            String info = json.getString("info");
            BigDecimal score = json.getBigDecimal("score");
            String rating = json.getString("rating");
            if(StringUtils.isBlank(entryId)){
                throw new RuntimeException("保存数据异常，请刷新后重试！");
            }
//            if(StringUtils.isBlank(rating) ||score==null){
//                throw new RuntimeException("评分评级数据不能为空！");
//            }
            Entry entry = Entry.dao.findById(entryId);
            if(!person.getId().equals(entry.getEntryApppersonid()) ){
                throw new RuntimeException("被考核人："+entry.getEntryKhpersonname()+"的审批人错误，请刷新后重试");
            }
            Integer entryAppManagerLv = entry.getEntryAppManagerLv();
            String newRating = getRating(score);
            if(!newRating.equals(rating)){
                log.error("评级提交和评级计算结果不一致："+newRating+"》"+rating+","+entry.getEntryId()+","+person.getId());
            }
            entry.setEntryInfo(info,entryAppManagerLv);
            entry.setEntryRating(newRating,entryAppManagerLv);
            entry.setEntryScore(score,entryAppManagerLv);
            entry.setEntryRating(newRating);
            entry.setEntryScore(score);
            entry.update();

            List<Kpi> kpiList = jxCommonService.getKpiList(entryId);
            for(Kpi kpi:kpiList){
                BigDecimal kpiWeight = kpi.getKpiWeight();
                if(kpi.getKpiType().equals("3")) {//附加项
                    score = new BigDecimal(0);
                }
                kpi.setKpiInfo(info);
                kpi.setKpiScore(score);
                kpi.setKpiInfolv(info,entryAppManagerLv);
                kpi.setKpiScorelv(score,entryAppManagerLv);

                BigDecimal realScore = null;
                if(score != null){
                    if(kpi.getKpiType().equals("3")){//附加项
                        realScore = new BigDecimal(0);
                    }else{
                        realScore = score.multiply(kpiWeight).divide(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                }
                kpi.setKpiRealscore(realScore);
                kpi.update();
            }
            //copyLvGrading(entry,entryAppManagerLv,person);
        }

    }


    /**
     * 获取考核查询页面数据
     * 只查询考核状态的数据
     * @param person
     * @param pageNumber
     * @param pageSize
     * @param cycleId
     * @param khOrg
     * @param personName
     * @return
     */
    public PageBean getJxEntryQueryList(Person person, Integer pageNumber, Integer pageSize, String cycleId, String khOrg, String personName) {

        String pid = person.getId();
        String sqlCount  =
                "select  count(1)  from ct_jx_entry  b " +
                        " left join ct_jx_personmanager d on  b.entry_khpersonid= d.personmanager_id " +
                        " left join t_bd_person p on b.entry_khpersonid =p.fid   where" +
                        "  (b.entry_superid ='"+pid+"' or d.personmanager_pid1='"+pid+"' or d.personmanager_pid2='"+pid+"' or d.personmanager_pid3='"+pid+"' or p.cfleaderid = '"+pid+"'  )" +
                        "and b.entry_apptype <>'0' " ;


        String sqlPara  =

                "select  b.entry_cyclename,b.entry_khpersonname,b.entry_displayname,b.entry_orgname,b.entry_submittime,b.entry_apptype,b.entry_interviewtime,b.entry_no,b.entry_id" +
                        ",case when b.entry_apptype <>'9' then null else entry_score end entry_score" +
                        ",case when b.entry_apptype <>'9' then '' else entry_rating end entry_rating" +
                        ",case when entry_superid ='"+pid+"' then 1 else 2 end issuper  " +
                        " from ct_jx_entry  b left join ct_jx_personmanager d on  b.entry_khpersonid= d.personmanager_id  " +
                        " left join t_bd_person p on b.entry_khpersonid =p.fid   where " +
                        "  (b.entry_superid ='"+pid+"' or d.personmanager_pid1='"+pid+"' or d.personmanager_pid2='"+pid+"' or d.personmanager_pid3='"+pid+"' or p.cfleaderid = '"+pid+"'  )" +
                        "and b.entry_apptype <>'0' " ;

        String whereBy = "";
        if(!StringUtils.isBlank(cycleId)){
            whereBy += "and b.entry_cycleid = '"+cycleId+"'";
        }
        if(!StringUtils.isBlank(khOrg)){
            whereBy += " and b.entry_orgid = '"+khOrg+"'";
        }

        if(!StringUtils.isBlank(personName)){
            whereBy += " and b.entry_khpersonname like '%"+personName+"%'";
        }

        sqlCount += whereBy;
        sqlPara += whereBy;

        sqlPara += "order by entry_submittime desc ,entry_orgname desc";//按照时间与考核部门排序
        PageBean pageBean = new PageBean();
        Page<DtBean> page = new DtBean().dao().paginateByFullSql(pageNumber, pageSize, sqlCount, sqlPara);
        pageBean.setCount(page.getTotalRow());
        pageBean.setData(page.getList());
        return pageBean;




    }

    /**
     * 获取我的考核数据
     * 只查看处于考核状态的数据
     * @param personId
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public PageBean getMyJxEntryList(String personId, int pageNumber, int pageSize) {
       String sqlCount   =
               "select count(1) from ct_jx_entry en  where en.entry_khpersonid = '"+personId+"' ";
//        String sqlPara   =
//                "select en.* ,(select count(*) from ct_jx_attachment where attachment_entryfeedback =entry_id) attachmentCnt   from ct_jx_entry en " +
//                        "where en.entry_khpersonid = '"+personId+"' ";
        String sqlPara   =
                "select en.* ,0 attachmentCnt   from ct_jx_entry en " +
                        "where en.entry_khpersonid = '"+personId+"' ";

        String whereBy = " and entry_apptype<>'0'  " ;//order by entry_submittime desc
        sqlCount += whereBy;
        sqlPara += whereBy;
        sqlPara += "order by entry_submittime desc ";//按照时间排序
        PageBean pageBean = new PageBean();
        Page<Entry> page = Entry.dao.paginateByFullSql(pageNumber, pageSize, sqlCount,sqlPara);
        pageBean.setCount(page.getTotalRow());
        pageBean.setData(page.getList());
        return pageBean;
    }

    /**
     * 根据entryid获取所有的kpi明细
     * @param entryid
     */
    public List<Kpi> getMyJxKpiList(String entryid,Person person) {
//        String sql =  "select kpi.* from ct_jx_kpi kpi  left join ct_jx_entry entry on kpi.kpi_entryid = entry.entry_id  where kpi.kpi_entryid = ? and " +
//                "entry.entry_khpersonid=?  order by len(kpi.kpi_num),kpi.kpi_num  asc ";
        String sql =  "select kpi.* from ct_jx_kpi kpi  left join ct_jx_entry entry on kpi.kpi_entryid = entry.entry_id  where kpi.kpi_entryid = ? and " +
                "entry.entry_khpersonid=?  order by length(kpi.kpi_num),kpi.kpi_num  asc "; //oracle 调整
        return  Kpi.dao.find(sql,entryid,person.getId());
    }

    /**
     * 整理 KPI ，相同KPI得分合并到head中
     * @param list
     * @return
     */
//    public void convertKpiList(List<Kpi> list){
//        //kpi_sweight
//        Kpi kpi = null;
//        BigDecimal scoreSum = new BigDecimal(0);
//        for(Kpi k:list){
//            BigDecimal kpiScore = k.getKpiScore();
//            if(k.getKpiHead().equals("1")){
//                if(kpi!=null){
//                    kpi.setKpiScore(Tool.getStripZeros(scoreSum));
//                    kpi = null;
//                }
//                kpi =k;
//                if(kpiScore==null){
//                    scoreSum = new BigDecimal(0);
//                }else{
//                    scoreSum = kpiScore.multiply(k.getKpiSweight().divide(new BigDecimal(100)));
//                }
//            }else if(k.getKpiHead().equals("2")){
//                if(kpiScore!=null){
//                    scoreSum = kpiScore.multiply(k.getKpiSweight().divide(new BigDecimal(100))).add(scoreSum);
//                }
//            }else if(k.getKpiHead().equals("3")) {
//                k.setKpiScore(Tool.getStripZeros(kpiScore));
//                if(kpi!=null){
//                    kpi.setKpiScore(Tool.getStripZeros(scoreSum));
//                    kpi = null;
//                }
//            }
//        }
//        if(kpi!=null){
//            kpi.setKpiScore(Tool.getStripZeros(scoreSum));
//        }
//    }


    /**
     * 获取评分人kpi明细
     * @param entryid
     * @param person
     * @return
     */
    public List<Kpi> getGradingKpiList(String  entryid, Person person) {
        Entry entry = Entry.dao.findById(entryid);
        if(!person.getId().equals(entry.getEntryApppersonid())){
            throw new RuntimeException("审批人错误，请刷新后重试");
        }
        if(!"2".equals(entry.getEntryApptype())){
            throw new RuntimeException("状态不匹配，请刷新后重试！");
        }
//        String sql =
//                " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid =k.kpi_id ) attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ? " +
//                " order by kpi_type,len(kpi_num),kpi_num asc ";
//        String sql =
//                " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid =k.kpi_id ) attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ? " +
//                        " order by kpi_type,length(kpi_num),kpi_num asc "; //oracle 调整
        String sql =
                " select k.*,0 attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ? " +
                        " order by kpi_type,length(kpi_num),kpi_num asc "; //oracle 调整

        return Kpi.dao.find(sql,entryid);
    }
    /**
     * 获取评分人数据 默认继承上一级数据
     * @param entry
     * @param gradingKpiList
     * @return
     */
    public void setManagerLvInfo(Entry entry,List<Kpi> gradingKpiList) {
        Integer entryAppManagerLv = entry.getEntryAppManagerLv(); //当前层级
        if(entryAppManagerLv == 1){
            return ;
        }
        if(entryAppManagerLv == 2 && entry.getEntryScorelv2() == null  && entry.getEntryScorelv1()!=null){//2级赋1级数据
            entry.setEntryScorelv2(entry.getEntryScorelv1());
            //entry.setEntryInfolv2(entry.getEntryInfolv1());
            entry.setEntryRatinglv2(entry.getEntryRatinglv1());

            for (Kpi kpi : gradingKpiList) {
                kpi.setKpiScorelv2(kpi.getKpiScorelv1());
                kpi.setKpiInfolv2(kpi.getKpiInfolv1());
            }
        }
        if(entryAppManagerLv == 3 && entry.getEntryScorelv3() == null && entry.getEntryScorelv2()!=null){//3级赋2级数据
            entry.setEntryScorelv3(entry.getEntryScorelv2());
           // entry.setEntryInfolv3(entry.getEntryInfolv2());
            entry.setEntryRatinglv3(entry.getEntryRatinglv2());

            for (Kpi kpi : gradingKpiList) {
                kpi.setKpiScorelv3(kpi.getKpiScorelv2());
                kpi.setKpiInfolv3(kpi.getKpiInfolv2());
            }
        }
        if(entryAppManagerLv == 3 && entry.getEntryScorelv3() == null && entry.getEntryScorelv2()==null && entry.getEntryScorelv1()!=null){//3级赋1级数据
            entry.setEntryScorelv3(entry.getEntryScorelv1());
            //entry.setEntryInfolv3(entry.getEntryInfolv1());
            entry.setEntryRatinglv3(entry.getEntryRatinglv1());

            for (Kpi kpi : gradingKpiList) {
                kpi.setKpiScorelv3(kpi.getKpiScorelv1());
                kpi.setKpiInfolv3(kpi.getKpiInfolv1());
            }
        }

    }

    /**
     * 获取批量评分数据
     * @param khOrgid 考核组织
     * @param khcycle 考核周期
     * @param person
     */
    public List<Kpi> getGradingInBathList(String khOrgid,String khcycle,Person person){
//        String sql =
//            " select k.*,e.entry_khpersonname,  (select count(*) from ct_jx_attachment where attachment_kpiid in " +
//        " (select k1.kpi_id from ct_jx_kpi k1 where k1.kpi_entryid = k.kpi_entryid and k1.kpi_index = k.kpi_index ) " +
//                " ) attachmentCnt from ct_jx_kpi k "+
//            " left join ct_jx_entry e on k.kpi_entryid = e.entry_id "+
//            " where  e.entry_orgid = ? and e.entry_cycleid = ? and  k.kpi_wf='1'  and k.kpi_graderid =? order by e.entry_khpersonname asc ";
        String sql =
                " select k.*,e.entry_khpersonname,  0 attachmentCnt from ct_jx_kpi k "+
                        " left join ct_jx_entry e on k.kpi_entryid = e.entry_id "+
                        " where  e.entry_orgid = ? and e.entry_cycleid = ? and  k.kpi_wf='1'  and k.kpi_graderid =? order by e.entry_khpersonname asc ";
        List<Kpi> KpiList = new Kpi().dao().find(sql, khOrgid, khcycle, person.getId());
        return KpiList;
    }

    /**
     * 保存或提交自填KPI
     * @param jsonObj
     * @return
     */
    @Before(Tx.class)
    public String saveOrSubmitSelfKpi(JSONObject jsonObj) {
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        String entryid = (String) jsonObj.get("entryid");
        String rearson = (String) jsonObj.get("reason");
        Person person = SessionUtil.getCurrentPerson();
        //type = 1 表示保存  type = 2 表示提交
        String type = (String) jsonObj.get("type");
        Entry jxEntry = Entry.dao.findById(entryid);
        boolean applyModify = false;
        List<Kpi> kpiList = getNoselfkpiList(entryid);
        int maxNum = 0;//绩效专员填写kpi最大max
        int maxIndex = 0;
        if(kpiList.size()>0){
            maxNum = Integer.parseInt(kpiList.get(kpiList.size()-1).getKpiNum());//绩效专员填写kpi最大max
            maxIndex = kpiList.get(kpiList.size()-1).getKpiIndex();
        }
        if("7".equals(jxEntry.getEntryApptype()) && jxEntry.getEntryKhpersonid().equals(person.getId())){
            applyModify = true;
        }
        if((SessionUtil.isAdmin() || SessionUtil.isJxjl())){
            //必须是考核人kpi编辑状态 或申请修改时才能保存
        }else  if(!"5".equals(jxEntry.getEntryApptype()) && !"7".equals(jxEntry.getEntryApptype()) || !jxEntry.getEntryKhpersonid().equals(person.getId())){
            throw new RuntimeException("链接错误！请退出重试！");
        }
        if(applyModify && "1".equals(type)){
            throw new RuntimeException("当前状态只允许提交数据！");
        }
        if(applyModify && StringUtils.isBlank(rearson)){
            throw new RuntimeException("原因不能为空！");
        }
        if(applyModify){
            Db.update("delete from ct_jx_kpi  where kpi_entryid = ?",entryid);
        }

        //批次号
        for(int i=0; i<kpis.size(); i++){
            JSONObject json = kpis.getJSONObject(i);
            String kpiid = json.getString("kpiid");
            maxNum++;
            maxIndex++;
            if(StringUtils.isBlank(kpiid)){//kpiid为空新增
                String kpiType=json.getString("kpitype");
                String apiName =json.getString("kpiname");
                Kpi kpi = new Kpi();
                String kid = Tool.uuid();
                kpi.setKpiId(kid);
                kpi.setKpiEntryid(entryid);
                kpi.setKpiName(apiName);
                kpi.setKpiType(kpiType);
                //kpi.setKpiBaseid(json.getString("kpibaseid"));
                kpi.setKpiDefine(json.getString("kpidefine"));
                kpi.setKpiCaption(json.getString("kpicaption"));
                kpi.setKpiTarget(json.getString("kpitarget"));
                kpi.setKpiWeight(json.getBigDecimal("kpiweight"));
//                kpi.setKpiGraderid(json.getString("kpigraderid"));
//                kpi.setKpiGradername(json.getString("kpigradername"));
//                kpi.setKpiNum(String.valueOf(json.getInteger("kpinum")+maxNum));
//                kpi.setKpiIndex(json.getInteger("kpiIndex")+maxIndex);
                kpi.setKpiNum(String.valueOf(maxNum));
                kpi.setKpiIndex(maxIndex);
                kpi.setKpiIsSelf("1");

                kpi.setKpiBaseid(json.getString("kpiBaseid"));
                kpi.save();
            }else{//kpiid不为空，
                Kpi kpi = Kpi.dao.findById(kpiid);
                String kpiType=json.getString("kpitype");
                String apiName =json.getString("kpiname");
                kpi.setKpiName(apiName);
                kpi.setKpiType(kpiType);
                kpi.setKpiDefine(json.getString("kpidefine"));
                kpi.setKpiCaption(json.getString("kpicaption"));
                kpi.setKpiTarget(json.getString("kpitarget"));
                kpi.setKpiWeight(json.getBigDecimal("kpiweight"));
//                kpi.setKpiGraderid(json.getString("kpigraderid"));
//                kpi.setKpiGradername(json.getString("kpigradername"));
//                kpi.setKpiNum(String.valueOf(json.getInteger("kpinum")+maxNum));
//                kpi.setKpiIndex(json.getInteger("kpiIndex")+maxIndex);
                kpi.setKpiNum(String.valueOf(maxNum));
                kpi.setKpiIndex(maxIndex);
                kpi.update();
            }
        }

        //更新重复indexNum数据的KpiHead
        jxCommonService.resetKpiHead(entryid);
        //保存不需要校验数据
        if("1".equals(type)){
            return entryid;
        }


        /***************kpi数据校验**********************/
        List<Kpi> selfKpiList = getSelfkpiList(entryid);
        if(selfKpiList.size() == 0){
            throw new RuntimeException("没有具体的kpi，无法保存");
        }

        //int tempKpiIndex = 0;
        BigDecimal kpiWeightSum = new BigDecimal("0");
        HashSet<Integer> kpiIndexs = new HashSet<>();
        for(int i=0;i<selfKpiList.size();i++){
            Kpi k = selfKpiList.get(i);
            Integer kpiIndex = k.getKpiIndex();
            String kpiName = k.getKpiName();
            String kpiDefine = k.getKpiDefine();
            String kpiarget = k.getKpiTarget();
            String kpiCaption = k.getKpiCaption();
            BigDecimal kpiWeight = k.getKpiWeight();
            //String kpiGraderid = k.getKpiGraderid();
            String kpiType = k.getKpiType();
            if(StringUtils.isBlank(kpiName)){
                throw new RuntimeException("关键考核指标不能为空！");
            }
            if(kpiType.equals("0") && StringUtils.isBlank(kpiCaption)){
                throw new RuntimeException("衡量标准不能为空！");
            }
            if(kpiWeight == null || kpiWeight.compareTo(new BigDecimal(0)) ==0){
                throw new RuntimeException("权重必须大于0!");
            }
            kpiWeightSum = kpiWeightSum.add(kpiWeight);


        }
        //获取考核人自填kpi占比
        BigDecimal selfkpiweight = jxEntry.getEntrySelfkpiweight();
        //判断指标权重的和
        if(kpiWeightSum.compareTo(selfkpiweight) != 0){
            throw new RuntimeException("指标权重之和应为"+selfkpiweight+"%！您提交的指标之和为："+kpiWeightSum+"%");
        }

        //更新上级领导
        //获取考核人上级
        Object[] managerAndLv = personManagerService.getManagerAndLv(jxEntry.getEntryKhpersonid(), 1);
        if(managerAndLv == null || managerAndLv[0] ==null ){
            throw new RuntimeException("获取员工:"+jxEntry.getEntryKhpersonname()+"的上级失败！");
        }
        Person superPerson = (Person)managerAndLv[0];
        Integer lv = (Integer)managerAndLv[1];
        //更新 ct_jx_entry 中流程节点为  领导审批kpi
        jxEntry.setEntryApptype("6");
        if(applyModify)jxEntry.setEntryApptype("61");
        jxEntry.setEntryAppManagerLv(lv);
        //设置这个的原因 当被打回时  wfstatus会变成3  再次提交的时候 需要把wfstatus设置为1
        jxEntry.setEntryWfstatus("1");
        jxEntry.setEntryApptime(Tool.getCurrTime());
        jxEntry.setEntrySuperName(superPerson.getName());
        jxEntry.setEntrySuperId(superPerson.getId());
        jxEntry.setEntryApppersonid(superPerson.getId());
        jxEntry.setEntryApppersonname(superPerson.getName());
        jxEntry.setEntryKpitime(Tool.getCurrTime());
        jxEntry.update();

        addHistoryKpi(selfKpiList);

        if(applyModify){
            String wflogName = person.getName()+"申请修改指标，待上级领导（"+superPerson.getName()+"）审核！";
            String wflogType = "71";
            wflogService.addWfLog(person,wflogName,wflogType,jxEntry.getEntryCycleid(),entryid,jxEntry.getEntryNo(),"3",rearson);
            wxMsgService.sendEntryWxMsg(jxEntry,WxMsgType.SJSHGRXG,superPerson);
        }else{
            wflogService.addWfLog(SessionUtil.getCurrentPerson(),SessionUtil.getCurrentPerson().getName() + "提交指标,待上级"+jxEntry.getEntrySuperName()+"审核!","7",jxEntry.getEntryCycleid(),entryid,jxEntry.getEntryNo(),"1","");
            wxMsgService.sendEntryWxMsg(jxEntry,WxMsgType.SJSH,superPerson);
        }


        return entryid;
    }

    private void addHistoryKpi(List<Kpi> kpiList){
        if(kpiList == null || kpiList.size()==0)return;
        String entryId = kpiList.get(0).getKpiEntryid();

        String time = Tool.getCurrTime();
        int histNoIndex = 1;
        List<KpiHistNo> kpiHistNos = KpiHistNo.dao.find("select * from ct_jx_kpihistno where kpihistno_entryid=? order by kpihistno_index desc", entryId);

        if(kpiHistNos !=null && kpiHistNos.size()>0){
            histNoIndex = kpiHistNos.get(0).getKpiHistNoIndex() +1;
        }
        String hkId = Tool.uuid();
        KpiHistNo kpiHistNo = new KpiHistNo();
        kpiHistNo.setKpiHistNoEntryId(entryId);
        kpiHistNo.setKpiHistNoTime(time);
        kpiHistNo.setKpiHistNoIndex(histNoIndex);
        kpiHistNo.setKpiHistNoId(hkId);
        kpiHistNo.save();

        for (Kpi kpi :kpiList){
            KpiHist kh =  copyKpiHist(kpi);
            kh.setKpiHistnoId(hkId);
            kh.setKpiId(Tool.uuid());
            kh.setKpiPid(kpi.getKpiId());
            kh.save();
        }
    }
    private KpiHist copyKpiHist(Kpi kpi){
        if(kpi == null)return null;
        KpiHist kpiHist = new KpiHist();
        kpiHist.setKpiBaseid(kpi.getKpiBaseid());
        kpiHist.setKpiCaption(kpi.getKpiCaption());
        kpiHist.setKpiDefine(kpi.getKpiDefine());
        kpiHist.setKpiEntryid(kpi.getKpiEntryid());
        kpiHist.setKpiIndex(kpi.getKpiIndex());
        kpiHist.setKpiIsSelf(kpi.getKpiIsSelf());
        kpiHist.setKpiName(kpi.getKpiName());
        kpiHist.setKpiNum(kpi.getKpiNum());
        kpiHist.setKpiType(kpi.getKpiType());
        kpiHist.setKpiTarget(kpi.getKpiTarget());
        kpiHist.setKpiWeight(kpi.getKpiWeight());
        return kpiHist;
    }

    /**
     * 上级领导审批通过自填KPI
     * @param entryId
     * @param person
     * @return
     */
    @Before(Tx.class)
    public void approvedSelfKpi(String entryId, Person person) {
        Entry entry = Entry.dao.findById(entryId);
        if(!"6".equals(entry.getEntryApptype())){
            throw new RuntimeException("链接错误！请退出重试！");
        }
        if(!person.getId().equals(entry.getEntrySuperId())){
            throw new RuntimeException("上级数据匹配错误！请退出重试！");
        }
        entry.setEntryApptype("7");//节点进入到待发起评分
        entry.setEntryWfstatus("1");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntryApppersonid("");
        entry.setEntryApppersonname("");
        entry.update();
        if(jxCommonService.isAllEntryStatus(entry.getEntryNo(),"7")){
            EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
            eno.setEntrynoAppnode("7");
            eno.update();
        }
        //日志
        wflogService.addWfLog(person,"上级领导("+person.getName() + ")审核通过目标","8",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"1","");
    }

    /**
     * 上级领导同意  申请修改指标
     * @param entryId
     * @param person
     * @return
     */
    @Before(Tx.class)
    public void approvedModifyKpi(String entryId, Person person) {
        Entry entry = Entry.dao.findById(entryId);
        if(!"61".equals(entry.getEntryApptype())){
            throw new RuntimeException("链接错误！请退出重试！");
        }
        if(!person.getId().equals(entry.getEntrySuperId())){
            throw new RuntimeException("上级数据匹配错误！请退出重试！");
        }
        entry.setEntryApptype("7");//节点进入到待发起评分
        entry.setEntryWfstatus("1");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntryApppersonid("");
        entry.setEntryApppersonname("");
        entry.update();
        //日志
        wflogService.addWfLog(person,"上级领导("+person.getName() + ")批准申请人修改指标","81",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"1","");
        //TODO 加微信消息
    }


    /**
     * 上级领导不同意修改指标
     * @param entryId
     * @param rearson
     * @param person
     * @param isSuperManager 是否上级领导
     * @return
     */
    @Before(Tx.class)
    public void backModifyKpi(String entryId, String rearson,Person person,boolean isSuperManager) {
        Entry entry = Entry.dao.findById(entryId);
        if(!"61".equals(entry.getEntryApptype())){
            throw new RuntimeException("链接错误！请退出重试！");
        }
        if(isSuperManager && !person.getId().equals(entry.getEntrySuperId())){
            throw new RuntimeException("上级数据匹配错误！请退出重试！");
        }
        if(!isSuperManager && !SessionUtil.isJxjl()&& !SessionUtil.isAdmin()){
            throw new RuntimeException("绩效专员才允许该操作！请退出重试！");
        }
        entry.setEntryApptype("7");//节点进入到待发起评分
        entry.setEntryWfstatus("1");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntryApppersonid("");
        entry.setEntryApppersonname("");
        entry.update();

        //还原上一个版本指标
        backHistoryKpi(entryId);

        if(jxCommonService.isAllEntryStatus(entry.getEntryNo(),"7")){
            EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
            eno.setEntrynoAppnode("7");
            eno.update();
        }
        //日志
        if(isSuperManager){
            wflogService.addWfLog(person,"上级领导("+person.getName() + ")不同意申请人修改指标","81",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",rearson);
        }else{
            wflogService.addWfLog(person,"绩效专员("+person.getName() + ")退回申请人修改指标","81",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",rearson);
        }
        //TODO 加微信消息
    }

    private void backHistoryKpi(String entryId){
        String time = Tool.getCurrTime();
        String lastNoId = null;
        String  toNoId = null;
        List<KpiHistNo> kpiHistNos = KpiHistNo.dao.find("select * from ct_jx_kpihistno where kpihistno_entryid=? order by kpihistno_index desc", entryId);

        if(kpiHistNos !=null && kpiHistNos.size()>0){
            lastNoId = kpiHistNos.get(0).getKpiHistNoId();
            toNoId = kpiHistNos.get(1).getKpiHistNoId();
        }else{
            throw new RuntimeException("数据异常！");
        }
        Db.update("delete from ct_jx_kpihistno  where kpihistno_id = ? ",lastNoId);
        Db.update("delete from ct_jx_kpihist  where kpi_entryid = ? and kpi_histnoid=?",entryId,lastNoId);
        Db.update("delete from ct_jx_kpi  where kpi_entryid = ? ",entryId);
        List<KpiHist> kpiHists = KpiHist.dao.find("select * from ct_jx_kpihist where kpi_histnoid = ?", toNoId);
        for(KpiHist kpiHist : kpiHists){
            Kpi kpi = new Kpi();
            String kid = Tool.uuid();
            kpi.setKpiId(kid);
            kpi.setKpiEntryid(entryId);
            kpi.setKpiName(kpiHist.getKpiName());
            kpi.setKpiType(kpiHist.getKpiType());
            kpi.setKpiDefine(kpiHist.getKpiDefine());
            kpi.setKpiCaption(kpiHist.getKpiCaption());
            kpi.setKpiTarget(kpiHist.getKpiTarget());
            kpi.setKpiWeight(kpiHist.getKpiWeight());
            kpi.setKpiNum(kpiHist.getKpiNum());
            kpi.setKpiIndex(kpiHist.getKpiIndex());
            kpi.setKpiIsSelf(kpiHist.getKpiIsSelf());
            kpi.setKpiBaseid(kpiHist.getKpiBaseid());
            kpi.save();
        }
    }

//    /**
//     * 申请修改KPI
//     *
//     * @param entryId
//     * @param rearson
//     * @param person
//     * @return
//     */
//    @Before(Tx.class)
//    public void applyModifyKpi( String entryId, String rearson, Person person) {
//
//        Entry entry = Entry.dao.findById(entryId);
//        if(!entry.getEntryKhpersonid().equals(person.getId())){
//            throw new RuntimeException("只能本人申请修改指标！");
//        }
//        if(!"7".equals(entry.getEntryApptype())){
//            throw new RuntimeException("状态错误！请刷新页面后重试！");
//        }
//        //更新上级领导
//        //获取考核人上级
//        Person superPerson = deptManagerService.getManager(entry.getEntryKhdeptid(),1);
//        if(superPerson == null){
//            throw new RuntimeException("获取员工:"+entry.getEntryKhpersonname()+"的上级失败！");
//        }
//        String wflogName = person.getName()+"申请修改指标，待上级领导（"+superPerson.getName()+"）审核！";
//        String wflogType = "71";
//        wflogService.addWfLog(person,wflogName,wflogType,entry.getEntryCycleid(),entryId,entry.getEntryNo(),"3",rearson);
//
//        entry.setEntryApptime(Tool.getCurrTime());
//        entry.setEntryApptype("61");
//        entry.setEntryWfstatus("4");
//        entry.setEntryAppManagerLv(1);
//        entry.setEntryApptime(Tool.getCurrTime());
//        entry.setEntrySuperName(superPerson.getName());
//        entry.setEntrySuperId(superPerson.getId());
//        entry.setEntryApppersonid(superPerson.getId());
//        entry.setEntryApppersonname(superPerson.getName());
//
//        entry.update();
//
//        EntryNo entryNo = jxCommonService.getEntryNoById(entry.getEntryNo());
//        if(entryNo.getEntrynoAppnode().equals("7")){
//            entryNo.setEntrynoAppnode("5");
//            entryNo.update();
//        }
//        try{
//            wxMsgService.sendEntryWxMsg(entry);//TODO
//        }catch (Exception e){
//            log.error("提醒领导批准修改指标微信发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
//        }
//    }

    /**
     * 上级领导/绩效经理 打回自填KPI
     *
     * @param type 1 上级领导  2 绩效经理
     * @param entryId
     * @param backReason
     * @param person
     * @return
     */
    @Before(Tx.class)
    public void backselfKpi( String entryId, String backReason,String type, Person person) {
        String wflogName = null;
        String wflogType = null;
        Entry entry = Entry.dao.findById(entryId);
        if(entry.getEntrySelfkpiweight()==null || entry.getEntrySelfkpiweight().compareTo(new BigDecimal(0))==0){
            throw new RuntimeException("自填权重为0%，不允许打回！");
        }
        //表示领导打回
        if("1".equals(type) && person.getId().equals(entry.getEntrySuperId())){
            if(!"6".equals(entry.getEntryApptype())){
                throw new RuntimeException("链接错误！请退出重试！");
            }
            wflogName = "上级领导("+person.getName() + ")打回目标填写";
            wflogType = "8";
        }else if((SessionUtil.isAdmin() || SessionUtil.isJxjl()) && "2".equals(type) ){
            if(!("6".equals(entry.getEntryApptype()) || "7".equals(entry.getEntryApptype()))){
                throw new RuntimeException("链接错误！请退出重试！");
            }
            wflogName = "绩效专员("+person.getName() + ")打回目标填写" ;
            wflogType = "5";
        }else{
            throw new RuntimeException("链接错误！请退出重试！");
        }
        wflogService.addWfLog(person,wflogName,wflogType,entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",backReason);
        //表示被打回
        entry.setEntryWfstatus("3");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntryApptype("5");
        entry.setEntryApppersonid("");
        entry.setEntryApppersonname("");
        entry.update();

        EntryNo entryNo = jxCommonService.getEntryNoById(entry.getEntryNo());
        if(entryNo.getEntrynoAppnode().equals("7")){
            entryNo.setEntrynoAppnode("5");
            entryNo.update();
        }
        try{
           // mailService.sendJxEmail(entry.getEntryId(),"1","10");
            wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRMBDH,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());
        }catch (Exception e){
            log.error("提醒员工编辑绩效指标微信发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
        }
    }


    /**
     * 获取自填KPI列表
     * @param entryid
     * type:4 表示领导审批kpi  6表示考核人填写kpi  61表示考核人申请修改   41领导审核修改
     */
    public List<Kpi> getSelfkpiList(String entryid,String nodeType,Person person) {
        String sql = null;
//        if("4".equals(nodeType)){
//            sql = "select * from ct_jx_kpi k left join  ct_jx_entry e on k.kpi_entryid = e.entry_id  where e.entry_id = ? and k.kpi_isself = ? " +
//                    " and e.entry_superid = ?  and e.entry_apptype = '6'  order by k.kpi_type, len(k.kpi_num),k.kpi_num  asc";
//        }else if ("6".equals(nodeType)){
//            sql = "select * from ct_jx_kpi k left join  ct_jx_entry e on k.kpi_entryid = e.entry_id  where e.entry_id = ? and k.kpi_isself = ? " +
//                    " and e.entry_khpersonid = ? and e.entry_apptype = '5'  order by k.kpi_type, len(k.kpi_num),k.kpi_num  asc";
//        }else{
//            throw new RuntimeException("链接错误！请退出重试！");
//        }
        if("4".equals(nodeType)){ //oracle 调整
            sql = "select * from ct_jx_kpi k left join  ct_jx_entry e on k.kpi_entryid = e.entry_id  where e.entry_id = ? and k.kpi_isself = ? " +
                    " and e.entry_superid = ?  and e.entry_apptype = '6'  order by k.kpi_type, length(k.kpi_num),k.kpi_num  asc";
        }else if ("41".equals(nodeType)){
            sql = "select * from ct_jx_kpi k left join  ct_jx_entry e on k.kpi_entryid = e.entry_id  where e.entry_id = ? and k.kpi_isself = ? " +
                    " and e.entry_superid = ?  and e.entry_apptype = '61'  order by k.kpi_type, length(k.kpi_num),k.kpi_num  asc";
        }else if ("6".equals(nodeType)){
            sql = "select * from ct_jx_kpi k left join  ct_jx_entry e on k.kpi_entryid = e.entry_id  where e.entry_id = ? and k.kpi_isself = ? " +
                    " and e.entry_khpersonid = ? and e.entry_apptype = '5'  order by k.kpi_type, length(k.kpi_num),k.kpi_num  asc";
        }else if ("61".equals(nodeType)){
            sql = "select * from ct_jx_kpi k left join  ct_jx_entry e on k.kpi_entryid = e.entry_id  where e.entry_id = ? and k.kpi_isself = ? " +
                    " and e.entry_khpersonid = ? and e.entry_apptype = '7'  order by k.kpi_type, length(k.kpi_num),k.kpi_num  asc";
        }else{
            throw new RuntimeException("链接错误！请退出重试！");
        }
        List<Kpi> kpis = Kpi.dao.find(sql, entryid, "1",person.getId());
        return kpis;
    }

    /**
     * 根据entryid获取绩效经理填写的kpi
     * @param entryid
     */
    public List<Kpi> getNoselfkpiList(String entryid) {
       // String sql = "select * from ct_jx_kpi where kpi_entryid = ? and kpi_isself = ?    order by kpi_type,len(kpi_num),kpi_num  asc  ";
        String sql = "select * from ct_jx_kpi where kpi_entryid = ? and kpi_isself = ?    order by kpi_type,length(kpi_num),kpi_num  asc  ";//oracle 调整
        return  Kpi.dao.find(sql,entryid,"2");
    }

    /**
     * 是否存在待处理事务
     * @param pid  人员Id
     * @return
     */
    public boolean isHaveToDoList(String pid) {
//        e.entry_apppersonid = ? and e.entry_apptype = '2'
//        e.entry_apptype = '1' and entry_khpersonid= ?

//        e.entry_apppersonid = ? and  e.entry_apptype = '61'
//        e.entry_apppersonid = ? and e.entry_apptype = '6'
//        e.entry_apptype = '5' and entry_khpersonid= ?
//        e.entry_superid = ? and e.entry_interviewdate is null and e.entry_apptype = '9' and entry_offline is null
        //评分人待办
        String sql =  "select count(*) count from  ct_jx_entry where entry_apptype='2' and entry_apppersonid =? ";
        DtBean bean = new DtBean().dao().findFirst(sql, pid);
        if(bean.getInt("count")>0){
            return true;
        }
        //自评待办
        sql =  "select count(*) count from  ct_jx_entry where entry_apptype='1' and entry_khpersonid =? ";
        bean = new DtBean().dao().findFirst(sql, pid);
        if(bean.getInt("count")>0){
            return true;
        }
        //上级领导审批kpi待办
        sql = "select count(*) count from ct_jx_entry e where e.entry_apppersonid = ? and (e.entry_apptype = '6' or e.entry_apptype = '61') ";
        bean = new DtBean().dao().findFirst(sql, pid);
        if(bean.getInt("count")>0){
            return true;
        }
        //考核人自填KPI
        sql  = "select  count(*) count from ct_jx_entry e where e.entry_apptype = '5' and entry_khpersonid= ?";
        bean = new DtBean().dao().findFirst(sql, pid);
        if(bean.getInt("count")>0){
            return true;
        }
        //绩效面谈
        sql  = "select  count(*) count from ct_jx_entry e where e.entry_superid = ? and e.entry_interviewdate is null and e.entry_apptype = '9' and entry_offline is null";
        bean = new DtBean().dao().findFirst(sql, pid);
        if(bean.getInt("count")>0){
            return true;
        }
//       //部门评级待办
//       sql = " select count(*)  count from ct_jx_ratingentry e "+
//             " left join  ct_jx_ratingdept d on e.ratingentry_deptid = d.ratingdept_id "+
//             " where d.ratingdept_managerid = ? and e.ratingentry_appnode = '1'";
//        bean = new DtBean().dao().findFirst(sql, pid);
//        if(bean.getInt("count")>0){
//            return true;
//        }
//       //中心评级待办
//        sql =  "select ratingdept_id from ct_jx_ratingdept where ratingdept_type = '2' and ratingdept_managerid = ? ";
//        List<DtBean> dtBeans = new DtBean().dao().find(sql, pid);
//        for(DtBean d:dtBeans){
//            if(ratingService.isAllArriveCenterNode(d.getStr("ratingdept_id"),SessionUtil.getCurrentPerson())){
//                return true;
//            }
//        }

//       //绩效评分人评分待办
//        sql = "select entryno_id from ct_jx_entryno where entryno_jxpersonid = ?";
//        dtBeans = new DtBean().dao().find(sql, pid);
//        for(DtBean d:dtBeans){
//            if(ratingService.isAllArriveJxPersonNode(d.getStr("entryno_id"),SessionUtil.getCurrentPerson())){
//                return true;
//            }
//        }
//
//       //hr领导评级待办
//        sql = "select entryno_id from ct_jx_entryno where entryno_hrmanagerid = ?";
//        dtBeans = new DtBean().dao().find(sql, pid);
//        for(DtBean d:dtBeans){
//            if(ratingService.isAllArriveHrManagerNode(d.getStr("entryno_id"),SessionUtil.getCurrentPerson())){
//                return true;
//            }
//        }
     /*   sql =  "select count(*) count from  ct_jx_entry where (entry_apptype = '4' or entry_apptype = '2')  and entry_creatorid =? ";
        bean = new DtBean().dao().findFirst(sql, pid);
        if(bean.getInt("count")>0){
            return true;
        }*/

        return false;
    }













    public SqlPara getSqlPara(Entry entry) {
        Conditions condi = new Conditions();
        condi.modelToCondition(entry);
        SqlPara sp = condi.getSqlPara();
        sp.setSql(sp.getSql() + "  order by entry_submittime desc");
        return sp;
    }




    public List<Kpi> getKpiQueryList(String entryid, Person person) {
       /* Kpi kpiWhere = new Kpi();
        kpiWhere.setKpiEntryid(entryid);
        if(person != null){
            kpiWhere.setKpiGraderid(person.getId());
        }
        return jxCommonService.getKpiByWhere(kpiWhere);*/
        if(person != null){
//            String sql =
//                    " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid in " +
//                            " (select k1.kpi_id from ct_jx_kpi k1 where k1.kpi_entryid = ? and k1.kpi_index = k.kpi_index ) " +
//                            " ) attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ? and " +
//                      " kpi_graderid = ?  order by kpi_type,len(kpi_num),kpi_num asc ";

//            String sql =
//                    " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid in " +
//                            " (select k1.kpi_id from ct_jx_kpi k1 where k1.kpi_entryid = ? and k1.kpi_index = k.kpi_index ) " +
//                            " ) attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ? and " +
//                            " kpi_graderid = ?  order by kpi_type,length(kpi_num),kpi_num asc ";//oracle 调整
            String sql =
                    " select k.*,0 attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ? and " +
                            " kpi_graderid = ?  order by kpi_type,length(kpi_num),kpi_num asc ";//oracle 调整
            return Kpi.dao.find(sql,entryid,entryid,person.getId());
        }else {
//            String sql =
//                    " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid = k.kpi_id ) attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ?  " +
//                     "  order by kpi_type,len(kpi_num),kpi_num asc ";
//            String sql =
//                    " select k.*,(select count(*) from ct_jx_attachment where attachment_kpiid = k.kpi_id ) attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ?  " +
//                            "  order by kpi_type,length(kpi_num),kpi_num asc ";//oracle 调整
            String sql =
                    " select k.*,0 attachmentCnt from ct_jx_kpi k  where  kpi_entryid = ?  " +
                            "  order by kpi_type,length(kpi_num),kpi_num asc ";//oracle 调整
            return Kpi.dao.find(sql,entryid);
        }
    }



    /**
     * 根据entryid获取考核人自填KPI列表
     * @param entryid
     */
    public List<Kpi> getSelfkpiList(String entryid) {
        //获取绩效专员填写KPI中index最大的值
       /* List<Kpi> kpiList = getNoselfkpiList(entryid);
        int maxIndex = 0;
        if(kpiList.size() > 0){
            maxIndex = kpiList.get(kpiList.size()-1).getKpiIndex();
        }*/
        //把自填的kpi中index 都减去maxIndex
//        String sql = "select * from ct_jx_kpi where kpi_entryid = ? and kpi_isself = ?    order by len(kpi_num),kpi_num  asc   ";
        String sql = "select * from ct_jx_kpi where kpi_entryid = ? and kpi_isself = ?    order by length(kpi_num),kpi_num  asc   "; //oracle 调整
        List<Kpi> kpis = Kpi.dao.find(sql, entryid, "1");
        for(Kpi k:kpis){
            k.setKpiIndex(k.getKpiIndex());
        }
        return kpis;
    }


    public List<Kpi> getBeforeKpiList(String khpersonid, String cycleId) {
        List <Kpi> result = new ArrayList<>();
        Cycle cycle = Cycle.dao.findById(cycleId);
        String sql = "select * from ct_jx_kpi k" +
                " left join ct_jx_entry e on k.kpi_entryid = e.entry_id " +
                " left join ct_jx_kpilib kl on kl.kpilib_id = k.kpi_baseid  " +
                " left join ct_jx_cycle c on c.cycle_id = e.entry_cycleid where " +
                " (e.entry_apptype ='9' or e.entry_apptype ='4')  and entry_khpersonid = ? and c.cycle_type = ? order by entry_createtime desc,kpi_type,kpi_index  ";//oracle 调整
        List<Kpi> kpis = Kpi.dao.find(sql, khpersonid, cycle.getCycleType());
        String entryId = null;
        for(Kpi k:kpis){
            if(entryId != null && !entryId.equals(k.getKpiEntryid())){
                break;
            }
            entryId = k.getKpiEntryid();
            result.add(k);
        }
        return result;
    }


    public List<KpiHist> getHistoryKpi(String entryId,int histNoIndex){

        List<KpiHistNo> kpiHistNoList = KpiHistNo.dao.find("select * from ct_jx_kpihistno where kpihistno_entryid=? order by  kpihistno_index",entryId);
        if(kpiHistNoList.size()<2){
            throw new RuntimeException("当前指标没有历史版本！");
        }
        int maxIndex = kpiHistNoList.get(kpiHistNoList.size()-2).getKpiHistNoIndex();//最新版不算进历史版本
        if(histNoIndex>maxIndex)throw new RuntimeException("没有更多版本了！");

        if(histNoIndex<=0){//默认返回最近的版本
            throw new RuntimeException("当前指标没有历史版本！");
        }
        KpiHistNo kpiHistNo  = KpiHistNo.dao.findFirst("select * from ct_jx_kpihistno where kpihistno_entryid=? and  kpihistno_index=?",entryId,histNoIndex);

        if(kpiHistNo==null)throw new RuntimeException("当前指标没有更多版本了！");
        List<KpiHist> kpiHists = KpiHist.dao.find("select * from ct_jx_kpihist where kpi_entryid=? and kpi_histnoid=? order by kpi_type,kpi_index", entryId, kpiHistNo.getKpiHistNoId());
        if(kpiHists.size()>0){
            kpiHists.get(0).put("KpiHistNoTime",kpiHistNo.getKpiHistNoTime());
        }
        return kpiHists;
    }

    public boolean existHistoryKpi(String entryId) {

        List<KpiHistNo> kpiHistNoList = KpiHistNo.dao.find("select kpihistno_entryid from ct_jx_kpihistno where kpihistno_entryid=? ", entryId);
        return kpiHistNoList.size() > 1;
    }
    public int getMaxHistNo(String entryId){
        List<KpiHistNo> kpiHistNoList = KpiHistNo.dao.find("select * from ct_jx_kpihistno where kpihistno_entryid=? order by  kpihistno_index",entryId);
        if(kpiHistNoList.size()<2){
            return -1;
        }
        return kpiHistNoList.get(kpiHistNoList.size()-2).getKpiHistNoIndex();
    }

    public DtBean getRatingPercent(String entryId){
        Entry entry = Entry.dao.findById(entryId);
        String deptId = entry.getEntryKhdeptid();
        String entryNo = entry.getEntryNo();
        Entry entryWhere = new Entry();
        entryWhere.setEntryKhdeptid(deptId);
        entryWhere.setEntryNo(entryNo);
        List<Entry> entryList = jxCommonService.getJxEntryByWhere(entryWhere);
        int count = entryList.size();
        int s_count = 0;
        int a_count = 0;
        int b_count = 0;
        int c_count = 0;
        int d_count = 0;
        for(Entry en:entryList){
            String entryRating = en.getEntryRating();
            if(StringUtils.isBlank(entryRating))continue;
            if("S".equals(entryRating))s_count++;
            if("A".equals(entryRating))a_count++;
            if("B".equals(entryRating))b_count++;
            if("C".equals(entryRating))c_count++;
            if("D".equals(entryRating))d_count++;
        }
        DtBean dtBean = new DtBean();
        setPercent(dtBean,count,"s",s_count);
        setPercent(dtBean,count,"a",a_count);
        setPercent(dtBean,count,"b",b_count);
        setPercent(dtBean,count,"c",c_count);
        setPercent(dtBean,count,"d",d_count);
        dtBean.put("deptName",entryList.get(0).getEntryKhdeptname());
        dtBean.put("deptLongName",entryList.get(0).getEntryDisplayname());
        return dtBean;
    }

    private void setPercent( DtBean dtBean,int count,String type,int typeCount){

        if(typeCount == 0){
            dtBean.put(type,"");
            dtBean.put(type+"p","");
        }else{
            dtBean.put(type,typeCount);
            dtBean.put(type+"p",Tool.getStripZeros(new BigDecimal(typeCount).multiply(new BigDecimal(100)).divide(new BigDecimal(count),2,BigDecimal.ROUND_HALF_UP)).toString()+"%");
        }

    }
    //提交绩效面谈
    @Before(Tx.class)
    public void saveInterview(Entry entry,Person person){
        String entryId = entry.getEntryId();

        String entryInterviewdate = entry.getEntryInterviewdate();
        String entryInterviewnotes = entry.getEntryInterviewnotes();
        if(StringUtils.isBlank(entryInterviewdate)){
            throw new RuntimeException("面谈日期不能为空！");
        }
        if(StringUtils.isBlank(entryInterviewnotes)){
            throw new RuntimeException("面谈结果不能为空！");
        }
        Entry e = jxCommonService.getJxentryById(entryId);


        if(!SessionUtil.getCurrentPerson().getId().equals(e.getEntrySuperId())){
            throw new RuntimeException("链接错误！请退出重试！");
        }

        e.setEntryInterviewtime(Tool.getCurrTime());
        e.setEntryInterviewpid(person.getId());
        e.setEntryInterviewdate(entryInterviewdate);
        e.setEntryInterviewnotes(entryInterviewnotes);
        e.update();
    }
    @Before(Tx.class)
    public void confirmEntry(String entryId,Person person){
        Entry entry = Entry.dao.findById(entryId);
        if(!SessionUtil.getCurrentPerson().getId().equals(entry.getEntryKhpersonid())){
            throw new RuntimeException("链接错误！请退出重试！");
        }
        if(!"9".equals(entry.getEntryApptype())){
            throw new RuntimeException("当前状态不允许确认操作，请退出重试！");
        }
        if("2".equals(entry.getEntryConfirmstatus())){
            throw new RuntimeException("您已经确认过！");
        }
        entry.setEntryConfirmstatus("2");
        entry.setEntryConfirmtime(Tool.getCurrTime());
        entry.update();
        wflogService.addWfLog(person,person.getName() + "确认指标结果","91",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"1","");
    }
    @Before(Tx.class)
    public void appealEntry(String entryId, String reason,Person person){
        Entry entry = Entry.dao.findById(entryId);
        if(!SessionUtil.getCurrentPerson().getId().equals(entry.getEntryKhpersonid())){
            throw new RuntimeException("链接错误！请退出重试！");
        }
        if(!"9".equals(entry.getEntryApptype())){
            throw new RuntimeException("当前状态不允许确认操作，请退出重试！");
        }
        if("2".equals(entry.getEntryConfirmstatus())){
            throw new RuntimeException("您已经确认过，不能进行申诉");
        }
        if("10".equals(entry.getEntryConfirmstatus()) ||"11".equals(entry.getEntryConfirmstatus())){
            throw new RuntimeException("已经申诉过，请等待处理！");
        }

        entry.setEntryConfirmstatus("10");
        entry.setEntryAppealtime(Tool.getCurrTime());
        entry.setEntryAppealreason(reason);
        entry.update();
        wflogService.addWfLog(person,person.getName() + "申诉指标结果","91",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"3",reason);
        wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRSS,entry.getEntryCreatorid(),entry.getEntryCreatorname());
    }

    public List<Entry> getConfirmEntrys(String entryNo) {
        return Entry.dao.find("select * from ct_jx_entry  where entry_apptype='9' and  entry_confirmstatus is null and entry_no=? order by entry_displayname asc",entryNo);
    }
    public List<Entry> getAppealEntrys(String entryNo) {
        return Entry.dao.find("select * from ct_jx_entry  where entry_apptype='9' and  entry_confirmstatus ='10' and entry_no=? order by entry_displayname asc",entryNo);
    }
    public List<Entry> getConfirmEntrys2(String entryNo) {
        return Entry.dao.find("select * from ct_jx_entry  where entry_apptype='9' and  entry_confirmstatus ='11' and entry_no=? order by entry_displayname asc",entryNo);
    }
}
