package com.kingdee.eas.custom.expandassess.hadler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.sql.ParserException;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.attachment.AttachmentFactory;
import com.kingdee.eas.base.attachment.AttachmentInfo;
import com.kingdee.eas.base.attachment.IAttachment;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.expandassess.*;
import com.kingdee.eas.custom.expandassess.app.AssessRatingEnum;
import com.kingdee.eas.custom.expandassess.app.ExpandStatusEunm;
import com.kingdee.eas.custom.expandassess.service.impl.ExpandAssessServiceImpl;
import com.kingdee.eas.custom.projectbonus.web.vo.*;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.hr.ats.AtsUtil;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.base.syssetting.web.util.MD5Util;
import com.kingdee.util.StringUtils;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.*;

/**
 * @author qingwu
 * @date 2024/5/16
 * @apiNote 拓展人员考核负责人维护
 */
public class ExpandAssessFZRDynamicListHandler extends DynamicListHandlerEx {
    ExpandAssessServiceImpl expandAssessService = new ExpandAssessServiceImpl();
    private Context ctx = SHRContext.getInstance().getContext();

    /**
     * 校验评级和复核评级是否为空
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws ShrWebBizException
     */
    public void verifyIsEmptyAction(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap modelMap) throws BOSException, ShrWebBizException {
        String idArray = request.getParameter("idArray");
        if (StringUtils.isEmpty(idArray)) {
            throw new ShrWebBizException("勾选数据无效，请联系管理员！");
        }
        try {
            IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
            FilterInfo filterInfo = new FilterInfo();
            filterInfo.getFilterItems().add(new FilterItemInfo("id", AtsUtil.toSet(idArray), CompareType.INCLUDE));
            filterInfo.getFilterItems().add(new FilterItemInfo("asseStatus", "3"));
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("adminOrg.*");
            sic.add("*");
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
            ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
            CoreBaseCollection collection = new CoreBaseCollection();
            if (expandAssessEntryCollection.size() > 0) {
                for (int i = 0; i < expandAssessEntryCollection.size(); i++) {
                    ExpandAssessEntryInfo expandAssessEntryInfo = expandAssessEntryCollection.get(i);
                    if (expandAssessEntryInfo.getAmendAssessRate() == null || expandAssessEntryInfo.getCheckRate() == null) {
                        throw new ShrWebBizException("部门[" + expandAssessEntryInfo.getAdminOrg().getName() + "]其中修正考核项评级，复核评级不能为空！");
                    }
                }
            }
        } catch (SHRWebException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 比较差异
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws ShrWebBizException
     */
    public void contrastDifferenceAction(HttpServletRequest request,
                                         HttpServletResponse response,
                                         ModelMap modelMap) throws BOSException, ShrWebBizException {
        String idArray = request.getParameter("idArray");
        if (StringUtils.isEmpty(idArray)) {
            throw new ShrWebBizException("勾选数据无效，请联系管理员！");
        }
        try {
            IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("adminOrg.*");
            sic.add("*");
            sic.add("assessor.*");
            FilterInfo filterInfo = new FilterInfo();
            filterInfo.getFilterItems().add(new FilterItemInfo("id", AtsUtil.toSet(idArray), CompareType.INCLUDE));
            filterInfo.getFilterItems().add(new FilterItemInfo("asseStatus", "3"));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
            ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
            if (expandAssessEntryCollection.size() > 0) {
                List list = new ArrayList();
                for (int i = 0; i < expandAssessEntryCollection.size(); i++) {
                    ExpandAssessEntryInfo expandAssessEntryInfo = expandAssessEntryCollection.get(i);
                    Map map = new HashMap();
                    PersonInfo assessor = expandAssessEntryInfo.getAssessor();
                    AdminOrgUnitInfo adminorg = expandAssessEntryInfo.getAdminOrg();
                    if (!expandAssessEntryInfo.getAmendAssessRate().equals(expandAssessEntryInfo.getCheckRate())
                    ) {
                        map.put("assessor.name", assessor.getName());
                        map.put("assessor.number", assessor.getNumber());
                        map.put("adminorg.name", adminorg.getName());
                        map.put("entrys.amendassessrate", expandAssessEntryInfo.getAmendAssessRate());
                        map.put("entrys.checkrate", expandAssessEntryInfo.getCheckRate());
                        list.add(map);
                    }
                }
                JSONUtils.SUCCESS(list);
            }
        } catch (SHRWebException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    /**
     * 查看计算规则
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws Exception
     */
    public void viewCalculationRulesAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
        String sql = "select top 1 FID ,FAttachment from T_HR_SHRAttachmentExt where FBunding like '%com.kingdee.eas.custom.expandassess.app.ComRule.form' ORDER BY FCreateTime DESC";
        IRowSet iRowSet = DbUtil.executeQuery(ctx, sql);
        String attachmentId = "";
        String attachmentExtId = "";
        while (iRowSet.next()) {
            attachmentExtId = iRowSet.getString("FID");
            attachmentId = iRowSet.getString("FAttachment");
        }
        if (attachmentExtId.equals("") || attachmentExtId.equals(null)) {
            throw new ShrWebBizException("未查询到附件，请联系管理员！！");
        }
        Map<String, String> map = new HashMap();
        String encode = URLEncoder.encode(attachmentId);
        map.put("attachmentId", encode);
        map.put("attachmentExtId", attachmentExtId);
        IAttachment iAttachment = AttachmentFactory.getLocalInstance(ctx);
        UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(ctx);
        //生成附件密钥
        try {
            String currentUserId = currentUserInfo.getId().toString();
            AttachmentInfo ai = iAttachment.getAttachmentInfo(new ObjectUuidPK(attachmentId));
            String fileKey = this.getFileKey(ai.getName(), ai.getSizeInByte(), ai.getAttachID(), currentUserId);
            map.put("fileKey", fileKey);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        JSONUtils.SUCCESS(map);
    }


    /**
     * 生成附件密钥
     *
     * @param attachName
     * @param attachSize
     * @param attachId
     * @param currentUserId
     * @return
     * @throws NoSuchAlgorithmException
     */
    private String getFileKey(String attachName, int attachSize, String attachId, String currentUserId) throws NoSuchAlgorithmException {
        String str = MessageFormat.format("{0}{1}{2}{3}{4}", "4dz0r08D", attachName, attachSize, attachId, currentUserId);
        return MD5Util.encode(str);
    }

    /**
     * 计算评级
     */
    public void calculateRateAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws ShrWebBizException {
        //周期ID
        String billID = request.getParameter("billId");
        //部门id集合
        String adminIdArray = request.getParameter("adminIdArray");
        if (com.kingdee.util.StringUtils.isEmpty(billID) && com.kingdee.util.StringUtils.isEmpty(adminIdArray)) {
            throw new ShrWebBizException("单据id和已选择部门不能为空！");
        }
        String[] split = adminIdArray.split(",");
        try {
            IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("assessor.*");
            sic.add("adminOrg.*");
            sic.add("parent.*");
            sic.add("assessRate");
            sic.add("checkRate");
            sic.add("amendAssessRate");
            ExpandAssessEntryCollection entryCollection = null;
            for (String adminorgId : split) {
                entryCollection = expandAssessService.qeruyEntryByBillIdAndAdminOrg(ctx, billID, adminorgId);
                //查询是否有未提交至考核人的数据
                Map map = queryAssestatus(entryCollection);
                Boolean is = Boolean.parseBoolean(map.get("is").toString());
                if (is) {
                    String message = (String) map.get("message");
                    JSONUtils.SUCCESS(message);
                    return;
                }
                List<ExpandAssessEntryInfo> list = new ArrayList();


                for (int i = 0; i < entryCollection.size(); i++) {
                    ExpandAssessEntryInfo expandAssessEntryInfo = entryCollection.get(i);
                    list.add(expandAssessEntryInfo);
                    ExpandAssessInfo parent = expandAssessEntryInfo.getParent();
                    BigDecimal target = expandAssessEntryInfo.getTarget();//目标值
                    BigDecimal threshold = expandAssessEntryInfo.getThreshold();//门槛值
                    BigDecimal challenge = expandAssessEntryInfo.getChallenge();//挑战值
                    BigDecimal oneLift = expandAssessEntryInfo.getOneLift();//自拓型项目
                    BigDecimal uniteLift = expandAssessEntryInfo.getUniteLift();//联拓联管型项目
                    BigDecimal shareLiftLC = expandAssessEntryInfo.getShareLiftLC();//共拓型项目-流程配合型
                    BigDecimal shareLiftZY = expandAssessEntryInfo.getShareLiftZY();//共拓型项目-专业配合型
                    BigDecimal shareLiftRes = expandAssessEntryInfo.getShareLiftRes();//共拓型项目-资源贡献型


                    BigDecimal contracts = expandAssessEntryInfo.getContracts();//签约额总和
                    //int rankings = expandAssessEntryInfo.getRankings();//排名
                    //获取考核评级
                    ExpandAssessEntryInfo entryInfo = null;
                    //判断是否是年度或者一季度，否则需要跟换计算方式
                    int quarter = parent.getQuarter();//季度
                    int year = parent.getYear();//年度

                    //计算季度比例后的的比例
                    Map<String, BigDecimal> matrixingRatio = getMatrixingRatio(parent, threshold, challenge, target);
                    BigDecimal thresholdDn = matrixingRatio.get("thresholdDn");
                    BigDecimal challengeDn = matrixingRatio.get("challengeDn");
                    BigDecimal targetDn = matrixingRatio.get("targetDn");
                    if (quarter > 1) {
                        //获取考核评级
                        entryInfo = getAssessRate(contracts, challengeDn, oneLift, expandAssessEntryInfo, targetDn, thresholdDn);
                        //累计完成签约额
                        BigDecimal sumContracts = getSumContracts(quarter, entryInfo, iExpandAssessEntry);
                        AssessRatingEnum assessRate = entryInfo.getAssessRate();
                        Integer value = Integer.parseInt(assessRate.getValue());
                        //先赋值，防止不进任何条件
                        entryInfo.setAmendAssessRate(entryInfo.getAssessRate());
                        if (value <= 4) {
                            //绩效评级 为 B及B以上 	 累计完成签约额 小于 门槛值，那么 绩效评级为 降两档。
                            if (sumContracts.compareTo(threshold) < 0) {
                                entryInfo.setAmendAssessRate(AssessRatingEnum.getEnum(String.valueOf(value + 2)));
                            } else
                                //绩效评级 为 B及B以上 	 累计完成签约额 大于等于 门槛值 且 累计完成签约额 小于 目标值，那么 绩效评级为 降一档。
                                if (sumContracts.compareTo(threshold) >= 0
                                        && sumContracts.compareTo(target) < 0) {
                                    entryInfo.setAmendAssessRate(AssessRatingEnum.getEnum(String.valueOf(value + 1)));
                                }
                        }
                        if (value >= 4) {
                            //绩效评级 为 B及B以下	累计完成签约额 大于 目标值 且 累计完成签约额 小于 挑战值，那么 绩效评级为 升一档。
                            if (sumContracts.compareTo(target) > 0 && sumContracts.compareTo(challenge) < 0) {
                                entryInfo.setAmendAssessRate(AssessRatingEnum.getEnum(String.valueOf(value - 1)));
                            } else
                                //绩效评级 为 B及B以下累计完成签约额 大于等于 挑战值，那么 绩效评级为 升两档。
                                if (sumContracts.compareTo(challenge) >= 0) {
                                    entryInfo.setAmendAssessRate(AssessRatingEnum.getEnum(String.valueOf(value - 2)));
                                }
                        }
                    } else {
                        //获取考核评级
                        entryInfo = getAssessRate(contracts, challengeDn, oneLift, expandAssessEntryInfo, targetDn, thresholdDn);
                        entryInfo.setAmendAssessRate(entryInfo.getAssessRate());
                        entryInfo.setCheckRate(entryInfo.getAssessRate());
                    }
                    if (entryInfo.getCheckRate() == null) {
                        entryInfo.setCheckRate(entryInfo.getAmendAssessRate());
                    }
                    SelectorItemCollection updSic = new SelectorItemCollection();
                    updSic.add("assessRate");
                    updSic.add("checkRate");
                    updSic.add("amendAssessRate");
                    iExpandAssessEntry.updatePartial(entryInfo, updSic);
                }
                // 使用比较器对列表进行排序
                Collections.sort(list, (o1, o2) -> o2.getContracts().intValue() - o1.getContracts().intValue());
                SelectorItemCollection udpateSic = new SelectorItemCollection();
                udpateSic.add("rankings");
                //保存排名
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setRankings(i + 1);
                    ExpandAssessEntryInfo expandAssessEntryInfo = list.get(i);
                    iExpandAssessEntry.updatePartial(expandAssessEntryInfo, udpateSic);
                }
            }
            JSONUtils.SUCCESS(entryCollection);

        } catch (BOSException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (EASBizException e) {
            throw new RuntimeException(e);
        } catch (SHRWebException e) {
            throw new RuntimeException(e);
        }

    }

    /***
     * 通过季度获取当前季度比例进行换算
     * @param parent
     * @param thresholdDn
     * @param challengeDn
     * @param targetDn
     */
    public Map getMatrixingRatio(ExpandAssessInfo parent, BigDecimal thresholdDn, BigDecimal challengeDn, BigDecimal targetDn) throws BOSException {
        Map<String, BigDecimal> map = new HashMap();
        QuarterlyRatioCollection quarterlyRatioByYearColl = expandAssessService.getQuarterlyRatioByYear(ctx, parent.getYear());
        if (quarterlyRatioByYearColl != null && quarterlyRatioByYearColl.size() > 0) {
            QuarterlyRatioInfo quarterlyRatioInfo = quarterlyRatioByYearColl.get(0);
            double ratio = 0;//比例
            if (parent.getQuarter() == 1) {
                ratio = quarterlyRatioInfo.getQuarterOne();
            }
            if (parent.getQuarter() == 2) {
                ratio = quarterlyRatioInfo.getQuarterTwo();
            }
            if (parent.getQuarter() == 3) {
                ratio = quarterlyRatioInfo.getQuarterThree();
            }
            if (parent.getQuarter() == 4) {
                ratio = quarterlyRatioInfo.getQuarterFour();
            }
            thresholdDn = thresholdDn.multiply(BigDecimal.valueOf((ratio / 100)));
            challengeDn = challengeDn.multiply(BigDecimal.valueOf((ratio / 100)));
            targetDn = targetDn.multiply(BigDecimal.valueOf((ratio / 100)));
            map.put("thresholdDn", thresholdDn);
            map.put("challengeDn", challengeDn);
            map.put("targetDn", targetDn);
        }
        return map;
    }

    /**
     * 查询是否有未提交至考核人的数据
     *
     * @param entryCollection
     */
    public Map queryAssestatus(ExpandAssessEntryCollection entryCollection) {
        Map map = new HashMap();
        StringBuilder sb = new StringBuilder();
        List list = new ArrayList();
        ExpandAssessEntryInfo entryInfo = entryCollection.get(0);
        sb.append(entryInfo.getAdminOrg().getName() + ":");
        for (int i = 0; i < entryCollection.size(); i++) {
            ExpandAssessEntryInfo expandAssessEntryInfo = entryCollection.get(i);
            if (expandAssessEntryInfo.getAsseStatus() == ExpandStatusEunm.START || expandAssessEntryInfo.getAsseStatus() == ExpandStatusEunm.UNSTART) {
                list.add(expandAssessEntryInfo.getAssessor().getName());
            }
        }

        sb.append(list + "这些人员还未提交至考核人，共" + list.size() + "人。");
        if (list.size() > 0) {
            map.put("is", true);
            map.put("message", sb.toString());
        } else {
            map.put("is", false);
            map.put("message", null);
        }
        return map;
    }

    /**
     * 获取之前季度的累计完成签约额
     *
     * @param quarter
     * @param entryInfo
     * @param iExpandAssessEntry
     * @throws BOSException
     */
    private BigDecimal getSumContracts(int quarter, ExpandAssessEntryInfo entryInfo, IExpandAssessEntry
            iExpandAssessEntry) throws BOSException {
        double num = 0;
        for (int j = quarter; j > 0; j--) {
            FilterInfo filterInfo = new FilterInfo();
            filterInfo.getFilterItems().add(new FilterItemInfo("assessor.id", entryInfo.getAssessor().getId()));
            filterInfo.getFilterItems().add(new FilterItemInfo("adminOrg.id", entryInfo.getAdminOrg().getId()));
            filterInfo.getFilterItems().add(new FilterItemInfo("parent.quarter", j));
            filterInfo.getFilterItems().add(new FilterItemInfo("parent.year", entryInfo.getParent().getYear()));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
            ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
            for (int i = 0; i < expandAssessEntryCollection.size(); i++) {
                ExpandAssessEntryInfo expandAssessEntryInfo = expandAssessEntryCollection.get(i);
                BigDecimal contracts = expandAssessEntryInfo.getContracts();
                num += contracts.doubleValue();
            }
        }
        BigDecimal sum = new BigDecimal(num);
        return sum;
    }

    /**
     * 获取绩效评级
     *
     * @param contracts             签约额总和
     * @param challenge             挑战值
     * @param oneLift               自拓型项目金额
     * @param expandAssessEntryInfo 考核人明细表
     * @param target                目标值
     * @param threshold             门槛值
     */
    private ExpandAssessEntryInfo getAssessRate(BigDecimal contracts, BigDecimal challenge, BigDecimal
            oneLift, ExpandAssessEntryInfo expandAssessEntryInfo, BigDecimal target, BigDecimal threshold) {
        if (contracts.compareTo(challenge.multiply(new BigDecimal("1.5"))) >= 0
                && oneLift.compareTo(contracts.multiply(new BigDecimal("0.5"))) >= 0) {//员工签约额总和 大于等于挑战值的1.5倍 且 自拓型项目金额 大于签约总和50% ，那么 绩效评级为A+。
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.APLUS);
        } else if (contracts.compareTo(challenge) >= 0) {//员工签约额总和 大于等于挑战值，那么 绩效评级为A。
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.A);
        } else if (contracts.compareTo(target.multiply(new BigDecimal("1.1"))) >= 0
                && contracts.compareTo(challenge) < 0) {//员工签约额总和 大于等于目标值的1.1倍 且 小于挑战值，那么 绩效评级为B+。
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.BPLUS);
        } else if (contracts.compareTo(target.multiply(new BigDecimal("0.9"))) >= 0
                && contracts.compareTo(target.multiply(new BigDecimal("1.1"))) < 0) {//员工签约额总和 大于等于目标值的0.9倍 且 小于目标值的1.1倍，那么 绩效评级为B。
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.B);
        } else if (contracts.compareTo(threshold) >= 0
                && contracts.compareTo(target.multiply(new BigDecimal("0.9"))) < 0) {//员工签约额总和 大于等于门槛值 且 小于目标值的0.9倍，那么 绩效评级为B-。
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.BMIUS);
        } else if (contracts.compareTo(threshold.multiply(new BigDecimal("0.8"))) >= 0
                && contracts.compareTo(threshold) < 0 && challenge.compareTo(contracts.multiply(new BigDecimal("0.5"))) >= 0) {//员工签约额总和 大于等于门槛值的0.8倍 且 小于门槛值 且 自拓型项目金额 大于签约总和50% ，那么 绩效评级为C。
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.C);
        } else {
            expandAssessEntryInfo.setAssessRate(AssessRatingEnum.D);
        }
        return expandAssessEntryInfo;
    }

    /**
     * 过滤提交按钮的行政组织F7数据
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void submitFilterAdminAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws
            SHRWebException, BOSException {
        String billID = request.getParameter("billId");
        JSONUtils.SUCCESS(expandAssessService.getAdminOrgFilter(ctx, billID));
    }

    /**
     * 撤回至考核人
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     */
    public void revocaAssessorAction(HttpServletRequest request,
                                     HttpServletResponse response,
                                     ModelMap modelMap) throws ShrWebBizException {
        //获取删除ID
        String idArray = request.getParameter("idArray");
        if (StringUtils.isEmpty(idArray)) {
            throw new ShrWebBizException("勾选数据无效，请联系管理员！");
        }
        try {
            expandAssessService.updateAsseStatusAll(ctx, idArray, ExpandStatusEunm.ASSESUBMINT, ExpandStatusEunm.START, "请勾选状态为考核人已提交的数据,否则无法撤回");
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (EASBizException e) {
            throw new ShrWebBizException(e);
        }

    }

    /**
     * 提交至专员
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     */
    public void submitAttacheAction(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap modelMap) throws ShrWebBizException {
        //获取删除ID
        String idArray = request.getParameter("idArray");
        if (StringUtils.isEmpty(idArray)) {
            throw new ShrWebBizException("勾选数据无效，请联系管理员！");
        }
        try {
            IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
            FilterInfo filterInfo = new FilterInfo();
            filterInfo.getFilterItems().add(new FilterItemInfo("id", AtsUtil.toSet(idArray), CompareType.INCLUDE));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
            ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
            CoreBaseCollection collection = new CoreBaseCollection();
            if (expandAssessEntryCollection.size() > 0) {
                for (int i = 0; i < expandAssessEntryCollection.size(); i++) {
                    ExpandAssessEntryInfo expandAssessEntryInfo = expandAssessEntryCollection.get(i);
                    if (expandAssessEntryInfo.getAssessRate() == null) {
                        throw new ShrWebBizException("提交失败，请检查考核人是否计算评级");
                    }
                    if (ExpandStatusEunm.ASSESUBMINT == expandAssessEntryInfo.getAsseStatus()) {
                        expandAssessEntryInfo.setAsseStatus(ExpandStatusEunm.PRINCIPALSUBMIT);
                        collection.add(expandAssessEntryInfo);
                    }
                    // else {
                    //    throw new ShrWebBizException("提交失败，不可重复提交！");
                    //}
                }
            }

            iExpandAssessEntry.updateBatchData(collection);
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (EASBizException e) {
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 动态表单保存
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     * @returnA
     */
    public void saveDynGridAction(HttpServletRequest request,
                                  HttpServletResponse response,
                                  ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            List<Map<String, String>> dataList = (List) JSONUtils.convertJsonToObject(request.getParameter("modi"), List.class);
            IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
            //待更新数据集合
            Map<String, ExpandAssessEntryInfo> updEntryCols = new HashMap<String, ExpandAssessEntryInfo>();
            //待更新字段
            Map<String, SelectorItemCollection> updSics = new HashMap<String, SelectorItemCollection>();
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, String> map = dataList.get(i);

                ExpandAssessEntryInfo entryInfo;
                SelectorItemCollection updSic;
                String fid = map.get("fid");
                //保存修改数据
                if (updEntryCols.containsKey(fid)) {
                    entryInfo = updEntryCols.get(fid);
                } else {
                    entryInfo = new ExpandAssessEntryInfo();
                    entryInfo.setId(BOSUuid.read(fid));
                    updEntryCols.put(fid, entryInfo);
                }
                //保存修改字段
                if (updSics.containsKey(fid)) {
                    updSic = updSics.get(fid);
                } else {
                    updSic = new SelectorItemCollection();
                    updSics.put(fid, updSic);
                }
                //字段名称
                String colName = map.get("column");
                //值类型
                String type = map.get("type");
                //修改值
                Object value = map.get("value");
                if (type.equals("Enum")) {
                    value = Integer.parseInt(value.toString());
                    colName = "checkRate";
                }
                updSic.add(colName);
                entryInfo.put(colName, value);
            }
            for (String id : updEntryCols.keySet()) {
                //修改的实体
                ExpandAssessEntryInfo entryInfo = updEntryCols.get(id);
                //修改的字段
                SelectorItemCollection updSic = updSics.get(id);
                updSic.add("contracts");
                iExpandAssessEntry.updatePartial(entryInfo, updSic);
            }
            JSONUtils.SUCCESS("成功修改" + dataList.size() + "条数据");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }

    }


    /**
     * 获取默认编辑列
     *
     * @param request
     * @return
     */
    protected Map<String, Map<String, Object>> getDefultEditColumnsSetting(HttpServletRequest request) {
        try {
            Map<String, Map<String, Object>> result = new HashMap();
            //复核评级
            EditColumnInfo stateEditColumn = new EditColumnInfo();
            stateEditColumn.setName("entrys.checkRate");
            stateEditColumn.setFormatter("shrselect");
            stateEditColumn.setEdittype("shrselect");
            stateEditColumn.setType("shrselect");
            EditOptions stateEditoptions = stateEditColumn.getEditoptions();
            stateEditoptions.setUrlSource("com.kingdee.eas.custom.expandassess.app.AssessRatingEnum");
            SelectJson selectJson = stateEditoptions.getSelectJson();
            selectJson.setId("setCheckRate");//方法名称
            selectJson.setName("checkRate");//属性名称
            selectJson.setEnumSource("com.kingdee.eas.custom.expandassess.app.AssessRatingEnum");
            result.put("entrys.checkRate", stateEditColumn.convertToMap());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
