package nccloud.web.hr.rpt.action;

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

import nc.bs.logging.Logger;
import nc.hr.utils.ResHelper;
import nc.itf.hr.wa.IClassitemQry;
import nc.itf.hr.wa.IPaydataQueryService;
import nc.itf.hr.wa.IWaClass;
import nc.itf.hr.wa.IWaProviderService;
import nc.itf.hr.wa.IWaPub;
import nc.itf.org.IOrgConst;
import nc.vo.bd.pub.NODE_TYPE;
import nc.vo.hr.tools.pub.GeneralVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.BusinessRuntimeException;
import nc.vo.uif2.LoginContext;
import nc.vo.wa.category.WaClassVO;
import nc.vo.wa.classitem.WaClassItemVO;
import nc.vo.wa.item.WaItemVO;
import nc.vo.wa.paydata.WaClassItemShowInfVO;
import nc.vo.wa.paydata.WaPaydataDspVO;
import nc.vo.wa.pub.PeriodStateVO;
import nc.vo.wa.pub.WaLoginContext;
import nc.vo.wa.pub.WaLoginVO;
import nc.wa.smartmodel.provider.util.WaGlobalVO;
import nc.wa.smartmodel.provider.util.WaProviderConst;
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.framework.web.ui.model.row.Cell;
import nccloud.framework.web.ui.model.row.Row;
import nccloud.framework.web.ui.pattern.form.Form;
import nccloud.web.hr.pub.HRCommonAction;
import nccloud.web.hr.pub.HRNccTemplateUtils;
import nccloud.web.hr.pub.HRNccUtils;
import nccloud.web.hr.rpt.pub.INccHrRptConst;
import nccloud.web.hrhi.pub.PsndocTempUtils;
import nccloud.web.hrwa.helper.WaLoginContextUtils;
import nccloud.web.hrwa.paydata.action.WaPaydataClassItemHelper;
import nccloud.web.uapbd.commons.web.ParamUtils;

/**
 * 编辑后事件
 */
public class WaRptQryAfterEditAction extends HRCommonAction {

	@Override
	public <T> Object execute(IRequest iRequest, T t) throws Exception {
		ParamUtils param = new ParamUtils(iRequest);
		LoginContext loginContext = HRNccUtils.getLoginContext(param);
		WaLoginContext context = WaLoginContextUtils.getWaLoginContext(param);

		String areaCode = param.getString("area_code", null);
		if (StringUtils.isBlank(areaCode)) {
			throw new BusinessRuntimeException("Parameter Error!");
		}

		String itemKey = param.getString("key", null);
		if (StringUtils.isBlank(itemKey)) {
			throw new BusinessRuntimeException("Parameter Error!");
		}
		HashMap result = new HashMap();
		// model参数
		GeneralVO vo = HRNccTemplateUtils.getVOFromForm(GeneralVO.class, PsndocTempUtils.getModelStr(param, null));
		if ("WaAccountByYearQueryConditionPanel".equals(areaCode)) {
			// 单位年度工资台账
			if (WaProviderConst.WA_CLASS_PK.equals(itemKey)) {
				String waClassPk = (String) vo.getAttributeValue(WaProviderConst.WA_CLASS_PK);
				WaClassVO waclassVO;
				String Cyear = "";
				waclassVO = getWaClass(waClassPk);
				if (null != waclassVO) {
					Cyear = waclassVO.getCyear();
				}
				vo.setAttributeValue(WaProviderConst.BASE_CYEAR, Cyear);
				Form form = HRNccTemplateUtils.getFormWithArea(INccHrRptConst.TEMPLET_WARPT_GRP, areaCode, vo);
				if (form != null && form.getModel() != null && form.getModel().getRows() != null && form.getModel().getRows().length > 0) {
					for (Row row : form.getModel().getRows()) {
						Cell cell = row.getCell(WaProviderConst.BASE_CYEAR);
						if (cell != null) {
							cell.setDisplay((String) cell.getValue());
						}
					}
				}
				result.put("form", form);
				WaGlobalVO waGlobalVO = new WaGlobalVO();
				waGlobalVO.setWaClassPK(waClassPk);
				waGlobalVO.setWaYear(Cyear);
				result.put("item_list", getItemList(waGlobalVO, 0));
				extracted(result, vo,context);
				return result;
			}
		} else if ("WaItemQueryConditionPanelForGroup".equals(areaCode) || "WaBaseQueryConditionPanel".equals(areaCode) || "WaSumByPsnclQueryConditionPanel".equals(areaCode)
				|| "WaSumByDeptQueryConditionPanel".equals(areaCode) || "WaItemQueryConditionPanel".equals(areaCode)) {
			// 集团级薪资明细表&薪资变动***表&人员类别汇总表&部门汇总表&薪资明细表
			if (WaProviderConst.WA_CLASS_PK.equals(itemKey)) {
				String waClassPk = (String) vo.getAttributeValue(WaProviderConst.WA_CLASS_PK);
				WaClassVO waclassVO;
				String Cperiod = "";
				waclassVO = getWaClass(waClassPk);
				if (waclassVO != null) {
					Cperiod = waclassVO.getCyear() + waclassVO.getCperiod();
				}
				vo.setAttributeValue(WaProviderConst.BASE_CPERIOD, null);
				vo.setAttributeValue(WaProviderConst.COMPARE_CPERIOD, Cperiod);
				Form form = HRNccTemplateUtils
						.getFormWithArea("WaItemQueryConditionPanelForGroup".equals(areaCode) ? INccHrRptConst.TEMPLET_WARPT_GRP : INccHrRptConst.TEMPLET_WARPT_ORG, areaCode, vo);
				if (form != null && form.getModel() != null && form.getModel().getRows() != null && form.getModel().getRows().length > 0) {
					for (Row row : form.getModel().getRows()) {
						Cell cell = row.getCell(WaProviderConst.COMPARE_CPERIOD);
						if (cell != null) {
							cell.setDisplay((String) cell.getValue());
						}
					}
				}
				result.put("form", form);
				return result;
			} else if (WaProviderConst.BASE_CPERIOD.equals(itemKey)) {
				String baseCperiod = (String) vo.getAttributeValue(WaProviderConst.BASE_CPERIOD);
				String waClassPk = (String) vo.getAttributeValue(WaProviderConst.WA_CLASS_PK);
				WaGlobalVO waGlobalVO = null;
				if (baseCperiod != null && baseCperiod.length() == 6) {
					String m_waYear = baseCperiod.substring(0, 4);
					String m_waPeriod = baseCperiod.substring(4, baseCperiod.length());
					// 设置薪资类别参数
					waGlobalVO = new WaGlobalVO();
					waGlobalVO.setWaClassPK(waClassPk);
					waGlobalVO.setWaYear(m_waYear);
					waGlobalVO.setWaPeriod(m_waPeriod);
					waGlobalVO.setCurPk_org(loginContext.getPk_org());
					waGlobalVO.setCurUserid(loginContext.getPk_loginUser());
				}
				result.put("item_list", getItemList(waGlobalVO, 0));
				extracted(result, vo,context);
				if ("WaBaseQueryConditionPanel".equals(areaCode) || "WaSumByDeptQueryConditionPanel".equals(areaCode) || "WaItemQueryConditionPanel".equals(areaCode)) {
					// 这三个要查询数值型薪资项目和字符型薪资项目
					IPaydataQueryService service = ServiceLocator.find(IPaydataQueryService.class);
					String m_waYear = baseCperiod.substring(0, 4);
					String m_waPeriod = baseCperiod.substring(4, baseCperiod.length());
					WaLoginContext waLoginContext = getWaLoginContext(loginContext.getPk_group(), loginContext.getPk_org(), m_waYear, m_waPeriod, waClassPk, null, null, null, null,
							"");// 补发期间参数
					WaClassItemVO[] itemVOs = service.getUserClassItemVOs(waLoginContext);
					// 用户对该方案下所有项目都没有权限的时候，就会NULL
					if (!ArrayUtils.isEmpty(itemVOs)) {
						List<Map<String, Object>> numlist = new ArrayList<>();
						List<Map<String, Object>> stringlist = new ArrayList<>();
						result.put("numlist", numlist);
						result.put("stringlist", stringlist);
						for (WaClassItemVO item : itemVOs) {
							Map<String, Object> headMap = new LinkedHashMap<>();
							headMap.put("attrcode", item.getItemkey());
							headMap.put("datatype", item.getIitemtype());
							headMap.put("label", item.getName());
							headMap.put("scale", item.getIflddecimal());
							headMap.put("maxlength", item.getIfldwidth());
							if (item.getIitemtype() == 0) {
								// 数字型
								numlist.add(headMap);
							} else if (item.getIitemtype() == 1) {
								// 字符型
								stringlist.add(headMap);
							}
						}
					}
				}
				return result;
			}

		} else if ("WaAccountByMonthQueryConditionPanel".equals(areaCode)) {
			// 年度对比分析
			if (WaProviderConst.WA_CLASS_PK.equals(itemKey)) {
				String waClassPk = (String) vo.getAttributeValue(WaProviderConst.WA_CLASS_PK);
				WaClassVO waclassVO;
				String Cyear = "";
				waclassVO = getWaClass(waClassPk);
				if (waclassVO != null) {
					Cyear = waclassVO.getCyear();
				}
				vo.setAttributeValue(WaProviderConst.BASE_CYEAR, null);
				vo.setAttributeValue(WaProviderConst.COMPARE_CYEAR, Cyear);
				Form form = HRNccTemplateUtils.getFormWithArea(INccHrRptConst.TEMPLET_WARPT_GRP, areaCode, vo);
				if (form != null && form.getModel() != null && form.getModel().getRows() != null && form.getModel().getRows().length > 0) {
					for (Row row : form.getModel().getRows()) {
						Cell cell = row.getCell(WaProviderConst.COMPARE_CYEAR);
						if (cell != null) {
							cell.setDisplay((String) cell.getValue());
						}
					}
				}
				result.put("form", form);
				WaGlobalVO waGlobalVO = new WaGlobalVO();
				waGlobalVO.setWaClassPK(waClassPk);
				waGlobalVO.setWaYear(Cyear);
				result.put("item_list", getItemList(waGlobalVO, 0));
				extracted(result, vo,context);
				return result;
			}
		} else if ("WaMultiRptQueryConditionPanel".equals(areaCode)) {
			if (WaProviderConst.WA_CLASS_PK.equals(itemKey)) {
				String curUserid = loginContext.getPk_loginUser();
				String m_waYear = (String) vo.getAttributeValue(WaProviderConst.CAC_CYEAR);
				String m_waPeriod = (String) vo.getAttributeValue(WaProviderConst.CAC_CPERIOD);
				if (m_waPeriod != null && m_waPeriod.trim().length() == 1) {
					m_waPeriod = "0" + m_waPeriod.trim();
				}
				String pk_org = loginContext.getPk_org();
				String classPKs = (String) vo.getAttributeValue(WaProviderConst.WA_CLASS_PK);
				if (StringUtils.isBlank(classPKs)) {
					//
					return result;
				}
				String[] waClassPks = classPKs.split(",");
				// 设置薪资类别参数
				WaGlobalVO[] waGlobalVOs = new WaGlobalVO[waClassPks.length];
				for (int i = 0; i < waClassPks.length; i++) {
					waGlobalVOs[i] = new WaGlobalVO();
					waGlobalVOs[i].setCurUserid(curUserid);
					waGlobalVOs[i].setCurPk_org(pk_org);
					waGlobalVOs[i].setWaClassPK(waClassPks[i]);
					waGlobalVOs[i].setWaYear(m_waYear);
					waGlobalVOs[i].setWaPeriod(m_waPeriod);
				}
				WaItemVO[] items = ServiceLocator.find(IClassitemQry.class).queryItemInfoWithPowerForMutiClasses(waGlobalVOs, 0);
				result.put("item_list", createList(items));
				extracted(result, vo,context);
				return result;
			}
		} else if ("OrgWaAccountQueryConditionPanel".equals(areaCode) || "DeptWaAccountQueryConditionPanel".equals(areaCode)) {
			// 单位薪资和部门信息
			if (WaProviderConst.CAC_CYEAR.equals(itemKey)) {
				// 存在一个校验
				GeneralVO[] generalVOs = null;
				try {
					generalVOs = ServiceLocator.find(IWaProviderService.class).getAllTmItem(loginContext.getPk_group(), loginContext.getPk_org(),
							(String) vo.getAttributeValue(WaProviderConst.CAC_CYEAR));
				} catch (BusinessException e) {
					Logger.error(e.getMessage(), e);
				}
				if (ArrayUtils.isEmpty(generalVOs)) {
					// 前端提示错误,清空年度输入框
					result.put("err_msg", ResHelper.getString("6013report", "06013report0036")/* @res "薪资总额项目数据不能为空！" */);
					vo.setAttributeValue(WaProviderConst.CAC_CYEAR, null);
					result.put("form", HRNccTemplateUtils.getFormWithArea(INccHrRptConst.TEMPLET_WARPT_ORG, areaCode, vo));
				}
				return result;
			}
		}
		
		return result;
	}

	private void extracted(HashMap result, GeneralVO vo,WaLoginContext context) throws BusinessException {
		//add by@chenzf 添加薪资发放设置的通用项目 2022-5-23 17:49:52 begin 
		if(result.get("item_list") != null) {
			List<Map> map = (List<Map>) result.get("item_list");
			List<Map> dmap = new ArrayList();//待选
			List<Map> ymap = new ArrayList();//已选
			if(map.size() > 0) {
				String waClassPk = (String) vo.getAttributeValue(WaProviderConst.WA_CLASS_PK);
				String baseCperiod = (String) vo.getAttributeValue(WaProviderConst.BASE_CPERIOD);
				WaLoginVO waLoginVO = null;
				if (baseCperiod != null && baseCperiod.length() == 6) {
					String m_waYear = baseCperiod.substring(0, 4);
					String m_waPeriod = baseCperiod.substring(4, baseCperiod.length());
					// 设置薪资类别参数
					waLoginVO = new WaLoginVO();
					waLoginVO.setPk_wa_class(waClassPk);
					waLoginVO.setPk_prnt_class(waClassPk);
					waLoginVO.setCyear(m_waYear);
					waLoginVO.setCperiod(m_waPeriod);
					waLoginVO.setPk_org(context.getPk_org());
					waLoginVO.setPk_group(context.getPk_group());
					context.setWaLoginVO(waLoginVO);
				}
				List<WaPaydataDspVO> list = ServiceLocator.find(IClassitemQry.class).queryWaPaydataDspVOByPkWaClass(waClassPk);
				if(list != null && list.size() > 0) {
					List<String> keyList = new ArrayList();
					for(WaPaydataDspVO dspVO : list) {
						keyList.add(dspVO.getItem_key());
					}
					for(String key : keyList) {
						for(Map m : map) {
							if(key.equals(m.get("itemkey"))) {
								ymap.add(m);
							}
						}
					}
					for(Map m : map) {
						if(keyList.contains(m.get("itemkey"))) {
//							ymap.add(m);
						} else {
							dmap.add(m);
						}
					}
				}
//				WaClassItemVO[] waClassItemVO = ServiceLocator.find(IClassitemQry.class).getUserShowClassItemVOs(context);
//				if(list != null && list.size() > 0) {
//					List<String> keyList = new ArrayList();
//					if(waClassItemVO != null && waClassItemVO.length > 0) {
//						for(WaClassItemVO item : waClassItemVO) {
//							for(WaPaydataDspVO dspVO : list) {
//								if(item.getItemkey().equals(dspVO.getItem_key())) {
//									keyList.add(item.getItemkey());
//								}
//							}
//						}
//					}
//					for(String key : keyList) {
//						for(Map m : map) {
//							if(key.equals(m.get("itemkey"))) {
//								ymap.add(m);
//							}
//						}
//					}
//					for(Map m : map) {
//						if(keyList.contains(m.get("itemkey"))) {
////							ymap.add(m);
//						} else {
//							dmap.add(m);
//						}
//					}
//				}
			}
			result.put("item_list", dmap);
			result.put("yitem_list", ymap);
		}
		//add by@chenzf 添加薪资发放设置的通用项目 2022-5-23 17:49:52 end
	}

	private static WaLoginContext getWaLoginContext(String pk_group, String pk_org, String cyear, String cperiod, String pk_wa_class, String pk_sub_class, String pk_childclass,
			String batch, String reyear, String reperiod) throws BusinessException {
		if (StringUtils.isBlank(pk_sub_class)) // 如果没有多次发放，则为当前方案
			pk_sub_class = pk_wa_class;
		if (StringUtils.isBlank(pk_childclass)) // 如果没有多次发放，则为当前方案
			pk_childclass = pk_wa_class;
		Integer batchValue = StringUtils.isBlank(batch) ? 0 : Integer.valueOf(batch); // 第n次发放
		if (StringUtils.isBlank(pk_group)) // 所属集团
			pk_group = SessionContext.getInstance().getClientInfo().getPk_group();
		String pk_user = SessionContext.getInstance().getClientInfo().getUserid();
		// 设置组织类型
		NODE_TYPE nodeType = NODE_TYPE.ORG_NODE;
		if (StringUtils.isBlank(pk_org)) {
			throw new RuntimeException("Error Only4Dev:pk_org一定要传！！！！！！！！！！");
			// return null;
		} else if (IOrgConst.GLOBEORG.equals(pk_org)) {
			nodeType = NODE_TYPE.GLOBE_NODE;
		} else if (pk_org.equals(pk_group)) {
			nodeType = NODE_TYPE.GROUP_NODE;
		} else {
			nodeType = NODE_TYPE.ORG_NODE;
		}
		// 薪资上下文
		WaLoginContext context = new WaLoginContext();
		context.setPk_group(pk_group);
		context.setNodeType(nodeType);
		context.setPk_org(pk_org);
		context.setPkorgs(new String[] { pk_org });
		context.setPk_loginUser(pk_user);

		if (StringUtils.isBlank(cyear) || StringUtils.isBlank(cperiod))
			return context;
		// 期间状态
		PeriodStateVO periodStateVO = new PeriodStateVO();
		periodStateVO.setCyear(cyear);
		periodStateVO.setCperiod(cperiod);
		periodStateVO.setPk_wa_class(pk_childclass);
		// 薪资参数
		WaLoginVO waLoginVO = new WaLoginVO();
		waLoginVO.setPk_group(pk_group);
		waLoginVO.setPk_org(pk_org);
		waLoginVO.setPeriodVO(periodStateVO);
		waLoginVO.setCyear(cyear);
		waLoginVO.setCperiod(cperiod);
		waLoginVO.setPk_prnt_class(pk_wa_class);
		waLoginVO.setPk_wa_class(pk_childclass);

		// 期间状态
		try {
			IWaPub service = ServiceLocator.find(IWaPub.class);
			waLoginVO = service.getWaclassVOWithState(waLoginVO);
		} catch (BusinessException e) {
			Logger.error(e.getMessage(), e);
		} catch (Exception e1) {
			throw new BusinessException(ResHelper.getString("6013salarypmt", "06013salarypmt0295")/* @res "方案类型已发生改变需重新加载" */);
		}
		// 当选择非最新期间 查询状态后会变成最新期间
		waLoginVO.setCyear(cyear);
		waLoginVO.setCperiod(cperiod);
		waLoginVO.setBatch(batchValue);
		waLoginVO.setReyear(reyear);
		waLoginVO.setReperiod(reperiod);
		context.setWaLoginVO(waLoginVO);
		return context;
	}

	protected List<Map> createList(WaItemVO[] systemItemVOs) {
		List<Map> itemList = new ArrayList<>();
		for (int i = 0; systemItemVOs != null && i < systemItemVOs.length; i++) {
			Map m = new HashMap();
			m.put("key", systemItemVOs[i].getPk_wa_item());
			m.put("title", systemItemVOs[i].getName());
			m.put("code", systemItemVOs[i].getCode());
			m.put("itemkey", systemItemVOs[i].getItemkey());
			itemList.add(m);
		}
		return itemList;
	}

	private List<Map> getItemList(WaGlobalVO waGlobalVO, int type) throws BusinessException {
		WaItemVO[] systemItemVOs = ServiceLocator.find(IClassitemQry.class).queryItemInfoWithClass(waGlobalVO, type);
		return createList(systemItemVOs);
	}

	private WaClassVO getWaClass(String pk) {
		if (StringUtils.isBlank(pk)) {
			return null;
		}
		WaClassVO waclassVO = null;
		try {
			waclassVO = ServiceLocator.find(IWaClass.class).queryWaClassByPK(pk);
		} catch (Exception ex) {
			Logger.error(ex.getMessage(), ex);
			return null;
		}
		return waclassVO;
	}
}
