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.bs.framework.common.InvocationInfoProxy;
import nc.desktop.ui.ServerTimeProxy;
import nc.desktop.ui.WorkbenchEnvironment;
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.itf.uap.pa.IPreAlertService;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.wa.paydata.DataVO;
import nc.vo.wa.pub.WaLoginContext;
import nc.vo.wa.pub.WaLoginVOHelper;
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.hrwa.helper.WaLoginContextUtils;
import nccloud.web.hrwa.paydata.util.WaPaydataUtil;
import nccloud.web.hrwa.pub.WaClassState;
import nccloud.web.uapbd.commons.web.ParamUtils;

/**
 * 发放数据
 * <p>
 * {@link nc.ui.wa.paydata.action.PayAction}
 * </p>
 * 
 * @author liuyuan
 * @date 2018-5-22
 */
public class WaPaydataPayAction extends HRCommonAction {

	/**
	 * 发放数据
	 * 
	 * @param arg0
	 *            请求参数，包含参数，year，period，pk_org，node_type
	 * @param uPayDate
	 *            发发时间
	 * @param payComment
	 *            发放说明
	 * @return
	 * @throws BusinessException
	 */
	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		ParamUtils param = new ParamUtils(request);
		UFDate payDate = null ;
		String uPayDateStr = param.getString("uPayDate", "");
		if(uPayDateStr.trim().length() == 13){
			payDate = new UFDate(Long.parseLong(uPayDateStr));
		}
		String payComment = param.getString("payComment", "");
		boolean sure = UFBoolean.valueOf(param.getString("sure", "false")).booleanValue();
		IPaydataManageService service = ServiceLocator
				.find(IPaydataManageService.class);

		WaLoginContext loginContext = WaLoginContextUtils.getWaLoginContext(param);
		// 判断薪资档案数据状态是否发生了改变20200410
		new WaClassState().validateWaClassStatus(loginContext, "pay");
		JSONObject result = new JSONObject();
		if(!sure){
			if ((payDate == null) && (payComment == null || payComment.trim().length() < 1)) {
				// 没有输入发放日期和发放原因，如果此次不输入，以后将不可修改，要继续吗？
				result.put("msg", ResHelper.getString("60130paydata", "060130paydata0489"));
				result.put("status", 300);
				return result;

			} else if (payDate == null) {
				// 没有输入发放日期，如果此次不输入，以后将不可修改，要继续吗？
				result.put("msg", ResHelper.getString("60130paydata", "060130paydata0345"));
				result.put("status", 300);
				return result;
			} else if (payComment == null || payComment.trim().length() < 1) {
				// 没有输入发放说明，如果此次不输入，以后将不可修改，要继续吗？
				result.put("msg", ResHelper.getString("60130paydata", "060130paydata0346"));
				result.put("status", 300);
				return result;
			}
		}

		Set<WaState> waStateSet = new HashSet<WaState>();
		waStateSet.add(WaState.CLASS_IS_APPROVED);
		waStateSet.add(WaState.CLASS_WITHOUT_PAY);
//		waStateSet.add(WaState.CLASS_ALL_PAY);
		loginContext.getWaLoginVO().getPeriodVO().setCpaydate(payDate);
		loginContext.getWaLoginVO().getPeriodVO().setVpaycomment(payComment);
		WaState state = loginContext.getWaLoginVO().getState();
		boolean isMUltClass = WaLoginVOHelper.isMultiClass(loginContext.getWaLoginVO());
		if(!waStateSet.contains(state) && !isMUltClass){
			throw new BusinessException(ResHelper.getString("60130payfile", "060130payfile0374")/*@res "该方案状态发生了变化，请刷新！"*/);
//			result.put("status", 300);
//			result.put("msg", "按钮不可用!\n 数据状态:"+state.getDescription() + ",是否汇总:" + isMUltClass/*@res "发放操作成功。"*/);
//			return result ;
		}
		
		JSONObject prealerJson = new JSONObject() ;
		List<String> files = WaPaydataUtil.getMessageAlertFileNameByButton(loginContext,"", WaPaydataUtil.PK_BTN_PAY);
		if(files.size() > 0){
			prealerJson.put("itemPrealerJson", files) ;
		}
		
		//add by@chenzf薪资项目发放控制功能 2021-3-17 21:13:16 begin
		boolean isRangeAll = UFBoolean.valueOf(param.getString("isRangeAll", "true")).booleanValue();
		String whereCondition = isRangeAll ? null : WaPaydataQueryHelper.getWhereCondition(param);
		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
		
		service.onPay(loginContext);
		
		// 先查询是否有配置预警,如果有预警,则调预警的代码.2021-4-26 11:16:23 begin
//		try {
//			IPreAlertService pa = ServiceLocator.find(IPreAlertService.class);
//			pa.getMessageAlertFileNameByEnter(loginContext.getPk_group(), 
//					WaPaydataUtil.FUNC_CODE, loginContext.getPk_org(), 
//					new UFDate(InvocationInfoProxy.getInstance().getBizDateTime()), 
//					InvocationInfoProxy.getInstance().getUserDataSource(), 
//					InvocationInfoProxy.getInstance().getUserId());
//			pa.showMessageAlertFileNameByButton(loginContext.getPk_group(),  
//					new UFDate(InvocationInfoProxy.getInstance().getBizDateTime()), 
//					InvocationInfoProxy.getInstance().getUserDataSource(), 
//					WaPaydataUtil.PK_BTN_PAY, 
//					getUserData(loginContext,whereCondition));
//		}catch(Exception ex){
//			ex.printStackTrace();
//		}
		// 先查询是否有配置预警,如果有预警,则调预警的代码.2021-4-26 11:16:23 end
		
		result.put("prealerJson", prealerJson);
		result.put("status", 200);
		result.put("msg", ResHelper.getString("60130paydata","060130paydata0518")/*@res "发放操作成功。"*/);
		
		return result;
	}
	
	protected Object getUserData(WaLoginContext loginContext,String whereCondition) {
	  String[] userData = new String[6];
	  
	  userData[0] = loginContext.getCyear();
	  userData[1] = loginContext.getCyear();
	  userData[2] = loginContext.getPk_wa_class();
	  userData[3] = loginContext.getPk_group();
	  userData[4] = loginContext.getPk_org();
	  
	  userData[5] = whereCondition;
	  
	  return userData;
	}
	
	/**
	 * 创建日期：(2003-11-14 11:05:43)
	 */
//	public void showAlertInfo(String[] files) {
//		try {
//			// nc.ui.pub.MainFrame.initAlertInfo()弹出.html信息的方法.
//			if (files != null) {
//				for (String file : files) {
//
//					// 5.0预警显示HTML文件的方法
//					String serverURL = ClientAssistant.getServerURL();
//					java.net.URL url = new java.net.URL(serverURL
//							+ "NCFindWeb?service=prealert&filename="
//							// + "PreAlart/Messages/" + files[i]);
//							// //这个即为文件的名字(不包含路径)
//							+ file);
//					ClientAssistant.showDocument(url, "_blank");
//
//					// 3.5预警显示HTML文件方法
//					// java.net.URL url = new
//					// java.net.URL(nc.ui.sm.cmenu.Desktop
//					// .getApplet().getServerURL()
//					// + files[i]);
//					// nc.ui.sm.cmenu.Desktop.getApplet().getAppletContext()
//					// .showDocument(url, "_blank");
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			Logger.info(nc.ui.ml.NCLangRes.getInstance().getStrByID(
//					"60131004", "UPP60131004-000216")/*
//													 * @res "弹出预警信息时出错,请刷新后再试!"
//													 */+e.getMessage());
//		}
//	}

}
