package nccloud.web.hrwa.paydata.action;

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

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.IPsndocWa;
import nc.itf.hr.wa.IWaRuleExQueryService;
import nc.vo.hr.caculate.CaculateTypeVO;
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 nc.vo.wa.pub.WaState;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
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.uapbd.commons.web.ParamUtils;

/**
 * 计算
 * <p>
 * {@link nc.ui.wa.paydata.action.CaculateAction}
 * </p>
 * 
 * @author liuyuan
 * @date 2018-5-22
 */
public class WaPaydataCaculateAction extends HRCommonAction {

	/**
	 * @param request
	 *            请求参数，包含参数，year，period，pk_org，node_type
	 * @param range
	 *            重新计算范围设置，true为全部人员，false为部分人员
	 * @param type
	 *            是否全部重新计算，true范围内重新计算，false计算尚未计算的人员
	 */
	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		ParamUtils param = new ParamUtils(request);

		long t1 = System.currentTimeMillis();
		
		boolean type = UFBoolean.valueOf(param.getString("type", "true")).booleanValue();
		boolean range = UFBoolean.valueOf(param.getString("range", "true")).booleanValue();
		boolean sure = UFBoolean.valueOf(param.getString("sure", "")).booleanValue();

		JSONObject js = new JSONObject();
		WaLoginContext loginContext = WaLoginContextUtils.getWaLoginContext(param);
		boolean bool = ServiceLocator.find(IPsndocWa.class).isExistUnCaculatePsn(
				loginContext.getWaLoginVO(), null, null);
		
		
		Set<WaState> waStateSet = new HashSet<WaState>();
		waStateSet.add(WaState.CLASS_WITHOUT_RECACULATED);
		waStateSet.add(WaState.CLASS_RECACULATED_WITHOUT_CHECK);
		waStateSet.add(WaState.CLASS_PART_CHECKED);
		WaState state = loginContext.getWaLoginVO().getState();
		
		if(waStateSet.contains(state)){
			if(!sure && bool){
				String msg = ResHelper.getString("60130paydata","060130paydata0332")/*@res "有员工调薪，应先进行计算,是否继续?"*/;
				js.put("msg", msg);
				js.put("status", 300);
				return js ;
			}
			IPaydataManageService service = ServiceLocator
					.find(IPaydataManageService.class);
			
			//当前页数据，用于时间戳校验
			JSONObject jo = JSONObject.parseObject(request.read());
			DataVO[] dataVos = HRNccTemplateUtils.getVOFromGrid(DataVO.class, jo.getString("modelInfo"));
		
			CaculateTypeVO caculateTypeVO = new CaculateTypeVO();
			caculateTypeVO.setType(UFBoolean.valueOf(type));
			caculateTypeVO.setRange(UFBoolean.valueOf(range));
			String where = WaPaydataQueryHelper.getWhereCondition(param) ;
			
			//如果是全部计算，则不考录查询条件的问题
			if(range){
				where = null ;
			}
			service.onCaculate(loginContext, caculateTypeVO,where,dataVos);
			
			List<String> files = WaPaydataUtil.getMessageAlertFileNameByButton(loginContext, null, WaPaydataUtil.PK_BTN_CHECK);

			
			//add by@chenzf薪资项目发放控制功能 2021-3-17 21:13:16 begin
			IPaydataQueryService queryService = ServiceLocator.find(IPaydataQueryService.class);
			DataVO[] dataVOs = queryService.queryDataVOsByCond(loginContext, where, null);
			
			IWaRuleExQueryService iruleExService = ServiceLocator.find(IWaRuleExQueryService.class);
			List<Map<String, Object>> ruleMap = iruleExService.queryWageformExContral(loginContext);
			Map<String,String> tipMap = new HashMap();
			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);
//						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(check.booleanValue()) {
//							if(value.compareTo(upperlimit) > 0) {
//								msg = msg + itemMap.get(key).get(0)+",";
//							}
//						}
//					}
//					if(msg.length() > 0) {
//						tipMap.put(psncode+","+psnname, msg.substring(0, msg.length() - 1));
//					}
					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) {
							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;
			}
			
			//add by@chenzf薪资项目发放控制功能 2021-3-17 21:13:16 end
			
			long t2 = System.currentTimeMillis();
			UFDouble s = new UFDouble(t2-t1, -2).div(1000.0D).setScale(-3, UFDouble.ROUND_HALF_UP);
			js.put("status", 200);
			js.put("msg",ResHelper.getString("60130paydata","060130paydata0336")/*@res "在"*/ + s.toString() + ResHelper.getString("60130paydata","060130paydata0337")/*@res "秒内计算完成."*/);
			js.put("messageEx", message);
			
			
			List<String> list = WaPaydataUtil.getMessageAlertFileNameByButton(loginContext, where, WaPaydataUtil.PK_BTN_CACULATE);
			JSONObject prealerJson = new JSONObject() ;
			if( list.size()> 0){
				prealerJson.put("itemPrealerJson", list) ;
			}
			js.put("prealerJson", prealerJson);
			return js;
		} else {
			js.put("msg", "按钮不可用！");
			js.put("status", 300);
			return js ;
		}
	}
}
