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.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.SessionUtil;
import com.sys.core.utils.Tool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class JxManagerService {
    static HrService hrService = Enhancer.enhance(HrService.class);
    static OrgService orgService = Enhancer.enhance(OrgService.class);
    static JxCommonService jxCommonService = Enhancer.enhance(JxCommonService.class);
    static JxCycleService jxCycleService = Enhancer.enhance(JxCycleService.class);
    static KpilibService kpilibService = Enhancer.enhance(KpilibService.class);
    static WflogService wflogService =  Enhancer.enhance(WflogService.class);
    static MailService mailService = new MailService();
    static SysCodeService codeService = new SysCodeService();
    static WxMsgService wxMsgService = new WxMsgService();
    static PersonManagerService personManagerService = Enhancer.enhance(PersonManagerService.class);
    Log log = LogFactory.getLog(this.getClass());
    /**
     * 绩效专员获取绩效管理中列表的分页数据
     * @param
     * @param person
     * @param cycleName
     * @param khOrg
     * @param isAdmin
     * @return
     */
    public PageBean getJxManagerList(Person person, int pageNumber, int pageSize, String cycleName, String khOrg, boolean isAdmin) {
        //获取人员组织权限
//        String sqlCount =
//                "select count(1) " +
//                        " from ( "+
//                        "        select *, row_number() over (partition by entry_no order by entry_cycleid,entry_khdeptid) as group_idx "+
//                        "        from ct_jx_entry "+
//                        ") s left join ct_jx_cycle b on s.entry_cycleid = b.cycle_id "+
//                        "where s.group_idx = 1 ";
//
//
//        String sqlPara =
//                "select s.*,cycle_name,cycle_quarter,cycle_yeartype,cycle_month " +
//                        " from ( "+
//                        "        select *, row_number() over (partition by entry_no order by entry_cycleid,entry_apptype,entry_submittime,entry_createtime) as group_idx "+
//                        "        from ct_jx_entry "+
//                        ") s  left join ct_jx_cycle b on s.entry_cycleid = b.cycle_id "+
//                        "where s.group_idx = 1 ";

        String sqlCount ="select count(1) from ct_jx_entryno s left join ct_jx_cycle b on s.entryno_cycleid = b.cycle_id  where 1=1 ";
        String sqlPara ="select s.*,cycle_name,cycle_quarter,cycle_yeartype,cycle_month from ct_jx_entryno s left join ct_jx_cycle b on s.entryno_cycleid = b.cycle_id  where 1=1 ";
        String whereBy = "";
        if(!StringUtils.isBlank(cycleName)){
            whereBy += "and s.entryno_cycleid = '"+cycleName+"'";
        }
        if(!StringUtils.isBlank(khOrg)){
            whereBy += " and s.entryno_orgid = '"+khOrg+"'";
        }
        if(isAdmin){//绩效管理员
        }else{//绩效专员
            List<Org> orgList = orgService.getOrgList(person.getId());
            if(orgList.size() > 0){
                String subWhere = " and s.entryno_orgid in ( ";
                for(Org org:orgList){
                    subWhere += "'" +org.getOrgId() +"',";
                }
                subWhere = subWhere.substring(0,subWhere.length()-1);
                subWhere += ")";
                whereBy += subWhere;
            }else{
                //没有任何组织授权的绩效专员  看不到任何数据
                whereBy += " and s.entryno_orgid ='192345' ";
            }

        }
        sqlCount += whereBy;
        sqlPara += whereBy;
        sqlPara += "order by entryno_createtime 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;
    }



    /**
     * 绩效专员保存人员kpi数据
     */
    @Before(Tx.class)
    public String saveJxKpis(JSONObject jsonObj) {
        JSONArray kpis = (JSONArray)jsonObj.get("kpis");
        String entryid = (String) jsonObj.get("entryid");
        String rating  = jsonObj.getString("rating");
        Entry entry = Entry.dao.findById(entryid);
//        List<Kpi> list = jxCommonService.getKpiList(entryid);
        Person currentPerson = SessionUtil.getCurrentPerson();
        BigDecimal weightSum = new BigDecimal("0");

        String entryAppType = entry.getEntryApptype();
        if(StringUtils.isNotBlank(entry.getEntryRating()) && StringUtils.isBlank(rating) && ("4".equals(entryAppType)||"9".equals(entryAppType))){
            throw new RuntimeException("评级不能为空！");
        }
        entry.setEntryRating(rating);
        //批次号
        for(int i=0; i<kpis.size(); i++){
            JSONObject json = kpis.getJSONObject(i);
            String kpiid = json.getString("kpiid");
            Kpi kpi = null;
            if(StringUtils.isBlank(kpiid)){//kpiid为空新增

            }else{//kpiid不为空，更新 用于绩效经理修改
                kpi = Kpi.dao.findById(kpiid);

                String kpiType = kpi.getKpiType();
                BigDecimal kpiWeight = json.getBigDecimal("kpiweight");
                if("0".equals(kpiType)||"1".equals(kpiType)){
                    kpi.setKpiDefine(json.getString("kpidefine"));
                    kpi.setKpiTarget(json.getString("kpitarget"));
                    kpi.setKpiWeight(kpiWeight);
                }
                kpiWeight = kpi.getKpiWeight();
                BigDecimal score =  json.getBigDecimal("kpiscore");

                if(score !=null && kpi.getKpiScore()!=null && kpi.getKpiScore().compareTo(score) !=0){
                    log.error(currentPerson.getCname()+"修改<"+entry.getEntryCyclename()+">-<"+entry.getEntryKhpersonname()+">的指标评分"+kpi.getKpiScore()+"》"+score+"，kpiId:"+kpiid);
                }
                if(!"3".equals(kpiType)){
                    kpi.setKpiZp(json.getString("kpizp"));
                    kpi.setKpiZpscore(json.getBigDecimal("zpscore"));
                }
                kpi.setKpiScore(score);
                kpi.setKpiInfo(json.getString("kpiinfo"));
                BigDecimal realScore = null;
                //绩效经理修改分数时
                if(score != null){
                    if(kpi.getKpiType().equals("3")){//附加项
                        realScore = score;
                    }else{
                        if(kpiWeight== null){
                            throw new RuntimeException(kpi.getKpiName()+">指标权重为空！");
                        }
                        realScore = score.multiply(kpiWeight).divide(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                    kpi.setKpiRealscore(realScore);
                }else{
                    kpi.setKpiRealscore(null);
                }
                if(kpiWeight!=null)weightSum = weightSum.add(kpiWeight);
                kpi.update();

            }

        }
        // 发起考核后 并且考核人已经提交自填kpi  kpi权重之和必须为100%
        if(!"0".equals(entryAppType) && !"5".equals(entryAppType)
                && weightSum.compareTo(new BigDecimal("100")) !=  0){
            throw new RuntimeException("kpi指标对应的指标权重之和应为100!现为："+weightSum);
        }else if(!"0".equals(entryAppType) && weightSum.compareTo(new BigDecimal("100")) > 0 ){
            throw new RuntimeException("kpi指标对应的指标权重之和不能大于100!现为："+weightSum);
        }
        //更新重复indexNum数据的KpiHead
        jxCommonService.resetKpiHead(entryid);
        //重新计算分数
        jxCommonService.updateJxEntryScoreAndRating(entry,rating);
        jxCommonService.updateJxEntryZpScore(entryid);

        return entryid;
    }


    /**
     * 绩效专员保存考核人员信息
     * @param jsonObj
     */
    @Before(Tx.class)
    public String saveJxEntrys(JSONObject jsonObj,Person person) {
        JSONArray khpersons = (JSONArray)jsonObj.get("khpersons");
        String kgOrgid = (String) jsonObj.get("kgOrgid");
        //String kgOrgName = hrService.getDeptById(kgOrgid).getName();
        String cycleId = (String) jsonObj.get("khcycle");
        //批次号 如果为空 创建entryno
        String entryno = (String) jsonObj.get("entryno");
        //String cycleName = jxCycleService.getCycleNameById(khcycle);
        EntryNo entryNO = null;
        if(StringUtils.isBlank(entryno)){
            entryNO =  jxCommonService.addEntryNo(cycleId,kgOrgid,person);
        }else{
            entryNO =  jxCommonService.updateEntryNo(entryno,cycleId,kgOrgid,person);
        }
        entryno = entryNO.getEntrynoId();
        String cycleName = entryNO.getEntrynoCyclename();
        String kgOrgName = entryNO.getEntrynoOrgname();
        Map<String,Person> personManagerMap = new HashMap<>();
        Map<String,Person> allEnablePerson = hrService.getAllEnablePerson().stream().collect(Collectors.toMap(Person::getId , p -> p));
        for(int i=0; i<khpersons.size(); i++){
            JSONObject json = khpersons.getJSONObject(i);
            Person khperson = hrService.getPersonById(json.getString("khpersonid"));

//            Person superPerson = hrService.getPersonById(json.getString("superPersonid"));
//            //获取考核人上级
//            try {
//                if(superPerson == null){
//                    superPerson =  hrService.getSuperPersonByPositionId(khperson.getPositionId());
//                }
//
//            }catch (Exception e){
//            }
//            if(superPerson == null){
//                throw new RuntimeException("员工:"+khperson.getName()+"获取上级失败！");
//            }
//            BigDecimal selKpiweight = json.getBigDecimal("selKpiweight");
            BigDecimal selKpiweight = new BigDecimal(100);
            String entryid = json.getString("entryid");


            String personId = khperson.getId();
            Person superPerson = null;
            if(!personManagerMap.containsKey(personId)){
                try {
                    superPerson =  personManagerService.getManager(personId,1,allEnablePerson);
                }catch (Exception ex){
                }
                if(superPerson == null){
                    throw new RuntimeException("获取员工:"+khperson.getName()+"的上级失败！");
                }
                personManagerMap.put(personId,superPerson);
            }else{
                superPerson = personManagerMap.get(personId);
            }

            if(StringUtils.isBlank(entryid)){//entryid为空新增
                Entry e = jxCommonService.isExist(khperson.getId(),cycleId,null);
                if(e!=null){
                    throw new RuntimeException("周期<"+cycleName+">下已存在员工:"+khperson.getName()+"的考核！考核组织为："+e.getEntryOrgname());
                }

                //保存绩效明细表ct_jx_entry
                Entry jxEntry = new Entry();
                jxEntry.setEntryId(Tool.uuid());
                jxEntry.setEntryCycleid(cycleId);
                jxEntry.setEntryCyclename(cycleName);
                jxEntry.setEntryKhpersonid(khperson.getId());
                jxEntry.setEntryKhpersonname(khperson.getName());
                jxEntry.setEntryKhdeptid(khperson.getDeptId());
                jxEntry.setEntryKhdeptname(khperson.getDeptName());
                jxEntry.setEntryDisplayname(khperson.getCname());
                jxEntry.setEntryKhpositionname(khperson.getPositionName());
                jxEntry.setEntryKhpositionid(khperson.getPositionId());
                jxEntry.setEntryOrgid(kgOrgid);
                jxEntry.setEntrySelfkpiweight(selKpiweight);
                jxEntry.setEntrySuperId(superPerson.getId());
                jxEntry.setEntrySuperName(superPerson.getName());

                jxEntry.setEntryOrgname(kgOrgName);
                jxEntry.setEntryApptype("0");//编辑状态
                jxEntry.setEntryWfstatus("0");//未触发
                jxEntry.setEntryNo(entryno);
                jxEntry.setEntryCreatetime(Tool.getCurrTime());
                jxEntry.setEntryCreatorid(person.getId());
                jxEntry.setEntryCreatorname(person.getName());
                jxEntry.save();
            }else{//entryid不为空，更新
                Entry e = jxCommonService.isExist(khperson.getId(),cycleId,entryno);
                if(e!=null){
                    throw new RuntimeException("周期<"+cycleName+">下已存在员工:"+khperson.getName()+"的考核！考核组织为："+e.getEntryOrgname());
                }



                Entry jxEntry = Entry.dao.findById(entryid);
                if("0".equals(jxEntry.getEntryApptype())){
                    jxEntry.setEntrySuperId(superPerson.getId());
                    jxEntry.setEntrySuperName(superPerson.getName());
                }
                jxEntry.setEntryCycleid(cycleId);
                jxEntry.setEntryCyclename(cycleName);
                jxEntry.setEntryKhpersonid(khperson.getId());
                jxEntry.setEntryKhpersonname(khperson.getName());
                jxEntry.setEntryKhdeptid(khperson.getDeptId());
                jxEntry.setEntryKhdeptname(khperson.getDeptName());
                jxEntry.setEntryDisplayname(khperson.getCname());
                jxEntry.setEntryKhpositionname(khperson.getPositionName());
                jxEntry.setEntryKhpositionid(khperson.getPositionId());

                jxEntry.setEntryOrgid(kgOrgid);
                jxEntry.setEntryOrgname(kgOrgName);
                jxEntry.setEntrySelfkpiweight(selKpiweight);
                jxEntry.update();

            }

        }
        return entryno;

    }

    /**
     * 绩效专员启动考核评分流程
     * @param jsonObj
     * @param person
     */
    @Before(Tx.class)
    public String startJxEntrysWf(JSONObject jsonObj,Person person) {
        //保存数据
        //String entryno = saveJxEntrys(jsonObj, person);
        String entryno = (String) jsonObj.get("entryno");
        EntryNo eno = EntryNo.dao.findById(entryno);
        if(StringUtils.isBlank(eno.getEntrynoZptime()) || StringUtils.isBlank(eno.getEntrynoLv1time())
                || StringUtils.isBlank(eno.getEntrynoLv2time())|| StringUtils.isBlank(eno.getEntrynoLv3time())){
            throw new RuntimeException("请先维护好流程要求完成时间！");
        }

        /**
         *
         * 1.判断所有数据中的 cycleid  考核组织ID  entryno是否都是一致的
         * 2.对应同一个考核周期(或者同一个考核周期和同一个考核组织)，每个人只有一条entry,目前写的同一个考核周期
         * 3.客观类型(且同一指标为第一位)的kpi必须要有公式
         * 4.附加项评分人一定是绩效经理？？？(需要确定？)
         */

        List<Entry> jxEntryList = jxCommonService.getJxEntryList(entryno);
        if(jxEntryList.size() == 0){
            throw new RuntimeException("没有被考核人，无法提交！");
        }
        //用来判断所有entry数据中cycleid和考核组织id是否相同
        HashSet<String> cycleidAndOrgId = new HashSet<String>();
        cycleidAndOrgId.add(jxEntryList.get(0).getEntryCycleid() + jxEntryList.get(0).getEntryOrgid());

        for(Entry e:jxEntryList){
            String entryId = e.getEntryId();
            //判断entry节点如果还在 考核人编辑KPI节点时  不允许发起评分
            if("5".equals(e.getEntryApptype())){
                throw new RuntimeException(e.getEntryKhpersonname()+"未完成绩效指标填写，无法发起评分!");
            }
            //判断考核人是否在职
            if(!hrService.isPersonInService(e.getEntryKhpersonid())){
                throw new RuntimeException("被考核人:" + e.getEntryKhpersonname() + "为不在职状态,无法发起评分!");
            }
            if(!hrService.isPersonInService(e.getEntrySuperId())){
                //throw new RuntimeException("评分人:" + e.getEntrySuperName() + "为不在职状态,无法发起评分!"); // 直接上级后面实时获取 230630
            }
            //被考核人姓名
            String khpersonname = e.getEntryKhpersonname();
            if(!cycleidAndOrgId.contains(e.getEntryCycleid() + e.getEntryOrgid())){
                throw new RuntimeException(khpersonname+"的考核数据中的考核周期或者是考核组织与其他人员考核数据不一致!");
            }

            //根据考核周期与考核人员查询entry
            Entry entryWhere = new Entry();
            entryWhere.setEntryCycleid(e.getEntryCycleid());
            entryWhere.setEntryKhpersonid(e.getEntryKhpersonid());
            List<Entry> jxEntryByWhere = jxCommonService.getJxEntryByWhere(entryWhere);
            if(jxEntryByWhere.size() > 1){
                throw new RuntimeException(khpersonname+"存在"+jxEntryByWhere.size()+"条考核数据,请核查！");
            }

            /***************kpi数据校验**********************/
            List<Kpi> kpis = jxCommonService.getKpiSimpleList(entryId);
            if(kpis.size() == 0){
                throw new RuntimeException( khpersonname +"没有具体的kpi，无法提交");
            }
            int tempKpiIndex = 0;
            //所有指标权重之和为100(除去附加项的、只计算head=1的数据)
            BigDecimal kpiWeightSum = new BigDecimal("0");
            HashSet<Integer> kpiIndexs = new HashSet<>();
            for(int i=0;i<kpis.size();i++){
                Kpi k = kpis.get(i);
                Integer kpiIndex = k.getKpiIndex();
                String kpiName = k.getKpiName();
                //String kpiDefine = k.getKpiDefine();
                BigDecimal kpiWeight = k.getKpiWeight();
                String kpiType = k.getKpiType();
                if(StringUtils.isBlank(kpiName) ||StringUtils.isBlank(kpiType)){
                    throw new RuntimeException( khpersonname + "第" + (i+1) +"条kpi信息异常!指标名称和类型不能为空！");
                }else{

                    if(kpiWeight == null){
                        throw new RuntimeException(khpersonname + "第" + (i+1) +"条kpi中<指标权重>不能为空!");
                    }

                }
                if(!kpiType.equals("3")){//不为附加项类型
                        kpiWeightSum = kpiWeightSum.add(kpiWeight);
                }

            }
            //判断指标权重的和
            if(kpiWeightSum.compareTo(new BigDecimal("100")) != 0){
                throw new RuntimeException(khpersonname + "的kpi指标对应的指标权重之和不为100!");
            }
        }

        /*********************更改流程状态***********************/
        String currTime = Tool.getCurrTime();
        for(Entry e:jxEntryList){
            String entryId = e.getEntryId();
            //更新entry中的流程状态
            e.setEntryApptype("1");
            e.setEntryWfstatus("1");
            e.setEntryAppManagerLv(0);
            e.setEntryAppname("");
            e.setEntryApptime(currTime);
            //e.setEntrySubmittime(currTime);
            e.setEntrySubmitid(person.getId());
            e.setEntrySubmitname(person.getName());
            e.setEntryApppersonid(e.getEntryKhpersonid());
            e.setEntryApppersonname(e.getEntryKhpositionname());
            e.update();
        }

        eno.setEntrynoAppnode("1");
        eno.update();
        wflogService.addWfLog(person, "绩效专员("+person.getName()+")启动考核评分","2",jxEntryList.get(0).getEntryCycleid(),null,entryno,"1","");
        jxEntryList = jxCommonService.getJxEntryList(entryno);
        for (Entry entry : jxEntryList) {
            try{
                //mailService.sendJxEmail(entry.getEntryId(),"1","30");
                wxMsgService.sendEntryWxMsg(entry, WxMsgType.GRZP,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());
            }catch (Exception e){
                log.error("提醒员工自评微信发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
            }
        }
        return entryno;
    }
    @Before(Tx.class)
    public void appealNoUpdate(String entryId,String reason){
        Entry entry = Entry.dao.findById(entryId);
        String confirmStatus = entry.getEntryConfirmstatus();
        if(!"10".equals(confirmStatus)){
            throw new RuntimeException("状态不正常，请刷新后重试！");
        }
        entry.setEntryConfirmstatus("12");
        entry.update();
        wflogService.addWfLog(SessionUtil.getCurrentPerson(), "绩效专员("+SessionUtil.getCurrentPerson().getName()+")处理申诉（无需调整）","92",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"3",reason);
    }
    @Before(Tx.class)
    public void appealUpdate(String entryId,String scoreSumAppeal,String ratingAppeal,String updateReason){
        Entry entry = Entry.dao.findById(entryId);
        String confirmStatus = entry.getEntryConfirmstatus();
        if(!"10".equals(confirmStatus)){
            throw new RuntimeException("状态不正常，请刷新后重试！");
        }
        entry.setEntryConfirmstatus("11");

        String update = "";
        BigDecimal scoreAppeal = new BigDecimal(scoreSumAppeal);
        if(entry.getEntryScore() == null){
            entry.setEntryScore(new BigDecimal(0));
        }
        if(entry.getEntryRating() == null){
            entry.setEntryRating("");
        }
        if(entry.getEntryScore().compareTo(scoreAppeal)!=0){
            update += "得分："+entry.getEntryScore()+"调整为"+scoreAppeal+";";
            entry.setEntryScore(scoreAppeal);
        }
        if(!entry.getEntryRating().equals(ratingAppeal)){
            update +="评级："+ entry.getEntryRating()+"调整为"+ratingAppeal+";";
            entry.setEntryRating(ratingAppeal);
        }
        entry.update();
        if(StringUtils.isBlank(update)){
            throw new RuntimeException("数据未调整，提交失败！");
        }
        wflogService.addWfLog(SessionUtil.getCurrentPerson(), "绩效专员("+SessionUtil.getCurrentPerson().getName()+")处理申诉,调整结果>"+update,"92",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"3",updateReason);
        wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRJGSS,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());
    }
//    /**
//     * 批量催办
//     * @param entryNo
//     * @param type  1 编辑指标  2审核指标 3自评 4评分
//     * @return
//     */
//    @Before(Tx.class)
//    public int sendWxMsg(String entryNo,String type){
//        String appType = "";
//        if("1".equals(type)){
//            appType = "5";
//        }else if("2".equals(type)){
//            appType = "6";
//        }else if("3".equals(type)){
//            appType = "1";
//        }else if("4".equals(type)){
//            appType = "2";
//        }
//        List<Entry> list = jxCommonService.getJxEntryListByType(entryNo, appType);
//        int count = 0;
////        int hour = -24;
////        SysCode sysCode = codeService.getSysCodeName("批量催办领导流程到达小时");
////        if(sysCode != null && StringUtils.isNotBlank(sysCode.getSyscodeValue())){
////            try{
////                int intValue = Integer.parseInt(sysCode.getSyscodeValue());
////                if(intValue>=0){
////                    hour = 0-intValue;
////                }
////            }catch (Exception e){
////            }
////        }
//        for (Entry entry : list) {
////            if("2".equals(type) || "4".equals(type)){
////                String entryApptime = entry.getEntryApptime();
////                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////                Calendar instance = Calendar.getInstance();
////                instance.add(Calendar.HOUR,hour);
////                Date time = instance.getTime();
////                try {
////                    Date appTime = sdf.parse(entryApptime);
////                    if(appTime.after(time)){
////                        continue;
////                    }
////                } catch (ParseException e) {
////                    log.error("时间转换失败",e);
////                    continue;
////                }
////            }
//            wxMsgService.sendEntryWxMsg(entry,type,true);
//            count++;
//        }
//        return count;
//    }
    /**
     * 绩效专员启动KPI审核
     * @param jsonObj
     * @param person
     */
    @Before(Tx.class)
    public String startJxKpisWf(JSONObject jsonObj, Person person) {
        //保存数据
        String entryno = saveJxEntrys(jsonObj, person);
        EntryNo eno = EntryNo.dao.findById(entryno);
        if(StringUtils.isBlank(eno.getEntrynoKpiapptime()) || StringUtils.isBlank(eno.getEntrynoKpitime()) ){
            throw new RuntimeException("请先维护好流程要求完成时间中的目标填报和目标审核时间！");
        }

        List<Entry> jxEntryList = jxCommonService.getJxEntryList(entryno);
        if(jxEntryList.size() == 0){
            throw new RuntimeException("没有被考核人，无法提交！");
        }
        //用来判断所有entry数据中cycleid和考核组织id是否相同
        HashSet<String> cycleidAndOrgId = new HashSet<String>();
        cycleidAndOrgId.add(jxEntryList.get(0).getEntryCycleid() + jxEntryList.get(0).getEntryOrgid());
        Map<String,Person> personManagerMap = new HashMap<>();
        Map<String,Person> allEnablePerson = hrService.getAllEnablePerson().stream().collect(Collectors.toMap(Person::getId , p -> p));

        for(Entry e:jxEntryList){
            String entryId = e.getEntryId();
            String personId = e.getEntryKhpersonid();
            //被考核人姓名
            String khpersonname = e.getEntryKhpersonname();
            if(!cycleidAndOrgId.contains(e.getEntryCycleid() + e.getEntryOrgid())){
                throw new RuntimeException(khpersonname+"的考核数据中的考核周期或者是考核组织与其他人员考核数据不一致!");
            }

            //根据考核周期与考核人员查询entry
            Entry entryWhere = new Entry();
            entryWhere.setEntryCycleid(e.getEntryCycleid());
            entryWhere.setEntryKhpersonid(e.getEntryKhpersonid());
            List<Entry> jxEntryByWhere = jxCommonService.getJxEntryByWhere(entryWhere);
            if(jxEntryByWhere.size() > 1){
                throw new RuntimeException(khpersonname+"存在"+jxEntryByWhere.size()+"条考核数据,请核查！");
            }
            //获取考核人上级

            if(!personManagerMap.containsKey(personId)){
                Person superPerson = null;
                try {
                    superPerson = personManagerService.getManager(personId,1,allEnablePerson);
                }catch (Exception ex){
                }
                if(superPerson == null){
                    throw new RuntimeException("获取员工:"+e.getEntryKhpersonname()+"的上级失败！");
                }
                personManagerMap.put(personId,superPerson);
            }

        }
       //jxCommonService.initKpi(jxEntryList);//根据模板生成指标数据

        /*********************更改流程状态***********************/
        String currTime = Tool.getCurrTime();
        String nextEntrynoNode = "7";
        for(Entry e:jxEntryList){
            String entryId = e.getEntryId();
            String personId = e.getEntryKhpersonid();
            Person superManager = personManagerMap.get(personId);
            BigDecimal selfkpiweight = e.getEntrySelfkpiweight();
            //只有当自填比例大于0时  节点流程到自填kpi节点  其余直接到绩效专员审批kpi节点
            if(selfkpiweight != null && selfkpiweight.compareTo(new BigDecimal(0)) == 1){
                e.setEntryApptype("5"); //自填kpi节点
                nextEntrynoNode ="5";
            }else{
                e.setEntryApptype("7"); //绩效专员审批kpi
            }
            e.setEntrySuperId(superManager.getId());
            e.setEntrySuperName(superManager.getName());
            e.setEntryWfstatus("1");
            e.setEntryAppname("");
            e.setEntryApptime(currTime);
            e.setEntrySubmittime(currTime);
            e.setEntrySubmitid(person.getId());
            e.setEntrySubmitname(person.getName());
            e.setEntryApppersonid(e.getEntryKhpersonid());
            e.setEntryApppersonname(e.getEntryKhpositionname());
            e.update();

        }

        eno.setEntrynoAppnode(nextEntrynoNode);
        eno.update();
        wflogService.addWfLog(person,"绩效专员("+person.getName()+")启动考核" ,"1",jxEntryList.get(0).getEntryCycleid(),null,entryno,"1","");

        jxEntryList = jxCommonService.getJxEntryList(entryno);
        for (Entry entry : jxEntryList) {
            try{
                if(!"5".equals(entry.getEntryApptype()))continue;
                //mailService.sendJxEmail(entry.getEntryId(),"1","10");
                //wxMsgService.sendWxMsg(entry.getEntryId(),"1",entry.getEntryKhpersonid(),"1");
                wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRMB,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());
            }catch (Exception e){
                log.error("提醒员工编辑绩效指标微信发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
            }
        }

        return entryno;
    }



    /**
     * 绩效经理根据entryId单个确认人员考核结果
     * @param entryId
     */
    @Before(Tx.class)
    public void confirmJxEntry(String entryId) {
        Entry entry = jxCommonService.getJxentryById(entryId);
        if(!"4".equals(entry.getEntryApptype())){
            throw new RuntimeException("考核不在待确认状态，请刷新页面重试!");
        }
        //Object[] managerAndLv = personManagerService.getManagerAndLv(entry.getEntryKhpersonid(), 1);
        Person khperson = hrService.getPersonById(entry.getEntryKhpersonid());
        Person superManager = personManagerService.getManager(entry.getEntryKhpersonid(),1);
        String superId = null;
        String superName = null;
        if(superManager != null  ){
            superId = superManager.getId();
            superName = superManager.getName();
        }
        String deptId = entry.getEntryKhdeptid();
        String deptName = entry.getEntryKhdeptname();
        String displayName = entry.getEntryDisplayname();
        if(StringUtils.isNotBlank(khperson.getDeptId())){
            deptId = khperson.getDeptId();
            deptName = khperson.getDeptName();
            displayName = khperson.getCname();
        }

        String sql = "update ct_jx_entry set entry_apptype=?,entry_wfstatus=?,entry_appname=?,entry_apptime=?,entry_apppersonid=?,entry_apppersonname=? ,entry_superid=?,entry_supername=?,entry_khdeptid=?,entry_khdeptname=?,entry_displayname=? where entry_Id = ?";
        Db.update(sql,"9","9","",Tool.getCurrTime(),"","",superId,superName,deptId,deptName,displayName,entryId);
        Person person = SessionUtil.getCurrentPerson();

        if(jxCommonService.isAllEntryStatus(entry.getEntryNo(),"9")){
            EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
            eno.setEntrynoAppnode("9");
            eno.update();
        }

        wflogService.addWfLog(person,"绩效专员("+person.getName()+")确认" ,"9",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"1","");

        wxMsgService.sendEntryWxMsg(entry,WxMsgType.JXMT,superId,superName);
        wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRJG,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());


    }

    /**
     * 绩效经理根据entryno批量确认人员考核结果
     * @param entryno
     */
    @Before(Tx.class)
    public void confirmJxEntrys(String entryno) {
        List<Entry> list = Entry.dao.find("select * from ct_jx_entry where entry_no = ? and entry_apptype<>'9'", entryno);
       // String sql = "update ct_jx_entry set entry_apptype=?,entry_wfstatus=?,entry_appname=?,entry_apptime=?,entry_apppersonid=?,entry_apppersonname=? where entry_no = ?";
       // Db.update(sql,"9","9","",Tool.getCurrTime(),"","",entryno);
//        Entry entryWhere = new Entry();
//        entryWhere.setEntryNo(entryno);
//        List<Entry> jxEntryList = jxCommonService.getJxEntryByWhere(entryWhere);
        Map<String,Person> allEnablePerson = hrService.getAllEnablePerson().stream().collect(Collectors.toMap(Person::getId , p -> p));

        //Map<String,Person> dept2ManagerId = new HashMap<>();
        for(Entry entry : list){
            String entryId = entry.getEntryId();
            Person khperson = hrService.getPersonById(entry.getEntryKhpersonid());
            String deptId = entry.getEntryKhdeptid();
            String deptName = entry.getEntryKhdeptname();
            String displayName = entry.getEntryDisplayname();
            if(StringUtils.isNotBlank(khperson.getDeptId())){
                deptId = khperson.getDeptId();
                deptName = khperson.getDeptName();
                displayName = khperson.getCname();
            }
            String superId = null;
            String superName = null;

            Person superManager = personManagerService.getManager(entry.getEntryKhpersonid(),1,allEnablePerson);
            if(superManager != null){
                superId = superManager.getId();
                superName = superManager.getName();
            }


            //需要上级填写面谈，重新刷新上级
            String sql = "update ct_jx_entry set entry_superid=?,entry_supername=?,entry_apptype=?,entry_wfstatus=?,entry_appname=?,entry_apptime=?,entry_apppersonid=?,entry_apppersonname=?,entry_khdeptid=?,entry_khdeptname=?,entry_displayname=? where entry_Id = ?";
            Db.update(sql,superId,superName,"9","9","",Tool.getCurrTime(),"","",deptId,deptName,displayName,entryId);

            wxMsgService.sendEntryWxMsg(entry,WxMsgType.JXMT,superId,superName);
            wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRJG,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());
        }
        EntryNo eno = jxCommonService.getEntryNoById(entryno);
        eno.setEntrynoAppnode("9");
        eno.update();
        Person person = SessionUtil.getCurrentPerson();
        wflogService.addWfLog(person,"绩效专员("+person.getName()+")确认完成" ,"9",list.get(0).getEntryCycleid(),null,entryno,"1","");

    }

    /**
     * 绩效经理打回到评分人
     * @param entryid
     * @param person
     */
    @Before(Tx.class)
    public String backGradingResult(String entryid,String backReason, Person person) {
//        //更新kpi
//        Kpi kpi = Kpi.dao.findById(kpiid);
//        kpi.setKpiWf("1");
//        kpi.setKpiWfstatus("3");
//        kpi.update();
        //更新entryid
//        String entryid = kpi.getKpiEntryid();
        Entry entry = Entry.dao.findById(entryid);
        entry.setEntryApptype("2");//打分人审核 状态
        entry.setEntryWfstatus("3");
        entry.setEntryScore(null);//清空得分 只有所有的kpi都到了绩效节点才算score
        entry.update();

        EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
        if("2".equals(eno.getEntrynoAppnode())){
            eno.setEntrynoAppnode("1");
            eno.update();
        }
        //日志
        wflogService.addWfLog(person,"绩效专员("+person.getName()+")打回考核评分","6",entry.getEntryCycleid(),entryid,entry.getEntryNo(),"2",backReason);
        return entryid;

    }
    //调整评分数据
    @Before(Tx.class)
    public void modifyEntry(Entry entry,String reason,Person person){
        String entryId = entry.getEntryId();

        BigDecimal scoreAppeal = entry.getEntryScore();
        String ratingAppeal = entry.getEntryRating();
        if(StringUtils.isBlank(ratingAppeal)){
            throw new RuntimeException("调整评级不能为空！");
        }
        if(scoreAppeal == null){
            throw new RuntimeException("调整评分不能为空！");
        }
        Entry oldEntry = jxCommonService.getJxentryById(entryId);
        String update = "";
        if(oldEntry.getEntryScore() == null){
            oldEntry.setEntryScore(new BigDecimal(0));
        }
        if(oldEntry.getEntryRating() == null){
            oldEntry.setEntryRating("");
        }
        if(oldEntry.getEntryScore().compareTo(scoreAppeal)!=0){
            update += "得分："+oldEntry.getEntryScore()+"调整为"+scoreAppeal+";";
            oldEntry.setEntryScore(scoreAppeal);
        }
        if(!oldEntry.getEntryRating().equals(ratingAppeal)){
            update +="评级："+ oldEntry.getEntryRating()+"调整为"+ratingAppeal+";";
            oldEntry.setEntryRating(ratingAppeal);
        }
        entry.update();
        if(StringUtils.isBlank(update)){
            throw new RuntimeException("数据未调整，提交失败！");
        }

        wflogService.addWfLog(SessionUtil.getCurrentPerson(), "绩效专员("+person.getName()+")调整结果>"+update,"92",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"3",reason);

    }
    @Before(Tx.class)
    public void saveAppTime(EntryNo entryNo,Person person){
        String entryNoId = entryNo.getEntrynoId();

        String entrynoKpitime = entryNo.getEntrynoKpitime();
        String entrynoKpiapptime = entryNo.getEntrynoKpiapptime();
        String entrynoZptime = entryNo.getEntrynoZptime();
        String entrynoLv1time = entryNo.getEntrynoLv1time();
        String entrynoLv2time = entryNo.getEntrynoLv2time();
        String entrynoLv3time = entryNo.getEntrynoLv3time();
        String interviewtime = entryNo.getEntrynoInterviewtime();


        EntryNo oldEntryNo = jxCommonService.getEntryNoById(entryNoId);
        if("0".equals(oldEntryNo.getEntrynoAppnode()) && (StringUtils.isBlank(entrynoKpitime) || StringUtils.isBlank(entrynoKpiapptime))){
            throw new RuntimeException("时间不能为空！");
        }
        oldEntryNo.setEntrynoKpitime(entrynoKpitime);
        oldEntryNo.setEntrynoKpiapptime(entrynoKpiapptime);
        oldEntryNo.setEntrynoZptime(entrynoZptime);
        oldEntryNo.setEntrynoLv1time(entrynoLv1time);
        oldEntryNo.setEntrynoLv2time(entrynoLv2time);
        oldEntryNo.setEntrynoLv3time(entrynoLv3time);
        oldEntryNo.setEntrynoInterviewtime(interviewtime);
        oldEntryNo.update();

    }


//    /**
//     * 绩效经理打回到自评
//     * @param entryid
//     * @param person
//     */
//    @Before(Tx.class)
//    public String backSelf(String entryid,String backReason, Person person) {
//
//        String appType = "1";//自评
//
//
//        //更新entryid
//       // String entryid = kpi.getKpiEntryid();
//        Entry entry = Entry.dao.findById(entryid);
//        entry.setEntryApptype(appType);//
//        entry.setEntryScore(null);//清空得分 只有所有的kpi都到了绩效节点才算score
//        entry.update();
//        //日志
//        wflogService.addWfLog(person,"绩效专员("+person.getName()+")打回自评","6",entry.getEntryCycleid(),entryid,entry.getEntryNo(),"2",backReason);
//        try{
//            mailService.sendJxEmail(entryid,"1","30");
//        }catch (Exception e){
//            log.error("提醒员工自评邮件发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
//        }
//        return entryid;
//    }
    /**
     * 绩效经理打回到自评
     * @param entryId
     * @param person
     */
    @Before(Tx.class)
    public String backSelfEntry(String entryId,String backReason, Person person) {
        Entry entry = Entry.dao.findById(entryId);
        if(!"2".equals(entry.getEntryApptype()) && !"4".equals(entry.getEntryApptype())){
            throw new RuntimeException("状态不匹配，请刷新后重试！");
        }
        entry.setEntryApptype("1");//
        entry.setEntryWfstatus("3");
        entry.setEntryScore(null);//清空得分
        entry.setEntryRating(null);
        entry.update();

        String sql = "update ct_jx_kpi set kpi_score=null,kpi_realscore=null where kpi_entryid = ?";
        Db.update(sql,entryId);
        //日志
        wflogService.addWfLog(person,"绩效专员("+person.getName()+")打回自评","6",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",backReason);
        try{
           // mailService.sendJxEmail(entryId,"1","30");
           // wxMsgService.sendWxMsg(entry.getEntryId(),"1",entry.getEntryKhpersonid(),"3");
            wxMsgService.sendEntryWxMsg(entry,WxMsgType.GRZPDH,entry.getEntryKhpersonid(),entry.getEntryKhpersonname());
        }catch (Exception e){
            log.error("提醒员工自评微信消息发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
        }
        EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
        if("2".equals(eno.getEntrynoAppnode())){
            eno.setEntrynoAppnode("1");
            eno.update();
        }
        return entryId;
    }
//    /**
//     * 绩效经理打回到评分
//     * @param entryId
//     * @param person
//     */
//    @Before(Tx.class)
//    public String backScoreEntry(String entryId,String backReason, Person person) {
//        Entry entry = Entry.dao.findById(entryId);
//        entry.setEntryApptype("2");//
//        entry.setEntryWfstatus("3");
//        entry.update();
//
//        EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
//        if("2".equals(eno.getEntrynoAppnode())){
//            eno.setEntrynoAppnode("1");
//            eno.update();
//        }
//        //日志
//        wflogService.addWfLog(person,"绩效专员("+person.getName()+")退回到领导评分","6",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",backReason);
//        try{
//            //wxMsgService.sendWxMsg(entry.getEntryId(),"1",entry.getEntrySuperId(),"4");
//            wxMsgService.sendEntryWxMsg(entry);
//        }catch (Exception e){
//            log.error("提醒评分微信消息发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
//        }
//        return entryId;
//    }
    /**
     * 绩效经理指定层级评分
     * @param entryId
     * @param backReason
     * @param level
     * @param person
     */
    @Before(Tx.class)
    public String toLevelScoreEntry(String entryId,String backReason,int level, Person person) {
        Entry entry = Entry.dao.findById(entryId);
        if(!"2".equals(entry.getEntryApptype())&& !"4".equals(entry.getEntryApptype())){
            throw new RuntimeException("状态不匹配，请刷新后重试！");
        }
        if(level<1 ||level>3){
            throw new RuntimeException("调整层级参数异常，请刷新后重试！");
        }
        String oldSuperId = entry.getEntryApppersonid();
        Integer oldLevel = entry.getEntryAppManagerLv();

       // String managerName = getManagerName(level);
        Object[] managerAndLv = personManagerService.getManagerAndLv(entry.getEntryKhpersonid(), level);


        if(managerAndLv==null || managerAndLv.length!=2 || managerAndLv[0]==null){
            throw new RuntimeException("上级获取失败！");
        }
        Person superPerson = (Person)managerAndLv[0];
        String nextManagerName = getManagerName((Integer) managerAndLv[1]);
        entry.setEntryAppManagerLv((Integer) managerAndLv[1]);
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntryApppersonname(superPerson.getName());
        entry.setEntryApppersonid(superPerson.getId());
        if("2".equals(entry.getEntryApptype()) && oldSuperId !=null && oldLevel!=null && oldSuperId.equals(entry.getEntryApppersonid()) && oldLevel == (Integer) managerAndLv[1]){
            throw new RuntimeException("上级未变化："+nextManagerName+"-"+superPerson.getName()+"，调整失败！");
        }
            //日志
        wflogService.addWfLog(person,"绩效专员("+person.getName()+")调整上级评分，待"+nextManagerName+superPerson.getName()+"评分","6",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",backReason);
        try{
            wxMsgService.sendEntryWxMsg(entry,WxMsgType.LDPF,superPerson);
        }catch (Exception e){
            log.error("提醒评分微信消息发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
        }
        entry.setEntryApptype("2");//
        entry.setEntryWfstatus("3");
//        if((Integer) managerAndLv[1]>level){//出现上级为同一个人情况
//            entry.setEntryRatinglv(null,level);
//            entry.setEntryScorelv(null,level);
//            if((Integer) managerAndLv[1] == level+2){//高2级的情况
//                entry.setEntryRatinglv(null,level+1);
//                entry.setEntryScorelv(null,level+1);
//            }
//        }
        entry.update();

        EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
        if("2".equals(eno.getEntrynoAppnode())){
            eno.setEntrynoAppnode("1");
            eno.update();
        }

        return entryId;
    }
    /**
     * 绩效经理自评跳评分
     * @param entryId
     * @param person
     */
    @Before(Tx.class)
    public String toScoreEntry(String entryId,String backReason, Person person) {
        Entry entry = Entry.dao.findById(entryId);
        if(!"1".equals(entry.getEntryApptype()) ){
            throw new RuntimeException("状态不匹配，请刷新后重试！");
        }
        entry.setEntryApptype("2");//
        //更新上级领导
        //获取考核人上级
        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("2");//跳转
        entry.setEntryAppname("评分");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntrySuperId(superPerson.getId());
        entry.setEntrySuperName(superPerson.getName());
        entry.setEntryApppersonname(entry.getEntrySuperName());
        entry.setEntryApppersonid(entry.getEntrySuperId());
        entry.update();

        EntryNo eno = EntryNo.dao.findById(entry.getEntryNo());
        if("2".equals(eno.getEntrynoAppnode())){
            eno.setEntrynoAppnode("1");
            eno.update();
        }
        //日志
        wflogService.addWfLog(person,"绩效专员("+person.getName()+")跳转到"+getManagerName(lv)+superPerson.getName()+"评分","6",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"2",backReason);
        try{
            //wxMsgService.sendWxMsg(entry.getEntryId(),"1",entry.getEntrySuperId(),"4");
            wxMsgService.sendEntryWxMsg(entry,WxMsgType.LDPF,superPerson);
        }catch (Exception e){
            log.error("提醒评分微信消息发送失败："+e.getMessage()+",员工："+entry.getEntryKhpersonname());
        }
        return entryId;
    }

    /**
     * 根据entryid离职处理
     *
     * @param entryid
     */
    @Before(Tx.class)
    public void quitJxEntry(String entryid,Person person) {

        Entry entry = Entry.dao.findById(entryid);
        String entryNo = entry.getEntryNo();
        String entryApptype = entry.getEntryApptype();

        if("1".equals(entryApptype) || "2".equals(entryApptype) ){

        }else{
            throw new RuntimeException("被考核人考核状态不允许离职处理！");

        }

        Kpi kpiWhere = new Kpi();
        kpiWhere.setKpiEntryid(entryid);
        //计算最后得分
        BigDecimal score = new BigDecimal("0");
        List<Kpi> kpiByWhere = jxCommonService.getKpiByWhere(kpiWhere);
        for(Kpi k:kpiByWhere){
            k.setKpiScore(new BigDecimal(0));
            k.setKpiRealscore(new BigDecimal(0));
            // k.setKpiInfo("离职处理>"+person.getName()+"    "+ LocalDateTime.now());
            k.update();
        }

        if(!"0".equals(entryApptype)){
            wflogService.addWfLog(person, "绩效专员("+person.getName()+")进行离职处理","9",entry.getEntryCycleid(),entry.getEntryId(),entry.getEntryNo(),"1","");
        }
        // entry.delete();
        entry.setEntryApptype("4");//节点类型绩效经理
        entry.setEntryWfstatus("5");
        entry.setEntryAppname("");
        entry.setEntryApptime(Tool.getCurrTime());
        entry.setEntryApppersonname("");
        entry.setEntryApppersonid("");
        entry.setEntryScore(new BigDecimal(0));
        entry.setEntryRating(null);
        entry.update();

        if(jxCommonService.isAllEntryStatus(entryNo,"4","9")){
            EntryNo eno = EntryNo.dao.findById(entryNo);
            eno.setEntrynoAppnode("2");
            eno.update();
        }

    }

    @Before(Tx.class)
    public void refreshManager(String entryId,Person person) {

        Entry jxEntry = Entry.dao.findById(entryId);
        String entryNo = jxEntry.getEntryNo();
        String entryApptype = jxEntry.getEntryApptype();
        if("6".equals(entryApptype) || "61".equals(entryApptype) || "2".equals(entryApptype) ||("9".equals(entryApptype) && StringUtils.isBlank(jxEntry.getEntryInterviewdate()))){
        }else{
            throw new RuntimeException("当前状态不需要刷新上级！");
        }
        int  toLv = 0;
        if("6".equals(entryApptype) || "61".equals(entryApptype) || "9".equals(entryApptype)){
            toLv = 1;
        }else{
            toLv = jxEntry.getEntryAppManagerLv();
            if(toLv<1)toLv=1;
        }
        //更新上级领导
        //获取考核人上级
        Person khperson = hrService.getPersonById(jxEntry.getEntryKhpersonid());
        Object[] managerAndLv = personManagerService.getManagerAndLv(jxEntry.getEntryKhpersonid(),  toLv);
        if(managerAndLv == null || managerAndLv[0] ==null ){
            if(toLv==1)throw new RuntimeException("获取员工:"+jxEntry.getEntryKhpersonname()+"的上级失败！");
            if(toLv>1)throw new RuntimeException("获取员工:"+jxEntry.getEntryKhpersonname()+"的第"+toLv+"层上级失败！");
        }
        Person superPerson = (Person)managerAndLv[0];
        Integer lv = (Integer)managerAndLv[1];
        if("9".equals(entryApptype) ) {
            if(superPerson.getId().equals(jxEntry.getEntrySuperId())){
                throw new RuntimeException("上级领导未变更，依然是："+superPerson.getName());
            }
        }else {
            if(superPerson.getId().equals(jxEntry.getEntryApppersonid())){
                throw new RuntimeException("上级领导未变更，依然是："+superPerson.getName());
            }
        }

        //更新 ct_jx_entry 中流程节点为  领导审批kpi
        jxEntry.setEntryAppManagerLv(lv);
        //设置这个的原因 当被打回时  wfstatus会变成3  再次提交的时候 需要把wfstatus设置为1
        jxEntry.setEntryWfstatus("1");
        jxEntry.setEntryApptime(Tool.getCurrTime());
        if("6".equals(entryApptype) || "61".equals(entryApptype)|| "9".equals(entryApptype) ) {
            jxEntry.setEntrySuperName(superPerson.getName());
            jxEntry.setEntrySuperId(superPerson.getId());
        }
        jxEntry.setEntryApppersonid(superPerson.getId());
        jxEntry.setEntryApppersonname(superPerson.getName());
        jxEntry.setEntryKpitime(Tool.getCurrTime());
        if(StringUtils.isNotBlank(khperson.getDeptId())){
            jxEntry.setEntryDisplayname(khperson.getCname());
            jxEntry.setEntryKhdeptname(khperson.getDeptName());
            jxEntry.setEntryKhdeptid(khperson.getDeptId());
        }
        jxEntry.update();

        wflogService.addWfLog(person, "绩效专员("+person.getName()+")刷新审核人至："+superPerson.getName(),"9",jxEntry.getEntryCycleid(),jxEntry.getEntryId(),jxEntry.getEntryNo(),"1","");

        if("6".equals(entryApptype) ) {
            wxMsgService.sendEntryWxMsg(jxEntry, WxMsgType.GRMB, superPerson);
        }
        if("61".equals(entryApptype) ) {
            wxMsgService.sendEntryWxMsg(jxEntry,WxMsgType.SJSHGRXG,superPerson);
        }
        if("9".equals(entryApptype) && StringUtils.isBlank(jxEntry.getEntryInterviewdate()) ) {
            wxMsgService.sendEntryWxMsg(jxEntry,WxMsgType.JXMT,superPerson);
        }
        if("2".equals(entryApptype) ) {
            wxMsgService.sendEntryWxMsg(jxEntry,WxMsgType.LDPF,superPerson);
        }

    }

    /**
     * 根据entryno批量删除考核人员信息
     */
    @Before(Tx.class)
    public void delJxEntrysByEntryNo(String entryNo,boolean admin,Person person) {
        EntryNo entryno = jxCommonService.getEntryNoById(entryNo);

        if(!admin) {
            String orgid = entryno.getEntrynoOrgid();
            Org org = orgService.getOrgById(orgid);
            String code = org.getOrgType() + "管理员";
            SysCode sysCode = codeService.getSysCodeName(code);
            if (sysCode != null && person.getId().equals(sysCode.getSyscodeValue())) {
                admin = true;
            }
        }
        if (!"2".equals(entryno.getEntrynoOnline()) && !admin && !entryno.getEntrynoAppnode().equals("0") ) {//非线下考核 发起后只能管理员删除
            throw new RuntimeException("考核不是编辑状态，仅管理员才能执行删除操作！");
        }
        List<Entry> jxEntryList = jxCommonService.getJxEntryList(entryNo);
        for (Entry entry : jxEntryList) {
            jxCommonService.delJxEntry(entry.getEntryId(),person);
            // ratingService.delRatingEntry(entry.getEntryId());
        }
        wflogService.addWfLog(person, "("+person.getName()+")删除考核信息","9",entryno.getEntrynoCycleid(),null,entryNo,"",entryno.getEntrynoCyclename()+","+entryno.getEntrynoOrgname()+",流程节点类型："+entryno.getEntrynoAppnode()+",共计"+jxEntryList.size()+"条考核记录！");
        entryno.delete();

    }
    /**
     * 绩效专员复制考核数据
     * @param entryno
     * @param khcycle
     * @param person
     */
    @Before(Tx.class)
    public void copyJxEntrys(String entryno, String khcycle, Person person) {
        if(StringUtils.isBlank(entryno) || StringUtils.isBlank(khcycle)){
            throw new RuntimeException("考核周期或者entryno为空!");
        }
        //根据所有entryno获取所有的entry
        Entry entryWhere = new Entry();
        entryWhere.setEntryNo(entryno);
        List<Entry> jxEntryByWhere = jxCommonService.getJxEntryByWhere(entryWhere);
        //获取新的entryno
        String newEntryno = Tool.uuid();
        String cycleName =jxCycleService.getCycleNameById(khcycle);
        for(Entry entry:jxEntryByWhere){
            Entry e = jxCommonService.isExist(entry.getEntryKhpersonid(),khcycle,null);
            if(e!=null){
                throw new RuntimeException("周期<"+cycleName+">下已存在员工:"+entry.getEntryKhpersonname()+"的考核！考核组织为："+e.getEntryOrgname());
            }
            String newEntryid = Tool.uuid();
            String oldEntryid = entry.getEntryId();
            /**********保存entry*************/
            entry.setEntryId(newEntryid);
            entry.setEntryCycleid(khcycle);
            entry.setEntryCyclename(cycleName);
            entry.setEntryApptype("0");//编辑状态
            entry.setEntryWfstatus("0");//未触发
            entry.setEntryApptime("");
            entry.setEntryApppersonname("");
            entry.setEntryApppersonid("");
            entry.setEntryScore(null);
            entry.setEntryNo(newEntryno);
            entry.setEntryCreatetime(Tool.getCurrTime());
            entry.save();
            /****************************/

            //根据entryid获取所有的kpi
            Kpi kpiWhere = new Kpi();
            kpiWhere.setKpiEntryid(oldEntryid);
            List<Kpi> kpiByWhere = jxCommonService.getKpiByWhere(kpiWhere);
            for(Kpi kpi:kpiByWhere){
                String newKpiid = Tool.uuid();
                String oldKpiid= kpi.getKpiId();
                /**********保存kpi*************/
                kpi.setKpiId(newKpiid);
                kpi.setKpiEntryid(newEntryid);
                kpi.setKpiIsSelf("2");
                kpi.setKpiScore(null);
                kpi.setKpiRealscore(null);
                kpi.setKpiValue(null);
                kpi.setKpiZp("");
                kpi.setKpiInfo("");
                kpi.save();
                /*******************************/

            }
        }


    }


    public PageBean getJxAllEntryQueryList(Person person, int pageNumber, int pageSize, String cycleName, String khOrg,String khPerson, Boolean isAdmin) {
        //获取人员组织权限
        String sqlCount =
                "select count(1) from ct_jx_entry s where 1=1 ";
//        String sqlPara =
//                "select s.*,(select count(*) from ct_jx_attachment where attachment_entryfeedback =entry_id) attachmentCnt from ct_jx_entry  s  where 1=1 ";
        String sqlPara =
                "select s.*,0 attachmentCnt from ct_jx_entry  s  where 1=1 ";
        String whereBy = "";
        if(!StringUtils.isBlank(cycleName)){
            whereBy += "and s.entry_cycleid = '"+cycleName+"'";
        }
        if(!StringUtils.isBlank(khOrg)){
            whereBy += " and s.entry_orgid = '"+khOrg+"'";
        }
        if(!StringUtils.isBlank(khPerson)){
            whereBy += " and s.entry_khpersonname like '%"+khPerson+"%'";
        }

        if(isAdmin){//绩效管理员
        }else{//绩效专员
            List<Org> orgList = orgService.getOrgList(person.getId());
            if(orgList.size() > 0){
                String subWhere = " and s.entry_orgid in ( ";
                for(Org org:orgList){
                    subWhere += "'" +org.getOrgId() +"',";
                }
                subWhere = subWhere.substring(0,subWhere.length()-1);
                subWhere += ")";
                whereBy += subWhere;
            }else{
                //没有任何组织授权的绩效专员  看不到任何数据
                whereBy += " s.entry_orgid is null ";
            }

        }
        sqlCount += whereBy;
        sqlPara += whereBy;
        sqlPara += " order by entry_createtime desc ,entry_khpersonname ";
        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;
    }
    @Before(Tx.class)
    public void updateSuperPerson(String entryId, String superPersonId,String superPersonName) {
        Entry entry = jxCommonService.getJxentryById(entryId);
        if(superPersonId.equals(entry.getEntrySuperId())){
            return;
        }
        Db.update("update ct_jx_entry set entry_superid =?,  entry_supername = ?,entry_apptime=? where entry_id = ?",superPersonId,superPersonName,Tool.getCurrTime(),entryId);

        String type = entry.getEntryApptype();
        if("2".equals(type) || "6".equals(type)){
            Person person = SessionUtil.getCurrentPerson();
            wflogService.addWfLog(SessionUtil.getCurrentPerson(),"绩效专员("+person.getName()+")调整上级审批至："+superPersonName,"0",entry.getEntryCycleid(),entryId,entry.getEntryNo(),"1","");
            if("2".equals(type)){
                wxMsgService.sendEntryWxMsg(entry,WxMsgType.LDPF,superPersonId,superPersonName);
            }else{
                wxMsgService.sendEntryWxMsg(entry,WxMsgType.SJSH,superPersonId,superPersonName);
            }

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

}
