package nccloud.web.hrwa.wagrade.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import nc.bs.framework.common.ITimeService;
import nc.itf.hr.wa.IWaGradeQueryService;
import nc.itf.hr.wa.IWaGradeService;
import nc.vo.bd.pub.NODE_TYPE;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.uif2.LoginContext;
import nc.vo.wa.grade.AggWaGradeVO;
import nc.vo.wa.grade.CrtVO;
import nc.vo.wa.grade.WaCriterionVO;
import nc.vo.wa.grade.WaGradeVO;
import nc.vo.wa.grade.WaGradeVerVO;
import nccloud.commons.lang.ArrayUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.web.hr.pub.HRCommonAction;
import nccloud.web.hr.pub.HRNccTemplateUtils;
import nccloud.web.hr.pub.HRNccUtils;
import nccloud.web.hrwa.helper.StringHelper;
import nccloud.web.hrwa.pub.ErrorContent;
import nccloud.web.hrwa.wagrade.save.WaGradeVerHelper;
import nccloud.web.hrwa.wagrade.validation.WaGradeVerValidateHelper;
import nccloud.web.uapbd.commons.web.ParamUtils;
/**
 * 
 * 2019年7月13日下午3:06:32
 * msw：
 * 保存薪资标准版本信息
 */
public class WaGradeVerSaveAction extends HRCommonAction {
	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		ParamUtils param = new ParamUtils(request);
		String headJson = StringHelper.getString(request, "head").replace("crtVOs", "crtVOs_null");
		WaGradeVerVO[] gradeVerVOs = HRNccTemplateUtils.getVOFromGrid(WaGradeVerVO.class, headJson);
		if (ArrayUtils.isEmpty(gradeVerVOs)) {
			return null;
		}
		WaGradeVerVO selectVerVO = new WaGradeVerHelper().getSelectVerVo(gradeVerVOs);
		if (selectVerVO == null) {
			return null;
		}
		String waStaTableData = param.get("sublist").toString();
		if (StringUtils.isBlank(waStaTableData)) {
			throw new BusinessException(ErrorContent.QUERYMETHODNULL);
		}
		WaGradeVerValidateHelper validateHelper = new WaGradeVerValidateHelper();
		WaGradeVerHelper waGradeVerHelper = new WaGradeVerHelper();
		// 重新整合聚合vo
		AggWaGradeVO aggWaGradeVO = getSelectAggWagradeFromDBByPkWaGrd(selectVerVO.getPk_wa_grd());
		WaGradeVO wagradeVO = (WaGradeVO) aggWaGradeVO.getParentVO();
		waGradeVerHelper.setWaGradeVerVO(selectVerVO, wagradeVO, waStaTableData);
		
		
		//add by@chenzf 判断是否从引用版本来的 1为是 2021-3-16 15:17:26 begin
//		String type = param.get("type").toString();
		LoginContext context = HRNccUtils.getLoginContext(param);
		if("1".equals(selectVerVO.getType())) {
			CrtVO[] crtVOs = selectVerVO.getCrtVOs();
			List<WaCriterionVO> crList = new ArrayList<>();
			if(crtVOs != null && crtVOs.length > 0) {
				for(int i = 0; i < crtVOs.length; i++) {
					if(crtVOs[i].getVecData() != null) {
						crList.add((WaCriterionVO) crtVOs[i].getVecData().get(0));
					}
				}
				selectVerVO.setStatus(VOStatus.NEW);
				selectVerVO.setCriterionvos(crList.toArray(new WaCriterionVO[0]));
			}
		}
		//add by@chenzf 判断是否从引用版本来的 1为是 2021-3-16 15:17:26 
		
		// 宽带薪酬的场合才校验
		validateHelper.validate(wagradeVO, selectVerVO, gradeVerVOs);
		// 更新审计信息
		resetModifyInfo(wagradeVO);
		
		//add by@chenzf 添加范围校验和数据校验 2021-4-6 12:19:28 begin
		//级别金额下限(含下限)lower000000000000001  级别金额上限(含上限)upper000000000000001
		WaCriterionVO[] waCrtVOs = selectVerVO.getCriterionvos();
		if(waCrtVOs != null && waCrtVOs.length > 0) {
			String msg = "";
			if(wagradeVO.getIsmultsec() != null && wagradeVO.getIsmultsec().booleanValue()) {
				if(StringUtils.isNotBlank(wagradeVO.getPk_wagrade_top())) {
					IWaGradeQueryService iWaGradeQueryService = ServiceLocator.find(IWaGradeQueryService.class);
					WaCriterionVO[] topWaCrtVOs = iWaGradeQueryService.queryByClsPk(wagradeVO.getPk_wagrade_top(), wagradeVO.getIsmultsec().booleanValue(), 1);
					//年薪，key为级别+档级,value为金额
					Map<String,UFDouble> map = new HashMap();
					//月工资或者年终奖 key为级别+档级,value为金额
					Map<String,UFDouble> map2 = new HashMap();
					for(WaCriterionVO topVO : topWaCrtVOs) {
						String prmlvName = topVO.getPrmlvName();
						String seclvName = topVO.getLevName();
						UFDouble value = topVO.getCriterionvalue();
						map.put(prmlvName+"@@"+seclvName, value);
					}
					
					//2为月薪，3为年终奖
					String standard_type = wagradeVO.getStandard_type() != null && wagradeVO.getStandard_type().equals("2") ? "3" : "2";
					if(wagradeVO.getStandard_type() != null && "1".equals(wagradeVO.getStandard_type())) {
						standard_type = "0";
					}
					String sql = "pk_wagrade_top = '"+wagradeVO.getPk_wagrade_top()+"' and standard_type = '"+standard_type+"' and nvl(dr,0) = 0";
					String pkWaGrd = iWaGradeQueryService.queryWaGradePK(sql);
					if(StringUtils.isNotBlank(pkWaGrd)) {
						WaCriterionVO[] crtVOs = iWaGradeQueryService.queryByClsPk(pkWaGrd, wagradeVO.getIsmultsec().booleanValue(), 1);
						if(crtVOs != null && crtVOs.length > 0) {
							for(WaCriterionVO vo : crtVOs) {
								if("lower000000000000001".equals(vo.getPk_wa_seclv()) || "upper000000000000001".equals(vo.getPk_wa_seclv())) {
									continue;
								}
								String prmlvName = vo.getPrmlvName();
								String seclvName = vo.getLevName();
								UFDouble value = vo.getCriterionvalue();
								map2.put(prmlvName+"@@"+seclvName, value);
							}
						}
					}
					UFBoolean check = UFBoolean.FALSE;
					if(wagradeVO.getStandard_type() != null && "2".equals(wagradeVO.getStandard_type())){
						check = UFBoolean.TRUE;
					}
					
					
					for(WaCriterionVO waCrtVO : waCrtVOs) {
						if("lower000000000000001".equals(waCrtVO.getPk_wa_seclv()) || "upper000000000000001".equals(waCrtVO.getPk_wa_seclv())) {
							continue;
						}
						String prmlvName = waCrtVO.getPrmlvName();
						String seclvName = waCrtVO.getLevName();
						UFDouble value = waCrtVO.getCriterionvalue();
						UFDouble value2 =  map2.get(prmlvName+"@@"+seclvName) == null ? UFDouble.ZERO_DBL : map2.get(prmlvName+"@@"+seclvName);
						UFDouble topValue = map.get(prmlvName+"@@"+seclvName);
						UFDouble trueValue = UFDouble.ZERO_DBL;
						if(check.booleanValue()) {
							trueValue = value.multiply(12).add(value2);
						} else {
							trueValue = value.add(value2.multiply(12));
						}
						
						if(trueValue.doubleValue() > topValue.doubleValue()) {
							msg = msg + "[薪级"+prmlvName+",薪档"+seclvName+"]";
						}
					}
				}
				if(selectVerVO.getEffect_flag().booleanValue()) {
					if(msg.length() > 0) {
						throw new BusinessException("对应级别的月薪标准*12与对应级别的年终奖标准之和需在对应级别的年薪标准范围内，超出范围则无法生效数据,这些数据不在范围内"+msg);
					}
				}
				//组织主键=集团主键，则证明是集团节点
//				if(wagradeVO.getPk_org().equals(wagradeVO.getPk_group())) {
//					if(context.getNodeType() == NODE_TYPE.GROUP_NODE) {
				UFBoolean isscope = wagradeVO.getIsscope();
				if(isscope != null && isscope.booleanValue()) {
					//key为薪级+薪档，value为值
					Map<String,UFDouble> valueMap = new HashMap();
					for(WaCriterionVO waCrtVO : waCrtVOs) {
						String pkWaPrmlv = waCrtVO.getPk_wa_prmlv();
						String pkWaSeclv = waCrtVO.getPk_wa_seclv();
						UFDouble value = waCrtVO.getCriterionvalue();
						if("lower000000000000001".equals(waCrtVO.getPk_wa_seclv()) || "upper000000000000001".equals(waCrtVO.getPk_wa_seclv())) {
							valueMap.put(pkWaPrmlv+"@"+pkWaSeclv, value);
						}
					}
					
					for(WaCriterionVO waCrtVO : waCrtVOs) {
						String pkWaPrmlv = waCrtVO.getPk_wa_prmlv();
						String pkWaSeclv = waCrtVO.getPk_wa_seclv();
						UFDouble value = waCrtVO.getCriterionvalue();
						if("lower000000000000001".equals(waCrtVO.getPk_wa_seclv()) || "upper000000000000001".equals(waCrtVO.getPk_wa_seclv())) {
							continue;
						}
						if(context.getNodeType() == NODE_TYPE.GROUP_NODE) {
							if(value.doubleValue() == 0) {
								continue;
							}
						}
						UFDouble lowerValue = valueMap.get(pkWaPrmlv + "@" + "lower000000000000001");//下限
						UFDouble upperValue = valueMap.get(pkWaPrmlv + "@" + "upper000000000000001");//上限
						
						if(value.doubleValue() >= lowerValue.doubleValue() && value.doubleValue() <= upperValue.doubleValue()) {
							
						} else {
							//不在范围内
							msg = msg+"[薪级"+waCrtVO.getPrmlvName()+",薪档"+waCrtVO.getSeclvName()+"]";
						}
					}
					if(msg.length() > 0) {
						throw new BusinessException("以下的数据不在上下限范围内："+msg);
					}
				}
				if(NODE_TYPE.GROUP_NODE.equals(context.getNodeType())) {
					String msg2 = "";
					//key为薪级+薪档，value为值
					Map<String,UFDouble> valueMap = new HashMap();
					for(WaCriterionVO waCrtVO : waCrtVOs) {
						String pkWaPrmlv = waCrtVO.getPk_wa_prmlv();
						String pkWaSeclv = waCrtVO.getPk_wa_seclv();
						UFDouble value = waCrtVO.getCriterionvalue();
						if("lower000000000000001".equals(waCrtVO.getPk_wa_seclv()) || "upper000000000000001".equals(waCrtVO.getPk_wa_seclv())) {
							valueMap.put(pkWaPrmlv+"@"+pkWaSeclv, value);
						}
					}
					List<String> list = new ArrayList();
					for(WaCriterionVO waCrtVO : waCrtVOs) {
						String pkWaPrmlv = waCrtVO.getPk_wa_prmlv();
						if(list.contains(pkWaPrmlv)) {
							continue;
						}
						UFDouble lowerValue = valueMap.get(pkWaPrmlv + "@" + "lower000000000000001");//下限
						UFDouble upperValue = valueMap.get(pkWaPrmlv + "@" + "upper000000000000001");//上限
						if(lowerValue.doubleValue() <= upperValue.doubleValue()) {
							list.add(pkWaPrmlv);
						} else {
							list.add(pkWaPrmlv);
							msg2 = msg2+"[薪级"+waCrtVO.getPrmlvName()+"]";
						}
					}
					if(msg2.length() > 0) {
						throw new BusinessException("以下的薪级金额下限不能大于薪级金额上限："+msg2);
					}
				}
			}
		}
			
//		}
		
		//add by@chenzf 添加范围校验和数据校验 2021-4-6 12:19:28 end
		
		// 保存
		WaGradeVerVO verVO = saveWaGradeVer(wagradeVO, selectVerVO);
		// 对保存后的数据进行校验，并把校验信息返回前端
		JSONObject validataMsgJson = new JSONObject();
		validateHelper.setValidataWaStandTableMsg(validataMsgJson, verVO, wagradeVO, aggWaGradeVO);
		return validataMsgJson;
	}

	/**
	 * 
	 * 2019年6月12日下午6:08:26 msw
	 * @param wagradeVO：
	 *
	 */
	private void resetModifyInfo(WaGradeVO wagradeVO) {
		wagradeVO.setModifier(SessionContext.getInstance().getClientInfo().getUserid());
		wagradeVO.setModifiedtime(ServiceLocator.find(ITimeService.class).getUFDateTime());
	}
    /**
     * 
     * 2019年7月13日下午2:17:15
     * msw
     * @param PkWaGrd
     * @return
     * @throws BusinessException：
     * 通过选中数据的PkWaGrd，查找聚合VO
     */
	private AggWaGradeVO getSelectAggWagradeFromDBByPkWaGrd(String PkWaGrd) throws BusinessException {
		return (AggWaGradeVO) ServiceLocator.find(IWaGradeQueryService.class).queryAggWagradeByGrdPK(PkWaGrd);
	}
    /**
     * 
     * 2019年7月13日下午2:24:01
     * msw
     * @param wagradeVO
     * @param selectVerVO
     * @return
     * @throws BusinessException：
     * 保存薪资标准版本信息
     */
	private WaGradeVerVO saveWaGradeVer(WaGradeVO wagradeVO, WaGradeVerVO selectVerVO) throws BusinessException {
		return ServiceLocator.find(IWaGradeService.class).processCriterionArray(wagradeVO, selectVerVO);
	}
	
}
