package nccloud.web.hrwa.waruleex.action;

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

import nc.hr.utils.ResHelper;
import nc.itf.hr.wa.IWaRuleExQueryService;
import nc.itf.hr.wa.IWaRuleExService;
import nc.vo.bd.pub.NODE_TYPE;
import nc.vo.hrwa.waruleex.AggWageformExVO;
import nc.vo.hrwa.waruleex.WageformExVO;
import nc.vo.hrwa.waruleex.WageformdetExVO;
import nc.vo.hrwa.waruleexorg.WageformExOrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.uif2.LoginContext;
import nc.vo.wa.rule.WageformVO;
import nccloud.commons.collections.MapUtils;
import nccloud.commons.lang.ArrayUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.ui.pattern.form.Form;
import nccloud.framework.web.ui.pattern.grid.Grid;
import nccloud.web.hr.pub.HRCommonAction;
import nccloud.web.hr.pub.HRNccTemplateUtils;
import nccloud.web.hrwa.helper.StringHelper;
import nccloud.web.hrwa.pub.IWATempletConst;
import nccloud.web.uapbd.commons.web.ParamUtils;

public class WaRuleExSaveAction extends HRCommonAction {

	@SuppressWarnings("unchecked")
	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		ParamUtils param = new ParamUtils(request);
		Map<String, String> map = new HashMap<String, String>();
		map = param.getMap("base_param", map);
		LoginContext context = WaRuleExUtil.getLogincontext(param, map);
		String opType = map.get("op_type");
		AggWageformExVO aggvo = new AggWageformExVO();
		//通过前端传值，获取聚合VO
		setAggWageformVO(aggvo, request);
		WageformdetExVO[] wageRuleVOArr = (WageformdetExVO[]) aggvo.getChildrenVO();
		//薪资规则数据
		if (ArrayUtils.isEmpty(wageRuleVOArr)) {
			throw new BusinessException(ResHelper.getString("60130adjmtc", "060130adjmtc0241")/* 保存失败！ */
					+ ResHelper.getString("60130payrule",
							"060130payrule0006")/* @res "表体数据不能为空！" */);
		}
		// 检查规则公式中是否存在重复的公式
		String msg = checkSameRule(wageRuleVOArr);
		// 重新封装聚合VO
		reMakeAggVO(aggvo, wageRuleVOArr);
		// 获取新增、修改或是复制之后的聚合VO
		aggvo = getAfterOperateAggWageformVO(opType, aggvo, context);
		
		//add by@chenzf公用类型保存生成对应下面各种组织数据 2021-4-7 21:42:41 begin
		WageformExVO wageformExVO = (WageformExVO) aggvo.getParentVO();
		//组织主键=集团主键，则证明是集团节点
		
//		if(wageformExVO.getPk_org().equals(wageformExVO.getPk_group())) {
		if(NODE_TYPE.GROUP_NODE.equals(context.getNodeType())) {
			//1为公用
			int scope = wageformExVO.getScope() == null ? 0 : wageformExVO.getScope();
			if(1 == scope) {
				//分配给组织aggvo数据
				List<AggWageformExVO> aggWageformExList = new ArrayList();
				//分配组织信息
				List<WageformExOrgVO> orgVOList = new ArrayList();
				List<String> orgList = ServiceLocator.find(IWaRuleExQueryService.class).queryAllOrgs();
				if(orgList != null && orgList.size() > 0) {
					for(String pk_org : orgList) {
						WageformExOrgVO wageformExOrgVO = new WageformExOrgVO();
						orgVOList.add(this.setWageformExOrgVO(wageformExOrgVO,wageformExVO.getPk_wa_wageformex(),pk_org));
						aggWageformExList.add(this.copyAggWageformExVO(aggvo,pk_org));
					}
				}
				List<AggWageformExVO> returnList = new ArrayList();
//				String pk="";
//				if(aggWageformExList.size() > 0) {
//					for(AggWageformExVO aggvo2 : aggWageformExList) {
//						AggWageformExVO returnAggVO = ServiceLocator.find(IWaRuleExService.class).insertVO(aggvo2);
//						returnList.add(returnAggVO);
//						pk = pk + returnAggVO.getParentVO().getPrimaryKey()+",";
//					}
//				}
				if(orgVOList.size() > 0) {
					ServiceLocator.find(IWaRuleExService.class).instertWageformExOrgVO(orgVOList.toArray(new WageformExOrgVO[0]));
				}
			}
			
		}
		//add by@chenzf公用类型保存生成对应下面各种组织数据 2021-4-7 21:42:41 end
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 设置返给前端的数据
		setResultMap(resultMap, aggvo, map, msg, context);
		return MapUtils.isEmpty(resultMap) ? null : resultMap;
	}
	
	public WageformExOrgVO setWageformExOrgVO(WageformExOrgVO wageformExOrgVO,String pkWaWageformex,String pk_org) {
		wageformExOrgVO.setPk_wa_wageformex(pkWaWageformex);
		wageformExOrgVO.setPk_org(pk_org);
		return wageformExOrgVO;
	}
	
	
	public AggWageformExVO copyAggWageformExVO(AggWageformExVO aggWageformExVO,String pk_org){
		AggWageformExVO newAggVO = new AggWageformExVO();
		WageformExVO wageformExVO = (WageformExVO) aggWageformExVO.getParentVO().clone();
		WageformdetExVO[] vos = (WageformdetExVO[]) aggWageformExVO.getChildrenVO();
		List<WageformdetExVO> voList = new ArrayList();
		for(int i = 0; i < vos.length; i++) {
			WageformdetExVO wageformdetExVO = new WageformdetExVO();
			wageformdetExVO = (WageformdetExVO) vos[i].clone();
			wageformdetExVO.setPk_wa_wageformdetex(null);
			wageformdetExVO.setPk_wa_wageformex(null);
			wageformdetExVO.setStatus(2);
			voList.add(wageformdetExVO);
		}
		
		
		wageformExVO.setPk_wa_wageformex(null);
		wageformExVO.setPk_org(pk_org);
		newAggVO.setParentVO(wageformExVO);
		newAggVO.setChildrenVO(voList.toArray(new WageformdetExVO[0]));
		return newAggVO;
	}

	
/**
 * 
 * 2019年6月5日下午5:59:25
 * msw
 * @param opType
 * @param aggvo
 * @param context
 * @return
 * @throws BusinessException：
 * 获取新增、修改或是复制之后的聚合VO
 *
 */
	private AggWageformExVO getAfterOperateAggWageformVO(String opType, AggWageformExVO aggvo, LoginContext context)
			throws BusinessException {
		switch (opType) {
		case "copy":
			// 设置组织
			((WageformVO) ((AggWageformExVO) aggvo).getParentVO()).setPk_org(context.getPk_org());
			// 复制
			return (AggWageformExVO) ServiceLocator.find(IWaRuleExService.class).copyTable((AggWageformExVO) aggvo);
		case "add":
			// 新增
			return (AggWageformExVO) ServiceLocator.find(IWaRuleExService.class).insertVO((AggWageformExVO) aggvo);
		case "edit":
			// 修改
			return (AggWageformExVO) ServiceLocator.find(IWaRuleExService.class).updateVO((AggWageformExVO) aggvo);
		default:
			return null;
		}
	}
/**
 * 
 * 2019年6月5日下午5:56:07
 * msw
 * @param resultMap
 * @param aggvo
 * @param map
 * @param msg
 * @param context：
 * 设置返给前端的数据
 *
 */
	private void setResultMap(Map<String, Object> resultMap, AggWageformExVO aggvo, Map<String, String> map, String msg,
			LoginContext context) {
		if (aggvo != null) {
			String areaParentCode = map.get("area_parent_code");
			String areaChildCode = map.get("area_child_code");
			String appCode = NODE_TYPE.ORG_NODE.equals(context.getNodeType()) ? IWATempletConst.APPCODE_WARULE_ORG
					: IWATempletConst.APPCODE_WARULE_GRP;
			if (areaParentCode == null || areaChildCode == null) {
				return;
			}
			WageformExVO selectedParentVo = (WageformExVO) aggvo.getParentVO();
			Form parentForm = (selectedParentVo != null)
					? HRNccTemplateUtils.getFormWithArea(appCode, areaParentCode, selectedParentVo) : null;
			WageformdetExVO[] selectedChildVOs = (WageformdetExVO[]) aggvo.getChildrenVO();
			Grid childGrid = (selectedChildVOs != null)
					? HRNccTemplateUtils.getGridWithArea(appCode, areaChildCode, selectedChildVOs) : null;
			resultMap.put("Parent", parentForm);
			resultMap.put("Child", childGrid);
			resultMap.put("message", msg);
			resultMap.put("success", "".equals(msg) ? true : false);
		} else {
			return;
		}
	}

	/**
	 * 
	 * 下午7:47:03 
	 * msw
	 * @param wageRuleVOArr
	 * @throws BusinessException：
	 * 检查规则公式中是否存在重复的公式
	 *
	 */

	private String checkSameRule(WageformdetExVO[] wageRuleVOArr) throws BusinessException {
		String msg = "";
		Map<String, WageformdetExVO> map = new HashMap<String, WageformdetExVO>();
		for (int i = 0; i < wageRuleVOArr.length; i++) {
			if (map.containsKey(wageRuleVOArr[i].getVformula())) {
				msg = ResHelper.getString("60130payrule",
						"060130payrule0007")/* @res "规则公式中存在重复的公式。" */;
			}
			map.put(wageRuleVOArr[i].getVformula(), wageRuleVOArr[i]);
		}
		return msg;
	}

	/**
	 * 
	 * 下午2:19:09 
	 * msw
	 * @param value
	 * @param wageRuleVOArr
	 * 设置聚合VO
	 *
	 */
	private void reMakeAggVO(Object value, WageformdetExVO[] wageRuleVOArr) {
		AggWageformExVO aggVo = (AggWageformExVO) value;
		resetWageformdetVOsStstus(wageRuleVOArr);
		if (!ArrayUtils.isEmpty(wageRuleVOArr)) {
			aggVo.setChildrenVO(wageRuleVOArr);
		}
	}

	/**
	 * 
	 * 下午2:19:06 
	 * msw
	 * @param wageRuleVOArr
	 * @return： 
	 * NC代码，保证只要保存就能修改、保存或删除
	 *
	 */
	private void resetWageformdetVOsStstus(WageformdetExVO[] wageRuleVOArr) {
		for (int i = 0; i < wageRuleVOArr.length; i++) {
			WageformdetExVO wageFormDetVO = wageRuleVOArr[i];
			if (VOStatus.UNCHANGED == wageFormDetVO.getStatus()) {
				wageFormDetVO.setStatus(VOStatus.UPDATED);
			}
		}
	}

	/**
	 * 
	 * 2019年6月27日下午4:45:42
	 * msw
	 * @param aggvo
	 * @param request：
	 * 通过前端传值，获取聚合VO
	 */
	private void setAggWageformVO(AggWageformExVO aggvo, IRequest request) {
		String parentVoStr = StringHelper.getString(request, "head");
		WageformExVO wageformVO = HRNccTemplateUtils.getVOFromForm(WageformExVO.class, parentVoStr);
		wageformVO.setPk_group(SessionContext.getInstance().getClientInfo().getPk_group());
		UFBoolean isenable = wageformVO.getIsenable();
		if(isenable == null) {
			wageformVO.setIsenable(UFBoolean.TRUE);
		}
		aggvo.setParentVO(wageformVO);
		// 设置子表
		String childVoStr = StringHelper.getString(request, "bodys");
		WageformdetExVO[] wageformdetVOs = HRNccTemplateUtils.getVOFromGrid(WageformdetExVO.class, childVoStr);
		if (ArrayUtils.isEmpty(wageformdetVOs))
			wageformdetVOs = new WageformdetExVO[0];
		aggvo.setChildrenVO(wageformdetVOs);
	}
}
