package nccloud.web.hryf.psninfoapprove.action;

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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.logging.Logger;
import nc.hr.utils.ResHelper;
import nc.itf.hr.infoset.IInfoSetQry;
import nc.vo.hr.infoset.InfoSetVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.BusinessRuntimeException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.uif2.LoginContext;
import nccloud.commons.lang.StringUtils;
import nccloud.dto.hryf.appconf.AppConfItemVO;
import nccloud.dto.hryf.appconf.AppConfSetVO;
import nccloud.dto.hryf.psninfo.PsnInfoApproveVO;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.ui.config.PageTemplet;
import nccloud.framework.web.ui.pattern.form.Form;
import nccloud.framework.web.ui.pattern.grid.Grid;
import nccloud.itf.hryf.appconf.IAppconfService;
import nccloud.itf.hryf.psninfoapprove.IPsninfoApproveService;
import nccloud.vo.hr.json.HRJsonUtils;
import nccloud.web.hr.pub.HRCommonAction;
import nccloud.web.hr.pub.HRNccTemplateUtils;
import nccloud.web.hr.pub.HRNccUtils;
import nccloud.web.hryf.psninfoapprove.util.PsninfoApproveUtils;
import nccloud.web.uapbd.commons.web.ParamUtils;

/**
 * 员工信息审核【详情】操作
 * 
 * @author tianxfc
 *
 */
public class PsninfoApproveDetailAction extends HRCommonAction {
	private static final String pageCode = "600920A0nccloud"; // 员工信息审核页面编码
	private static final String areaCode = "psninfoappform"; // 员工信息审核详情表头模版id

	private static final String tempAppCode = "60651010"; // 自助应用-人员自助应用-部门人员信息应用编码
	private static final String tempPageCode = "60651010nccloud"; // 自助应用-人员自助应用-部门人员信息页面编码

	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ParamUtils param = new ParamUtils(request);
		LoginContext context = HRNccUtils.getLoginContext(param);
		String pk_org = param.getString("pk_org", null);
		if (StringUtils.isEmpty(pk_org)) {
			throw new BusinessRuntimeException(ResHelper.getString("6001uif2", "06001uif20070")/* @res 请先选择人力资源组织！ */);
		}
		String pk_psninfoapprove = param.getString("pk_psninfoapprove", null);
		if (StringUtils.isEmpty(pk_psninfoapprove)) {
			throw new BusinessException(ResHelper.getString("6008hrgx", "06008hrgx0007")/* @res "参数不能为空！" */);
		}

		// 查询员工信息审核vo
		PsnInfoApproveVO vo = ServiceLocator.find(IPsninfoApproveService.class).queryByPk(pk_psninfoapprove);
		if (vo == null) {
			map.put("data", null);
			return map;
		}

		// 信息集
		String condition = " pk_infoset = '" + vo.getPk_infoset() + "'";
		InfoSetVO[] infosets = ServiceLocator.find(IInfoSetQry.class).queryInfoSet(context, condition);
		// 信息集编码
		String infoset_code = null;
		// 信息集名称
		String infoset_name = null;
		String vo_class_name = null;
		if (infosets != null && infosets.length > 0) {
			infoset_code = infosets[0].getInfoset_code();
			infoset_name = infosets[0].getInfoset_name();
			vo_class_name = infosets[0].getVo_class_name();
		}
		List<AppConfSetVO> appConflist = ServiceLocator.find(IAppconfService.class).queryAppConfSetVOByCond(pk_org, infoset_code);
		if (appConflist == null || appConflist.isEmpty()) {
			throw new BusinessException(ResHelper.getString("6008hrgx", "06008hrgx0027")
			/* @res "个人信息项配置数据为空！" */);
		}
		// 获取个人信息模版
		PageTemplet pt = PsninfoApproveUtils.getPageTemplet(tempAppCode, tempPageCode);
		pt = PsninfoApproveUtils.filteByAppConfSet(pt, pk_org, infoset_code);

		// 组装要显示的信息集的信息项数据字典，key：信息项编码code， value：信息项的名称name
		Map<String, String> codeMap = new HashMap<String, String>();
		codeMap.put("status", ResHelper.getString("6008hrgx", "06008hrgx0028")
		/* @res "变更类型" */);
		// 修改前的信息集的数据集合
		// List<Map<String, String>> oldvoList = new ArrayList<Map<String, String>>();
		// 修改后的信息集的数据集合
		// List<Map<String, String>> newvoList = new ArrayList<Map<String, String>>();

		List<AppConfItemVO> itemList = appConflist.get(0).getItemList();
		if (itemList == null || itemList.isEmpty()) {
			throw new BusinessException(ResHelper.getString("6008hrgx", "06008hrgx0027")
			/* @res "个人信息项配置数据为空！" */);
		}
		for (AppConfItemVO itemvo : itemList) {
			UFBoolean entry_card_show_edit = itemvo.getEntry_card_show_edit() == null ? UFBoolean.FALSE : itemvo.getEntry_card_show_edit();
			UFBoolean unentry_card_show_edit = itemvo.getUnentry_card_show_edit() == null ? UFBoolean.FALSE : itemvo.getUnentry_card_show_edit();
			UFBoolean manager_card_show = itemvo.getManager_card_show() == null ? UFBoolean.FALSE: itemvo.getManager_card_show();

			if (entry_card_show_edit.booleanValue() || unentry_card_show_edit.booleanValue() || manager_card_show.booleanValue()) {
				if (!codeMap.containsKey(itemvo.getInfoset_item_code())) {
					codeMap.put(itemvo.getInfoset_item_code(), itemvo.getInfoset_item_name());
				}
			}
		}
		Class<?> clazzVO = null;
		try {
			clazzVO = Class.forName(vo_class_name);
		} catch (ClassNotFoundException ex) {
			Logger.error(ex);
		}
		// IJson json = JsonFactory.create();

		Form oldPsndocForm = null;
		Form newPsndocForm = null;
		Grid oldGrid = null;
		String oldValue = null;
		if (vo.getOldvalue() != null) {
			byte[] old = (byte[]) vo.getOldvalue();
			oldValue = new String(old);
			if (StringUtils.isNotEmpty(oldValue) && !"[null]".equals(oldValue)) {
				// 如果是人员基本信息
				if ("bd_psndoc".equals(infoset_code)) {
					// res = json2map(oldValue);
					SuperVO superVO = HRJsonUtils.fromJson(oldValue, clazzVO);
					// 组装要显示的信息集的信息项数据字典，key：信息项编码code， value：信息项的值value
					Map<String, String> valueMap = new HashMap<String, String>();
					String[] attrs = superVO.getAttributeNames();
					for (String code : attrs) {
						if (codeMap.containsKey(code)) {
							if (superVO.getAttributeValue(code) != null) {
								valueMap.put(code, superVO.getAttributeValue(code).toString());
							}
						}
					}
					// oldvoList.add(valueMap);
					oldPsndocForm = HRNccTemplateUtils.getFormWithArea(tempAppCode, tempPageCode, infoset_code, superVO);
				} else {
					// 如果是人员基本信息子集
					List<SuperVO> oldSubVOList = new ArrayList<SuperVO>();
					if (StringUtils.isNotEmpty(oldValue)) {
						JSONArray jsonArray = (JSONArray) JSONArray.parse(oldValue);
						if (jsonArray != null && jsonArray.size() > 0) {
							for (Object obj : jsonArray) {
								if (obj != null) {
									JSONObject jo = (JSONObject) obj;
									String joStr = jo.toString();
									SuperVO superVO = HRJsonUtils.fromJson(joStr, clazzVO);
									oldSubVOList.add(superVO);
								}
							}
						}
					}
					if (oldSubVOList != null && !oldSubVOList.isEmpty()) {
						SuperVO[] chgedVOs = filterOldNoChangVO(oldSubVOList.toArray(new SuperVO[0]));
						if(chgedVOs!=null&&chgedVOs.length>0){
							oldGrid = HRNccTemplateUtils.getGridWithArea(tempAppCode, tempPageCode, infoset_code,chgedVOs);
						}
					}
				}

			}
		}

		Grid newGrid = null;
		String newValue = null;
		if (vo.getNewvalue() != null) {
			byte[] newb = (byte[]) vo.getNewvalue();
			newValue = new String(newb);
			if (StringUtils.isNotEmpty(newValue) || !"[null]".equals(newValue)) {
				if ("bd_psndoc".equals(infoset_code)) {
					// 如果是人员基本信息
					// res = json2map(newValue);
					SuperVO superVO = HRJsonUtils.fromJson(newValue, clazzVO);
					// 组装要显示的信息集的信息项数据字典，key：信息项编码code， value：信息项的值value
					Map<String, String> valueMap = new HashMap<String, String>();
					String[] attrs = superVO.getAttributeNames();
					// 人员基本信息新增和删除不做处理
					valueMap.put("status", ResHelper.getString("6008hrgx", "06008hrgx0029")
					/* @res "更新" */);
					for (String code : attrs) {
						if (codeMap.containsKey(code)) {
							if (superVO.getAttributeValue(code) != null) {
								valueMap.put(code, superVO.getAttributeValue(code).toString());
							}
						}
					}
					// newvoList.add(valueMap);
					newPsndocForm = HRNccTemplateUtils.getFormWithArea(tempAppCode, tempPageCode, infoset_code, superVO);
				} else {
					// 如果是人员基本信息子集
					List<SuperVO> newSubVOList = new ArrayList<SuperVO>();
					if (StringUtils.isNotEmpty(newValue)) {
						JSONArray jsonArray = (JSONArray) JSONArray.parse(newValue);
						if (jsonArray != null && jsonArray.size() > 0) {
							for (Object obj : jsonArray) {
								if (obj != null) {
									JSONObject jo = (JSONObject) obj;
									String joStr = jo.toString();
									SuperVO superVO = HRJsonUtils.fromJson(joStr, clazzVO);
									newSubVOList.add(superVO);
								}
							}
						}
					}
					if (newSubVOList != null && !newSubVOList.isEmpty()) {
						SuperVO[] chgedVOs = filterNoChangVO(newSubVOList.toArray(new SuperVO[0]));
						if(chgedVOs!=null&&chgedVOs.length>0){
							newGrid = HRNccTemplateUtils.getGridWithArea(tempAppCode, tempPageCode, infoset_code, chgedVOs);
						}
					}
				}
			}
		}
		vo.setOldvalue(null);
		vo.setNewvalue(null);
		Form form = HRNccTemplateUtils.getFormWithArea(pageCode, areaCode, vo);
		map.put("headform", form);
		map.put("ptArea", pt);
		map.put("infoset_code", infoset_code);
		map.put("infoset_name", infoset_name);

		Map<String, Form> formMap = new HashMap<String, Form>();
		formMap.put("oldForm", oldPsndocForm);
		formMap.put("newForm", newPsndocForm);
		map.put("formMap", formMap);

		Map<String, Grid> gridMap = new HashMap<String, Grid>();
		gridMap.put("oldGrid", oldGrid);
		gridMap.put("newGrid", newGrid);
		map.put("gridMap", gridMap);
		return map;
	}
	
	//过滤掉没变化的数据
	private SuperVO[] filterNoChangVO(SuperVO[] vos) {
		List<SuperVO> list = new ArrayList<>();
		for(int i=0;vos!=null&&i<vos.length;i++){
			if(vos[i].getStatus()==VOStatus.UNCHANGED){
				continue;
			}
			list.add(vos[i]);
		}
		return list.toArray(new SuperVO[0]);
	}
	
	//过滤掉没变化的数据
	private SuperVO[] filterOldNoChangVO(SuperVO[] vos) {
		List<SuperVO> list = new ArrayList<>();
		for(int i=0;vos!=null&&i<vos.length;i++){
//			if(vos[i].getStatus()==VOStatus.UNCHANGED){
//				continue;
//			}
			list.add(vos[i]);
		}
		return list.toArray(new SuperVO[0]);
	}
}