package nccloud.web.hrzz.psninfo.action;

import nc.hr.utils.HRFileUtils;
import nc.hr.utils.ResHelper;
import nc.itf.bd.pubinfo.IPubinfoService;
import nc.itf.hi.IPsndocQryService;
import nc.itf.hr.frame.IPersistenceRetrieve;
import nc.itf.hr.frame.IPersistenceUpdate;
import nc.vo.bd.address.AddressVO;
import nc.vo.hi.psndoc.PsndocAggVO;
import nc.vo.hi.psndoc.PsndocVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.BusinessRuntimeException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.uif2.LoginContext;
import nccloud.commons.lang.ArrayUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.dto.hryf.psninfo.PsnInfoApproveCheckEnum;
import nccloud.dto.hryf.psninfo.PsnInfoApproveVO;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.json.JsonFactory;
import nccloud.itf.hryf.psninfoapprove.IPsninfoApproveService;
import nccloud.itf.hrzz.pub.HRZZConst;
import nccloud.web.hr.pub.HRCommonAction;
import nccloud.web.hr.pub.HRNccTemplateUtils;
import nccloud.web.hr.pub.HRNccUtils;
import nccloud.web.hrzz.pub.util.HrzzPubUtils;
import nccloud.web.uapbd.commons.web.ParamUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息填写功能-【人员基本信息-查询】操作
 * 
 * @author tianxfc
 */
public class PsninfoQueryAction extends HRCommonAction {

	@Override
	public <T> Object execute(IRequest request, T para) throws Exception {
		ParamUtils param = new ParamUtils(request);
		LoginContext context = HRNccUtils.getLoginContext(param);
		// 获取用户ID
		String cuserid = context.getPk_loginUser();
		if (StringUtils.isEmpty(cuserid)) {
			throw new BusinessRuntimeException(ResHelper.getString("6065hrzz",
					"06065hrzz0016")/* @res "用户ID不能为空！" */);
		}
		// 获取人员信息
		PsndocAggVO psndocAgg = null;
		String pk_psndoc = param.getString("pk_psndoc", null);
		String areaCode = param.getString("areaCode", null);
		boolean isTeam ;
		if (StringUtils.isNotBlank(pk_psndoc)) {// pk_psndoc有值 表示是在我的团队中查看团队成员信息
			psndocAgg = ServiceLocator.find(IPsndocQryService.class).queryPsndocVOByPk(pk_psndoc);
			isTeam = true;
		} else { // 查看自己的信息
			psndocAgg = HrzzPubUtils.queryPsndocByUserID(cuserid);
			isTeam = false;
		}
		if (psndocAgg == null) {
			throw new BusinessRuntimeException(ResHelper.getString("6065hrzz",
					"06065hrzz0015")/* @res "没有找到对应的人员信息！" */);
		}
		PsndocVO psndocVO = psndocAgg.getParentVO();
		// 计算人员类别：1：在职人员；2：未入职人员； 3：我的团队
		int psntype = -1;
		if (StringUtils.isNotBlank(pk_psndoc)) {
			psntype = 3;
		} else {
			// 根据是否已转档判断是否在职人员
			UFBoolean indocFlag = psndocVO.getPsnOrgVO() == null ? null : psndocVO.getPsnOrgVO().getIndocflag();
			psntype = indocFlag != null && indocFlag.booleanValue() ? 1 : 2;
			pk_psndoc = psndocVO.getPk_psndoc();
		}
		// 取人员所属组织
		String pk_org = psndocVO.getPsnJobVO().getPk_hrorg();
		// 合并我的待审核的信息
		Map<String, String> hasSubmitMap = mergeSubmitInfos(pk_org, psndocVO);
		boolean hasSubmit = UFBoolean.valueOf((String) hasSubmitMap.get("mergeSubmit")).booleanValue();
		// 返回结果
		Map<String, Object> retMap = new HashMap<String, Object>();
		if (!hasSubmit) {
			Map<String, String> valiMap = getCheckstatus(pk_org, psndocVO);
			if (null != valiMap && !valiMap.isEmpty()) {
				String isapproved = valiMap.get("isapproved");
				if (null != isapproved && "Y".equals(isapproved)) {
					// 返回是否已审核标识：isapproved ：Y-审核通过 N-审核不通过
					retMap.put("isapproved", "Y");
				} else if (null != isapproved && "N".equals(isapproved)) {
					retMap.put("isapproved", "N");
				}
				// 个人信息审核数据主键
				retMap.put("pk_psninfoapprove", valiMap.get("pk_psninfoapprove"));
				// 审核信息
				retMap.put("checknote", valiMap.get("checknote"));
			}
		} else {
			if (psntype != 3) {
				retMap.put("pk_psninfoapprove", (String) hasSubmitMap.get("pk_psninfoapprove"));
			}
		}
		psndocVO.setPhoto(null);
	
		retMap.put("bd_psndoc", HRNccTemplateUtils.getFormWithArea(HRZZConst.APPCODE_DEPTPSNINFO,
				HRZZConst.PAGECODE_DEPTPSNINFO, PsndocVO.getDefaultTableName(), psndocVO));
		retMap.put("isedit", UFBoolean.valueOf(psntype != 3 && !hasSubmit).toString()); // 查本人信息且没有待审核时可编辑
		retMap.put("isneedapp", UFBoolean.valueOf(hasSubmit).toString());
		
		//返回子表审核信息
		Map<String, Object> voMap = ServiceLocator.find(IPsninfoApproveService.class).queryPsnInfoByTableCode(areaCode, psndocVO.getPk_psndoc(), isTeam);
		retMap.put("submitPsnInfos",voMap.get("submitPsnInfos"));
		//由于家庭地址审核问题，这里先复制一条数据，如果存在家庭地址修改则进行审核,审核通过后更新这条旧的数据
		if (psndocVO.getAddr() != null) {
			AddressVO addressVO = (AddressVO) ServiceLocator.find(IPersistenceRetrieve.class).retrieveByPk(null, AddressVO.class, psndocVO.getAddr());
			AddressVO tempVO = (AddressVO) ServiceLocator.find(IPersistenceRetrieve.class).retrieveByPk(null, AddressVO.class, psndocVO.getAddr().substring(0, 16) + "ABCD");
			if (addressVO != null) {
				if (tempVO == null && addressVO.getPk_address() != null) {
					addressVO.setPk_address(addressVO.getPk_address().substring(0, 16) + "ABCD");
					addressVO.setStatus(2);
					ServiceLocator.find(IPubinfoService.class).update(addressVO);
				}
			} else {
				if (!hasSubmit) {
					String whereCond = " pk_org = '" + pk_org
							+ "' and checkstatus = 1 and pk_infoset = '1002Z7100000000046GP' and pk_psndoc = '"
							+ psndocVO.getPk_psndoc() + "' order by ts desc ";
					PsnInfoApproveVO[] approveVOs = ServiceLocator.find(IPsninfoApproveService.class).queryByCondition(whereCond);
					if (approveVOs != null && approveVOs.length > 0) {
						String psnInfo = new String((byte[]) approveVOs[0].getNewvalue());
						PsndocVO newPsndocVO = JsonFactory.create().fromJson(psnInfo, PsndocVO.class);
						if (newPsndocVO.getAddr() != null) {
							ServiceLocator.find(IPersistenceUpdate.class).deleteVO(null, tempVO, null);
							addressVO.setPk_address(addressVO.getPk_address().substring(0, 16) + "ABCD");
							addressVO.setStatus(2);
							ServiceLocator.find(IPubinfoService.class).update(addressVO);
						}
					}
				}
			}
		}
		return retMap;
	}

	/**
	 *
	 * @param pk_org
	 * @param psndocVO
	 * @return
	 * @throws BusinessException
	 */
	private Map<String, String> getCheckstatus(String pk_org, PsndocVO psndocVO) throws BusinessException {
		Map<String, String> retMap = new HashMap<String, String>();
		// readstatus:预览状态 0-未读 1-已读
		String whereCond = " pk_org = '" + pk_org
				+ "' and checkstatus <> 0 and readstatus <> 1 and pk_infoset = '1002Z7100000000046GP' and pk_psndoc = '"
				+ psndocVO.getPk_psndoc() + "' order by ts desc ";
		PsnInfoApproveVO[] vos = ServiceLocator.find(IPsninfoApproveService.class).queryByCondition(whereCond);
		if (ArrayUtils.isEmpty(vos) || vos[0].getNewvalue() == null) {
			return null;
		}
		// 审核通过 并且 未读状态 返回isapproved 等于Y，如果是通过且已读，就不再返回【 预览状态 0-未读 1-已读】
		if (PsnInfoApproveCheckEnum.CHECK_SUCCESS.getIndex() == vos[0].getCheckstatus() ) {
			retMap.put("isapproved", "Y");
		} // 审核不通过
		else if (PsnInfoApproveCheckEnum.CHECK_FAIL.getIndex() == vos[0].getCheckstatus()) {
			retMap.put("isapproved", "N");
		}
		retMap.put("checknote", vos[0].getChecknote());
		retMap.put("pk_psninfoapprove", vos[0].getPk_psninfoapprove());
		return retMap;
	}

	/**
	 * 合并已提交的基本信息
	 * 
	 * @param pk_org
	 * @param psndocVO
	 * @return 是否有待审核的信息
	 * @throws BusinessException
	 */
	private Map<String, String> mergeSubmitInfos(String pk_org, PsndocVO psndocVO) throws BusinessException {
		Map<String, String> retMap = new HashMap<String, String>();
		String whereCond = " pk_org = '" + pk_org
				+ "' and checkstatus = 0 and pk_infoset = '1002Z7100000000046GP' and pk_psndoc = '"
				+ psndocVO.getPk_psndoc() + "'";
		PsnInfoApproveVO[] approveVOs = ServiceLocator.find(IPsninfoApproveService.class).queryByCondition(whereCond);
		if (ArrayUtils.isEmpty(approveVOs) || approveVOs[0].getNewvalue() == null) {
			retMap.put("mergeSubmit", "N");
			return retMap;
		}
		String psnInfo = new String((byte[]) approveVOs[0].getNewvalue());
		PsndocVO newPsndocVO = JsonFactory.create().fromJson(psnInfo, PsndocVO.class);
		if (newPsndocVO == null) {
			retMap.put("mergeSubmit", "N");
			return retMap;
		}
		retMap.put("pk_psninfoapprove", approveVOs[0].getPk_psninfoapprove());
		newPsndocVO.setPhoto(null);
		// 拷贝至原vo中
		String[] attrs = psndocVO.getAttributeNames();
		for (String attr : attrs) {
			if (PsndocVO.PK_PSNDOC.equals(attr) || "status".equals(attr)) {
				continue;
			}
			if (newPsndocVO.getAttributeValue(attr) == null) {
				continue;
			}
			if ("photo".equals(attr) && newPsndocVO.getPhoto() != null) {
				if (newPsndocVO.getPhoto().equals("cleanphoto")) {
					newPsndocVO.setPhoto(null);
				} else {
					newPsndocVO.setPhoto(HRFileUtils.base64Decode(newPsndocVO.getPhoto().toString()));
				}
			}
			psndocVO.setAttributeValue(attr, newPsndocVO.getAttributeValue(attr));
		}
		retMap.put("mergeSubmit", "Y");
		return retMap;
	}

}