package nccloud.web.hrwa.paydata.action;

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

import com.alibaba.fastjson.JSONObject;

import nc.hr.utils.ResHelper;
import nc.itf.hr.wa.IPaydataManageService;
import nc.itf.hr.wa.IPaydataQueryService;
import nc.itf.hr.wa.IWaRuleExQueryService;
import nc.vo.hrp.budgetmgt.BudgetWarnMessageVo;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.wa.paydata.DataVO;
import nc.vo.wa.pub.WaLoginContext;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
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.WaLoginContextUtils;
import nccloud.web.hrwa.paydata.util.WaPaydataUtil;
import nccloud.web.hrwa.pub.IWATempletConst;
import nccloud.web.hrwa.pub.WaClassState;
import nccloud.web.uapbd.commons.web.ParamUtils;

/**
 * 审核数据
 * <p>
 * {@link nc.ui.wa.paydata.action.CheckAction}
 * </p>
 * 
 * @author liuyuan
 * @date 2018-5-22
 */
public class WaPaydataCheckAction extends HRCommonAction {

	/**
	 * 审核数据
	 * 
	 * @param arg0
	 *            请求参数，包含参数，year，period，pk_org，node_type
	 * @param isRangeAll
	 *            是否时全部计算，true为全部计算，false为部分计算
	 * @return
	 * @throws BusinessException
	 */
	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {

		JSONObject result = new JSONObject();
		result.put("status", 200);
		ParamUtils param = new ParamUtils(request);
		boolean isRangeAll = UFBoolean.valueOf(param.getString("isRangeAll", "true")).booleanValue();
		boolean sure = param.getBoolean("sure", false);
		IPaydataManageService service = ServiceLocator.find(IPaydataManageService.class);

		WaLoginContext loginContext = WaLoginContextUtils.getWaLoginContext(param);
		// 判断薪资档案数据状态是否发生了改变20200410
		new WaClassState().validateWaClassStatus(loginContext, "check");
		// 当前页数据，用于时间戳校验
		JSONObject jo = JSONObject.parseObject(request.read());
		DataVO[] dataVos = HRNccTemplateUtils.getVOFromGrid(DataVO.class, jo.getString("modelInfo"));
		String whereCondition = isRangeAll ? null : WaPaydataQueryHelper.getWhereCondition(param);

		boolean b = false;
		for (DataVO vo : dataVos) {
			if (vo.getCaculateflag().equals(UFBoolean.TRUE) && vo.getCheckflag().equals(UFBoolean.FALSE)) {
				b = true;
				break;
			}
		}
		
		//add by@chenzf薪资项目发放控制功能 2021-3-17 21:13:16 begin
		IWaRuleExQueryService iruleExService = ServiceLocator.find(IWaRuleExQueryService.class);
		List<Map<String, Object>> ruleMap = iruleExService.queryWageformExContral(loginContext);
		IPaydataQueryService queryService = ServiceLocator.find(IPaydataQueryService.class);
		DataVO[] dataVOs = queryService.queryDataVOsByCond(loginContext, whereCondition, null);
		Map<String,String> tipMap = new HashMap();
		boolean controlFlag = false;
		if(ruleMap != null && ruleMap.size() > 0) {
			Map<String,List> itemMap = new HashMap();
			for(int i = 0; i < ruleMap.size(); i++) {
				List list = new ArrayList();
				Map<String, Object> map = ruleMap.get(i);
				//例子f_1
				String itemkey = (String) map.get("itemkey");
				//bd_psndoc.edu = "@@@@Z710000000005L5U"
				String vformula = (String)map.get("vformula");
				//薪资项目名称
				String name = (String) map.get("name");
				//发放控制
				String iscontrol = (String) map.get("iscontrol");
				//上限金额
				UFDouble upperlimit = map.get("upperlimit") == null ? UFDouble.ZERO_DBL : new UFDouble(map.get("upperlimit").toString());
				if(!upperlimit.isTrimZero()) {
					list.add(name);
					list.add(upperlimit);
					list.add(vformula);
					list.add(iscontrol);
					itemMap.put(itemkey, list);
				}
			}
			for(DataVO dataVO : dataVOs) {
				String psncode = dataVO.getPsncode();
				String psnname = dataVO.getPsnname();
				String msg = "";
				for(String key : itemMap.keySet()) {
					UFDouble value = (UFDouble) dataVO.getAttributeValue(key);
					if(itemMap.get(key) == null) {
						continue;
					}
					UFDouble upperlimit = (UFDouble) itemMap.get(key).get(1);
					String vformula =  (String) itemMap.get(key).get(2);
					UFBoolean check = iruleExService.checkData(dataVO.getPk_wa_data(),vformula);
					if(value != null && value.compareTo(upperlimit) > 0) {
						if("Y".equals(itemMap.get(key).get(3))) {
							msg = msg + itemMap.get(key).get(0)+",";
						}
						if(!controlFlag) {
							controlFlag = "Y".equals(itemMap.get(key).get(3)) ? true : false;
						}
					}
				}
				if(msg.length() > 0) {
					tipMap.put(psncode+","+psnname, msg.substring(0, msg.length() - 1));
				}
			}
		}
		
		String message = "";
		if(tipMap.size() > 0) {
			for(String key : tipMap.keySet()) {
				message = message + "["+key + ","+tipMap.get(key)+"]";
			}
			message = "不符合薪资发放控制范围的数据如下：" +message;
		}
		if(controlFlag && message.length() > 0) {
			throw new BusinessException("审核失败。" + message);
		}
		//add by@chenzf薪资项目发放控制功能 2021-3-17 21:13:16 end
		
		if (b) {
			/** 调用预警 **/
			JSONObject prealerJson = new JSONObject();
			if (!sure) {
				// 项目预警
				List<String> files = WaPaydataUtil.getMessageAlertFileNameByButton(loginContext, whereCondition, WaPaydataUtil.PK_BTN_CHECK);
				if (files.size() > 0) {
					prealerJson.put("itemPrealerJson", files);
				}
				// 总额预警
				BudgetWarnMessageVo messageVO = WaPaydataUtil.budgetAlarm4Pay(loginContext, isRangeAll, whereCondition);
				if (messageVO != null && (messageVO.getLisCorpWarns().size() > 0 || messageVO.getLisDeptWarns().size() > 0)) {
					Map<String, Object> totalPrealerJson = new HashMap<>();
					Grid corpGrid = null;
					Grid deptGrid = null;
					if (messageVO.getLisCorpWarns().size() > 0) {
						corpGrid = HRNccTemplateUtils.getGridWithArea(IWATempletConst.PAGECODE_PAYDATA, IWATempletConst.AREACODE_PAYDATA_BGTWARN_Y, messageVO.getLisCorpWarns().toArray(new BudgetWarnMessageVo[0]));
					}
					if (messageVO.getLisDeptWarns().size() > 0) {
						deptGrid = HRNccTemplateUtils.getGridWithArea(IWATempletConst.PAGECODE_PAYDATA, IWATempletConst.AREACODE_PAYDATA_BGTWARN_D, messageVO.getLisDeptWarns().toArray(new BudgetWarnMessageVo[0]));
					}

					String title = "";
					boolean isControled = messageVO.isControled();
					if (isControled) {
						title = ResHelper.getString("60030wabudgetitem", "060030wabudgetitem0052")/* @res"[根据严格控制规则，不可以继续发放]" */;
					} else {
						title = ResHelper.getString("60030wabudgetitem", "060030wabudgetitem0051")/* @res"[根据控制规则，可以继续发放]" */;
					}
					totalPrealerJson.put("deptGrid", deptGrid);
					totalPrealerJson.put("corpGrid", corpGrid);
					totalPrealerJson.put("isControled", isControled);
					totalPrealerJson.put("title", title);
					prealerJson.put("totalPrealerJson", totalPrealerJson);
					result.put("status", 300);
					result.put("prealerJson", prealerJson);
					return result;
				}
			}
			result.put("prealerJson", prealerJson);
			service.onCheck(loginContext.getWaLoginVO(), whereCondition, isRangeAll);
			result.put("msg", ResHelper.getString("60130paydata",
					"060130paydata0522")/* @res "审核成功。" */+message);
			return result;

		}
		throw new BusinessException(ResHelper.getString("6013salarypmt",
				"06013salarypmt0288")/* @res "所选择的人员全部没有计算" */);
	}

}
