package nc.net.uapbd.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bs.bd.baseservice.busilog.IBDBusiLogUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.uap.tools.formula.ExtFormulaParser;
import nc.itf.bd.psn.psndoc.IPsndocQueryService;
import nc.itf.bd.psnbankacc.IPsnBankaccQueryService;
import nc.itf.bd.psnbankacc.IPsnBankaccService;
import nc.itf.bd.psn.psndoc.IPsndocService;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.IVOPersistence;
import nc.itf.uap.rbac.IRoleManage;
import nc.itf.uap.rbac.IRoleManageQuery;
import nc.itf.uap.rbac.IUserManage;
import nc.itf.uap.rbac.IUserManageQuery;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.net.pu.utils.PubUtils;
import nc.net.servlet.NewEsbJsonServlet;
import nc.pub.sap.constant.SapConstants;
import nc.pubitf.para.SysInitQuery;
import nc.uapbd.service.rest.util.JsonTools;
import nc.vo.bd.bankaccount.BankAccSubVO;
import nc.vo.bd.bankaccount.BankAccbasVO;
import nc.vo.bd.bankdoc.BankdocVO;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.bd.psn.PsnjobVO;
import nc.vo.bd.psnbankacc.PsnBankaccUnionVO;
import nc.vo.bd.psnbankacc.PsnBankaccVO;
import nc.vo.esb.ResultVO;
import nc.vo.om.job.JobVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFLiteralDate;
import nc.vo.pub.para.SysInitVO;
import nc.vo.pubapp.AppContext;
import nc.vo.sap.log.SapPurchaseLogVO;
import nc.vo.sm.UserVO;
import nc.vo.uap.rbac.UserGroupVO;
import nc.vo.uap.rbac.role.RoleVO;
import nccloud.commons.lang.StringUtils;
import uap.json.JSONArray;
import uap.json.JSONObject;

public class MDG2NCCPsndocServelet extends NewEsbJsonServlet {


	private BaseDAO dao = null;
	private IPsndocQueryService iPsndocQueryService = null;
	private IUserManage userManageSerivce = null;
	private IRoleManageQuery roleManageQuery = null;
	private IRoleManage roleManageSercvice = null;
	private IBDBusiLogUtil busiLogUtil = null;

	private String pk_group = null;
	private String creater = null;
	private String code = null;
	private String bank = null;
	String uuid = null;
	String issuccess_sn = "Y";
	
	private IUserManage getUserManageSerivce() {
		if (userManageSerivce == null) {
			userManageSerivce = ((IUserManage)NCLocator.getInstance().lookup(IUserManage.class));
		}
		
		return userManageSerivce;
	}
	
	private BaseDAO getDao() {
		if (dao == null)
			dao = new BaseDAO();
		return dao;
	}
	
	private IRoleManageQuery getIRoleManageQuery() {
		if (roleManageQuery == null) {
			roleManageQuery = ((IRoleManageQuery)NCLocator.getInstance().lookup(IRoleManageQuery.class));
		}
		
		return roleManageQuery;
	}

	 private IRoleManage getIRoleManage() {
	 	if (roleManageSercvice == null) {
	 		roleManageSercvice = ((IRoleManage)NCLocator.getInstance().lookup(IRoleManage.class));
	 	}
	 	return roleManageSercvice;
	 }
	 
	@Override
	public void execFunction(HttpServletRequest request, HttpServletResponse response, JSONObject jsonobj)
			throws Exception {
		Map<String, Object> outlook = new HashMap<String, Object>();
		String puuid = jsonobj.getJSONObject("ESB").getJSONObject("DATA").getJSONObject("DATAINFOS").getString("PUUID");
		Map<String, String> successPsnCode = new HashMap<String, String>();
		ResultVO resultvo = new ResultVO();
		//wby 20211017 收集报文所有人员，用于记录在日志
		StringBuilder sb_psnCode = new StringBuilder();
		try {
			JSONArray items = new JSONArray(ReceiveUtils.convert2Array(
					(com.alibaba.fastjson.JSONObject.parseObject(jsonobj.toString())).getJSONObject("ESB")
							.getJSONObject("DATA").getJSONObject("DATAINFOS").getJSONArray("DATAINFO")
			).toString());

			Map<String, Map<String, Object>> mapItems = ReceiveUtils
					.convert2Map((com.alibaba.fastjson.JSONObject.parseObject(jsonobj.toString())).getJSONObject("ESB")
							.getJSONObject("DATA").getJSONObject("DATAINFOS").getJSONArray("DATAINFO")
					);
			pk_group = ((SysInitVO) ((ArrayList) NCLocator.getInstance().lookup(IUAPQueryBS.class)
					.retrieveByClause(SysInitVO.class, "initcode='GROUP'")).get(0)).getValue();
			creater = ((SysInitVO) ((ArrayList) NCLocator.getInstance().lookup(IUAPQueryBS.class)
					.retrieveByClause(SysInitVO.class, "initcode='ITFUSER'")).get(0)).getValue();
			ExtFormulaParser extFormulaParser = new ExtFormulaParser();

			//人员信息翻译配置
			HashMap<String, ArrayList<String>> formulaone = JsonTools.getFormulas("MDM2NccPsndoc", 0);
			if(formulaone == null) {
				throw new Exception( "人员基础信息翻译未配置（MDM2NccPsndoc），请先配置后再同步！");
			}
			
			//人员工作记录翻译配置
			HashMap<String, ArrayList<String>> formulaoneStation = JsonTools.getFormulas("MDM2NccRY", 0);
			if(formulaoneStation == null) {
				throw new Exception( "人员工作记录翻译未配置（MDM2NccRY），请先配置后再同步！");
			}
			
			ArrayList<String> formulas = formulaone.get(SapConstants.FORMULA_KEY);
			//按报文中每个人员处理
			mapItems.forEach((k, v) -> {
				try {
					String def1 = new JSONObject(k).getString("code");
					String pk_psncl = null;
					List<Map<String, Object>> list = Stream.of(v).collect(Collectors.toList());
					JSONArray item = new JSONArray(com.alibaba.fastjson.JSONObject
							.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(list)).toString());
					JSONArray stationItem = item.getJSONObject(0).getJSONArray("station");
					JSONObject psn = item.getJSONObject(0).getJSONObject("psn");
					JSONArray psnItem = new JSONArray();
					psnItem.put(psn);
					String sex = psn.getString("EMP_SEX") == null ? "" : psn.getString("EMP_SEX");
					if ("F".equalsIgnoreCase(sex)) {// MDG F为女，M为男
						sex = "2";
					} else if ("M".equalsIgnoreCase(sex)) {
						sex = "1";
					}
					
					List<CircularlyAccessibleValueObject> listDoc = JsonTools.setRecValues(
							(Class<? extends CircularlyAccessibleValueObject>) Class.forName("nc.vo.bd.psn.PsndocVO"),
							psnItem, formulaone);
					List<CircularlyAccessibleValueObject> listJob = JsonTools.setRecValues(
							(Class<? extends CircularlyAccessibleValueObject>) Class.forName("nc.vo.bd.psn.PsnjobVO"),
							stationItem, formulaoneStation);
					// update by guojx 添加岗位信息
					List<CircularlyAccessibleValueObject> listStation = JsonTools.setRecValues(
							(Class<? extends CircularlyAccessibleValueObject>) Class.forName("nc.vo.om.job.JobVO"),
							stationItem, formulaoneStation);
					extFormulaParser.execFormulas(formulas.toArray(new String[formulas.size()]),
							(CircularlyAccessibleValueObject[]) listJob
									.toArray(new CircularlyAccessibleValueObject[listJob.size()]));
					extFormulaParser.execFormulas(formulas.toArray(new String[formulas.size()]),
							(CircularlyAccessibleValueObject[]) listDoc
									.toArray(new CircularlyAccessibleValueObject[listDoc.size()]));
					CircularlyAccessibleValueObject docVO = listDoc.get(0);
					//人员编码
					String psnCode = (String) docVO.getAttributeValue("code");
					sb_psnCode.append(psnCode);
//					CircularlyAccessibleValueObject stationVO = listStation.get(0);
					String mrPsncl = getQueryVal(" select pk_psncl from bd_psncl where code='01' ");
					pk_psncl = mrPsncl;// 人员类别默认合同工
					Map<String, String> mapStatus = new HashMap<String, String>() {
						{
							put("0", "调岗");
							put("1", "试用");
							put("2", "转正");
						}
					};
					// 增加职务判断
					for (int i = 0; i < listJob.size(); i++) {
						String jobcode = (String) listStation.get(i).getAttributeValue("jobcode");
						List<JobVO> stations = (List<JobVO>) NCLocator.getInstance().lookup(IUAPQueryBS.class)
								.retrieveByClause(nc.vo.om.job.JobVO.class, "jobcode = '" + jobcode + "'");
						if (stations.size() > 0) {
							JobVO station = stations.get(0);
							// 如果不为空，为更新，jobVO要刷新时间
							String pk = station.getPrimaryKey();
							listStation.get(i).setPrimaryKey(pk);
							NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) listStation.get(i));
							listJob.get(i).setAttributeValue("pk_job", station.getAttributeValue("pk_job"));
						} else {
							NCLocator.getInstance().lookup(IVOPersistence.class).insertVO((SuperVO) listStation.get(i));
							JobVO newJob = ((List<JobVO>) NCLocator.getInstance().lookup(IUAPQueryBS.class)
									.retrieveByClause(nc.vo.om.job.JobVO.class, "jobcode = '" + jobcode + "'")).get(0);
							listJob.get(i).setAttributeValue("pk_job", newJob.getAttributeValue("pk_job"));// 给人员传职务信息
						}
						
						//任职记录任职公司处理
//						if(listJob.get(i).getAttributeValue("pk_org") == null) {
//							throw new Exception( "人员任职组织不能为空，请检查接口报文！");
//						}
						//人员所属公司处理
						if(docVO.getAttributeValue("pk_org") == null) {
							throw new Exception( "人员所属组织不能为空，请检查接口报文！");
						}
						
						String jobOrgCode = (String) docVO.getAttributeValue("pk_org");
						//wby 20211117 增加业务单元属性过滤，非业务单元没有关联部门
						String pk_org = getPKfromCode("org_orgs", "pk_org", "code", jobOrgCode, "isbusinessunit='Y'");
						if(StringUtils.isEmpty(pk_org)) {
							throw new Exception( "人员任职组织不存在，请先同步组织：" + jobOrgCode + ",人员编码:" + psnCode);
						}
						listJob.get(i).setAttributeValue("pk_org", pk_org);
						
						//任职记录任职部门处理
						if(psn.getString("NCC_FIN_DEPT_CODE") == null || "" == psn.getString("NCC_FIN_DEPT_CODE")) {
							throw new Exception( "人员任职部门编码NCC_FIN_DEPT_CODE不能为空，请检查接口报文！");
						}
						
						String jobDeptCode = psn.getString("NCC_FIN_DEPT_CODE");
//						String jobDeptCode = (String) listJob.get(i).getAttributeValue("pk_dept");
						//如果为空 后面要抛错
						String pk_dept = getQueryVal("select pk_dept from org_dept where code='" + jobDeptCode + "' and pk_org = '" + pk_org + "'");
						if(StringUtils.isEmpty(pk_dept)) {
							throw new Exception( "人员任职部门不存在，请先同步部门：" + jobDeptCode + ",人员编码:" + psnCode);
						}
						
						listJob.get(i).setAttributeValue("pk_dept", pk_dept);
						listJob.get(i).setAttributeValue("pk_group", pk_group);
						listJob.get(i).setAttributeValue("pk_psncl", pk_psncl);
						listJob.get(i).setAttributeValue("ismainjob",
								stationItem.getJSONObject(i).getInt("DESC5") == 1 ? "Y" : "N");
						listJob.get(i).setAttributeValue("psncode", psnCode);
						listJob.get(i).setAttributeValue("def10", mapStatus.get(listJob.get(i).getAttributeValue("def10")));

					}
					docVO.setAttributeValue("def1", def1);
					docVO.setAttributeValue("sex", sex);
					
					
					String orgCode = (String) docVO.getAttributeValue("pk_org");
					String pk_org = getPKfromCode("org_orgs", "pk_org", "code", orgCode, "isbusinessunit='Y'");
					if(StringUtils.isEmpty(pk_org)) {
						throw new Exception( "人员所属组织组织不存在，请先同步组织：" + orgCode + ",人员编码:" + psnCode);
					}
					
					docVO.setAttributeValue("pk_org", pk_org);
					docVO.setAttributeValue("pk_group", pk_group);
					if(docVO.getAttributeValue("def5") != null) {
						docVO.setAttributeValue("def5", docVO.getAttributeValue("def5").equals("A") ? "在职" : "离职");// 在岗状态
					}
					else {
						docVO.setAttributeValue("def5", "在职");
					}
					
					//生成人员
					StringBuffer error = new StringBuffer();
					error = handlePsn(psnCode, listJob, listDoc, docVO, error);
					if(!StringUtils.isEmpty(error.toString())) {
						issuccess_sn = "N";
						outlook.put(k, "人员操作执行失败，原因：" + error.toString());
						return;
					}
					
					//用户处理
					handleUser(psnCode,docVO.getAttributeValue("def5"));
					
					outlook.put(k, "主数据人员同步执行成功" + error + ",人员编码:" + psnCode);
					successPsnCode.put(psnCode, k);
					issuccess_sn = "Y";
				} catch (Exception e) {
					issuccess_sn = "N";
//					outlook.put(k, "人员操作执行失败，原因：" + (e.getMessage() != null ? e.getMessage() : e.toString()));
					outlook.put(k, "主数据人员同步执行失败，原因：" + e.toString());
					return;
//								new JSONArray(com.alibaba.fastjson.JSONObject.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(Stream.of(v).collect(Collectors.toList()))).toString()).getJSONObject(0).getJSONObject("psn").getString("PS_EMP_PK")+e.getMessage()
				}
			});

			// 根据成功的人员编码去更新其银行账户
			List<String[]> afterFiliter = resolveArray(items);
			if (successPsnCode.size() != 0) {
				afterFiliter.forEach(x -> {
					if (!successPsnCode.containsKey(x[3])) {
						outlook.put(successPsnCode.get(x[3]), "不存在此人员,无法新增银行账户:"+x[3]);
						return;
					}
					try {
						this.handleBank(x);
						outlook.put(successPsnCode.get(x[3]), outlook.get(successPsnCode.get(x[3])) + ",银行账户操作执行成功");
					} catch (BusinessException e) {
						e.printStackTrace();
						outlook.put(successPsnCode.get(x[3]),
								outlook.get(successPsnCode.get(x[3])) + ",银行账户操作执行失败+" + e.getMessage());
					}
				});
			}

		} catch (Exception e) {
			issuccess_sn = "N";
			outlook.put("all", "主数据人员同步时发生异常");
			sendResponse(response, ReceiveUtils.responseMsg("S", "主数据人员同步异常" + e.getMessage(), puuid, outlook));
			resultvo.setError(e.getMessage());
		} finally {
			List<SapPurchaseLogVO> logvo_list = new ArrayList<SapPurchaseLogVO>();
			String billno = sb_psnCode.toString();
			//wby 20211017 将每次报文所有人员记录在日志billno字段
			SapPurchaseLogVO logvo = PubUtils.createSNLog("MDG-NCC-PSNDOC", "", billno, "",
					"", jsonobj.toString(), outlook.toString(), "" + resultvo.getError(), issuccess_sn,
					this.getClass().getName());
			logvo_list.add(logvo);
			PubUtils.getSaplog().insertPurchaseLog_RequiresNew(logvo_list);
			if ("N".equals(issuccess_sn)) {
				sendResponse(response, ReceiveUtils.responseMsg("N", "主数据人员同步异常", puuid, outlook));
			} else {
				sendResponse(response, ReceiveUtils.responseMsg("S", "主数据人员同步成功", puuid, outlook));
			}
		}
	}
	
	/*
	 * wby 20211017 用户相关业务处理8
	 * update by daim 人员离职 停用账户 20220517
	 */
	private void handleUser(String code,Object status) throws BusinessException {
		//查询人员
		String condition = "code='" + code + "' and nvl(dr,0)=0 ";
		PsndocVO[] psndocVOs = getPsndocQueryService().queryPsndocVOsByCondition(condition);
		if(psndocVOs == null || psndocVOs.length == 0)
			return;
		
		PsndocVO psndocVO = psndocVOs[0];
		String whereSql = " pk_psndoc='" + psndocVO.getPk_psndoc() + "'"+" or user_code = '"+psndocVO.getDef2()+"'";
		UserVO[] users = NCLocator.getInstance().lookup(IUserManageQuery.class).queryUserByClause(whereSql);
		//存在的用户做相关处理
		if(users != null && users.length > 0) {
			UserVO user = users[0];
			//人员停用则用户停用
			if( !"在职".equals(status) ) {
				getUserManageSerivce().disableUser(user);
			}else {
				getUserManageSerivce().enableUser(user);
			}
			user.setPk_base_doc(psndocVO.getPk_psndoc());
			getUserManageSerivce().updateUser(user);
			
		} else { //不存在用户，则创建用户
			//BIP账号def2不为空则自动创建用户
			if(!StringUtils.isEmpty(psndocVO.getDef2())) {
				UserVO uservo = new UserVO();
				uservo.setUser_code(psndocVO.getDef2());
				uservo.setUser_name(psndocVO.getName());
				uservo.setEnablestate(Integer.valueOf(2));
				uservo.setPk_group(psndocVO.getPk_group());
				uservo.setPk_psndoc(psndocVO.getPk_psndoc());
				uservo.setBase_doc_type(Integer.valueOf(0));
				uservo.setPk_base_doc(psndocVO.getPk_psndoc());
				uservo.setIdentityverifycode("staticpwd");
//				LanguageVO currentLang = MultiLangContext.getInstance().getCurrentLangVO();
				uservo.setContentlang("zhCN0000000000000000");
				uservo.setPwdlevelcode("update");
				uservo.setFormat("FMT0Z000000000000000");
				UFDate enableDate = new UFDate(true);
				uservo.setAbledate(enableDate);
				//密码设置为空则使用系统默认密码
				uservo.setUser_password(null);
				uservo.setUser_type(1);
				//默认业务用户组
				String pk_userGroup = getQueryVal("select pk_usergroup, groupcode, groupname groupname, parentid, pk_group, dr, innercode, pk_org from sm_usergroup where groupcode='002' ");
				if(!StringUtils.isEmpty(pk_userGroup)) {
					UserGroupVO userGroupVo = (UserGroupVO)getDao().retrieveByPK(UserGroupVO.class, pk_userGroup, new String[] { "pk_org" });
					uservo.setPk_org(userGroupVo == null ? null : userGroupVo.getPk_org());
					uservo.setPk_usergroupforcreate(pk_userGroup);
				} else {
					uservo.setPk_org(null);
					uservo.setPk_usergroupforcreate(null);
				}
				uservo = getUserManageSerivce().addUser(uservo);
				
				RoleVO rolevo = getIRoleManageQuery().queryRoleByCode("SF_Role", psndocVO.getPk_group());
				if(rolevo != null) {
					getIRoleManage().assignRole2User(uservo.getCuserid(), new RoleVO[] { rolevo }, uservo.getPk_org(), enableDate, null);
				}
				
				//写业务日志
//				new BDBusiLogUtil(getMDId()).writeBusiLog("CreateUser", null, psndocVO);
			}
		}
	}

	/**
	 * 郭晋贤 2021年10月16日13:55:44 新逻辑
	 * @return
	 */
	public StringBuffer handlePsn(String code,List<CircularlyAccessibleValueObject> listJob,List<CircularlyAccessibleValueObject> listDoc,CircularlyAccessibleValueObject docVO,StringBuffer error) throws BusinessException{
		String condition = "code='" + code + "' and nvl(dr,0)=0 ";
		PsndocVO[] psndocVOs = getPsndocQueryService().queryPsndocVOsByCondition(condition);//根据编码查询是否存在此人员
		PsndocVO newdocVO = (PsndocVO) docVO;
		newdocVO.setPsnjobs(listJob.toArray(new PsnjobVO[listJob.size()]));
		//add by daim 设置默认的修改人 修改时间
		newdocVO.setModifiedtime(new UFDateTime(new Date()));
		newdocVO.setModifier("1001Q710000000025SD2");
		//人员编码不存在的情况，两个表都插入
		if (psndocVOs == null || psndocVOs.length == 0) {
			//update by daim 20220517 修改新增用户
			NCLocator.getInstance().lookup(IPsndocService.class).insertPsndoc((PsndocVO) docVO, true);
//			PsndocVO[] afterInsertParentVOs = getPsndocQueryService().queryPsndocVOsByCondition(condition);
			//PsndocVO afterInsertParentVO = getPsndocQueryService().queryPsndocVOsByCondition(condition)[0];
			//error.append(handlePsnjob(listJob, afterInsertParentVO, true, error));
		} else {//人员编码存在的情况，无论如何更新人员基本信息，针对工作信息不同的场景对工作信息作对应的处理
			//修改
			PsndocVO oldVO = (PsndocVO) psndocVOs[0];
			newdocVO.setAttributeValue("modifier", creater);
			newdocVO.setAttributeValue("modifiedtime", AppContext.getInstance().getServerTime());
			newdocVO.setPrimaryKey(oldVO.getPrimaryKey());
			listJob.forEach(x -> x.setStatus(1));
			
			//add by daim 检查人员工作信息 
			error=checkIsUapPsnjob(newdocVO,oldVO,error);
			//wby 20220228 调整工作信息调整
			//error.append(handlePsnjob(listJob, oldVO, false, error));
//			if (oldVO.getPsnjobs() != null) { 
//				//根据日期是否小于等于现在最新的任职日期来决定是否插入 从旧工作信息里面找任职结束日期为空的那个vo 根据他报文传的任职日期来判断
//				// update begin =====
//				for (PsnjobVO vo : oldVO.getPsnjobs()) {			
//					//主职的情况：如果工作信息为主职，结束日期为空，则走下一步逻辑处理
//					if(new UFBoolean(true).equals(vo.getIsmainjob())&&vo.getEnddutydate()==null) {
//						//判断：报文传的任职日期必须大于等于现在最新的任职日期
//						listJob.forEach(x->{
//							if(new UFBoolean(true).equals(x.getAttributeValue("ismainjob"))
//									&& vo.getIndutydate().before((UFLiteralDate) x.getAttributeValue("indutydate"))) {//判断是否为主职且报文传的任职日期大于旧vo任职日期
//									UFLiteralDate date = (UFLiteralDate) x.getAttributeValue("indutydate");
//									UFLiteralDate newDate = date.getDateBefore(1);
//									vo.setAttributeValue("enddutydate", newDate);
//									try {
//										NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) vo);
//										//插入这条主职的数据
//										if(x.getAttributeValue("pk_dept")==null) {
//											error.append("部门不存在,主职无法插入");
//											return;
//										}
//										x.setAttributeValue("pk_psndoc", oldVO.getPrimaryKey());
//										NCLocator.getInstance().lookup(IVOPersistence.class).insertVO((SuperVO) x);
//										
//									} catch (BusinessException e) {
//										// TODO Auto-generated catch block
//										error.append("更新人员工作信息时发生错误");
//										e.printStackTrace();
//									}
//								}
//						});
//						
//					}
//				}
//			}
			//处理兼职情况
//			listJob.stream().filter(x->new UFBoolean(false).equals(x.getAttributeValue("ismainjob"))).forEach(y->{
//				try {
//					y.setAttributeValue("pk_psndoc", oldVO.getPrimaryKey());
//					NCLocator.getInstance().lookup(IVOPersistence.class).insertVO((SuperVO) y);
//				} catch (BusinessException e) {
//					// TODO Auto-generated catch block
//					error.append("插入人员工作信息时发生错误");
//					e.printStackTrace();
//				}
//			});
		}
		return error;
	}
	
	 private StringBuffer checkIsUapPsnjob(PsndocVO newdocVO, PsndocVO psndoc, StringBuffer error) {
		  //当前人员档案所有工作信息
		  PsnjobVO[] jobs = psndoc.getPsnjobs();
		  List<PsnjobVO> newPsnJob = new ArrayList<PsnjobVO>();
		  //新传入的工作信息
		  List<PsnjobVO> listJob  = new ArrayList<PsnjobVO>(Arrays.asList(newdocVO.getPsnjobs()));
		  boolean isNewJob = false;
		  for(PsnjobVO newJob:listJob) {
			  try {
			  //新工作信息与旧工作信息对比处理
				  for(PsnjobVO oldJob : jobs) {
				   //找到当前唯一主职
				  if(oldJob.getIsmainjob().equals(new UFBoolean(true))&&(oldJob.getEnddutydate()==null||oldJob.getEnddutydate().compareTo(newJob.getIndutydate())>0)) {
					   //判断部门和组织是否相同 
					   //不相同则代表是新增数据 先修改旧数据的结束日期
						//特殊数据处理
					  if(!oldJob.getPk_dept().equals(newJob.getPk_dept()) &&oldJob.getIndutydate().equals(newJob.getIndutydate())) {
						  oldJob.setPk_dept(newJob.getPk_dept());
						  NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) oldJob);
					  }
					  else if(!oldJob.getPk_dept().equals(newJob.getPk_dept()) ||!oldJob.getPk_org().equals(newJob.getPk_org())) {
						   isNewJob  = true;
						   UFLiteralDate date = (UFLiteralDate) newJob.getIndutydate();
						   UFLiteralDate newDate = date.getDateBefore(1);
						   if(newDate.compareTo(oldJob.getIndutydate())>=0) {
							   oldJob.setEnddutydate(newDate);
							   NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) oldJob);
						   }
					   }
					   else {
						   //同组织部门 开始日期不同则也代表代表新增数据
						   if(!oldJob.getIndutydate().equals(newJob.getIndutydate())) {
							   isNewJob  = true;
							   UFLiteralDate date = (UFLiteralDate) newJob.getIndutydate();
							   UFLiteralDate newDate = date.getDateBefore(1);
							   if(newDate.compareTo(oldJob.getIndutydate())>=0) {
								   oldJob.setEnddutydate(newDate);
								   NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) oldJob);
							   }
						   }
						   
					   }
				   }
				   newPsnJob.add(oldJob);
			   }
			   //先修改一次旧数据  避开因跨组织出现新异常
//			   psndoc.setPsnjobs(newPsnJob.toArray(new PsnjobVO[newPsnJob.size()]));
//			   try {
//				   NCLocator.getInstance().lookup(IPsndocService.class).updatePsndoc(psndoc,false);
//				   new BaseDAO().executeUpdate("commit");
//			   } catch (BusinessException e) {
//					  error.append("同步人员档案信息时发生错误，" + e.getMessage());
//					  return error;
//				  }
			    //新增
			   if(isNewJob) {
		     //插入这条主职的数据
				   newJob.setAttributeValue("pk_psndoc", psndoc.getPk_psndoc());
				   newPsnJob.add(newJob);
			   }
		  } catch(Exception ex) {
			  error.append("同步人员工作信息时发生错误，" + ex.getMessage());
		  }
		}

			  //插入这条主职的数据
			  newdocVO.setPsnjobs(newPsnJob.toArray(new PsnjobVO[newPsnJob.size()]));
			   try {
				   NCLocator.getInstance().lookup(IPsndocService.class).updatePsndoc(newdocVO,false);
			   } catch (BusinessException e) {
				   error.append("同步人员档案信息时发生错误，" + e.getMessage());
				   return error;
			   }

		  return error;
	 }

	/*
	 * wby 20220228 人员工作信息处理
	 */
	private StringBuffer handlePsnjob(List<CircularlyAccessibleValueObject> listJob, PsndocVO psndoc, boolean isNewPsn, StringBuffer error) throws BusinessException {
		//新增人员则直接增加工作信息
		if(isNewPsn) {
			listJob.forEach(newJob -> {
				newJob.setAttributeValue("pk_psndoc", psndoc.getPk_psndoc());
				try {	
					NCLocator.getInstance().lookup(IVOPersistence.class).insertVO((SuperVO) newJob);
				} catch (BusinessException e) {
					error.append("插入人员工作信息时发生错误");
					e.printStackTrace();
				}
			});
		} else { 
			//修改人员，工作信息未变更的情况不新增（部门和任职结束日期一致，则认为未变更）
			//wby 20220510 重复生成工作记录优化
			
			PsnjobVO[] jobs = psndoc.getPsnjobs();
//			List<PsnjobVO> listOldJob = Arrays.asList(jobs);
			
			listJob.forEach(newJob -> {
				try {
					//新工作信息与旧工作信息对比处理
					boolean isNewJob = true;
//					listOldJob.forEach(oldJob -> {
					for(PsnjobVO oldJob : jobs) {
						if(oldJob.getPk_dept().equals(newJob.getAttributeValue("pk_dept"))) {
							//部门一致，结束日期或是否主职不一致，则修改
							boolean isUpdate = false;
							if(!newJob.getAttributeValue("ismainjob").equals(oldJob.getIsmainjob())) {
								oldJob.setIsmainjob((UFBoolean)newJob.getAttributeValue("ismainjob"));
								if(newJob.getAttributeValue("ismainjob").equals(new UFBoolean(true))) {
									UFLiteralDate date = (UFLiteralDate) oldJob.getAttributeValue("indutydate");
									UFLiteralDate newDate = date.getDateBefore(1);
									oldJob.setAttributeValue("enddutydate", newDate);
									oldJob.setEnddutydate((UFLiteralDate)newJob.getAttributeValue("enddutydate"));
									isUpdate = true;
								}
							}
							
							if(newJob.getAttributeValue("enddutydate") != null && oldJob.getEnddutydate() != null && !newJob.getAttributeValue("enddutydate").equals(oldJob.getEnddutydate())) {
								oldJob.setEnddutydate((UFLiteralDate)newJob.getAttributeValue("enddutydate"));
								isUpdate = true;
							}
							
							if(isUpdate) {
								NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) oldJob);
	//							NCLocator.getInstance().lookup(IVOPersistence.class).deleteVO((SuperVO) oldJob);
								error.append("工作记录修改成功！(" + oldJob.getPk_psnjob() + ")");
							}
							
							isNewJob = false;
						}
					}
					
					//任职部门不一致，则认为是新增
					if(isNewJob) {
						//插入这条主职的数据
						if(newJob.getAttributeValue("pk_dept") == null) {
							error.append("部门不存在,主职无法插入");
							return;
						}
						
						newJob.setAttributeValue("pk_psndoc", psndoc.getPk_psndoc());
						NCLocator.getInstance().lookup(IVOPersistence.class).insertVO((SuperVO) newJob);
						error.append("工作记录增加成功！(" + newJob.getAttributeValue("pk_dept") + ")");
					}
				} catch(BusinessException ex) {
					error.append("同步人员工作信息时发生错误，" + ex.getMessage());
				}
			});
					
		}
		
		return error;
	}
	
	/*
	 * 处理个人银行信息 
	 */
	public void handleBank(String[] params) throws BusinessException {
//		String accname = params[4];
		StringBuffer buffer = new StringBuffer();
		bank = params[0];
		String accnum = params[0];
		PsnBankaccUnionVO unionvo = new PsnBankaccUnionVO();
		PsnBankaccVO psnbankvo = new PsnBankaccVO();// 个人银行账户 (bd_psnbankacc)
		BankAccbasVO basavo = new BankAccbasVO();// 个人银行账户信息 (bd_bankaccbas)
		BankAccSubVO subvo = new BankAccSubVO();// 个人银行账户子户 (bd_bankaccsub )
		String pk_bankaccbas = getPKfromCode("bd_bankaccbas", "pk_bankaccbas", "accnum", accnum);
		//wby 人员编码
		String pk_psndoc = getPKfromCode("bd_psndoc", "pk_psndoc", "code", params[3]);
		//个人银行账户已存在
		if (!StringUtils.isEmpty(pk_bankaccbas)) {
			String pk_psnbankacc = getPKfromCode("bd_psnbankacc", "pk_psnbankacc", "pk_bankaccbas", pk_bankaccbas);
			//个人银行账户信息已存在
			if (!StringUtils.isEmpty(pk_psnbankacc)) {
				PsnBankaccUnionVO[] unionvos = NCLocator.getInstance().lookup(IPsnBankaccQueryService.class)
						.queryPsnBankaccUnionVosByPks(new String[] { pk_psnbankacc });
				
				if (unionvos == null) {
					throw new BusinessException("不存在个人银行账户，请检查！");
				}
				
				psnbankvo = unionvos[0].getPsnbankaccVO();
				basavo = unionvos[0].getBankaccbasVO();
				subvo = basavo.getBankaccsub()[0];
			}
			
		} 
		
		String pk_org = getPKfromCode("org_orgs", "pk_org", "code", params[2], "isbusinessunit='Y'");
		psnbankvo.setPk_org(isNotNull(pk_org));// 所属业务单元
		psnbankvo.setPk_psndoc(isNotNull(pk_psndoc));// 人员主键
		psnbankvo.setDr(0);
		// 账户性质默认为个人
		basavo.setAccountproperty(1);
		unionvo.setPsnbankaccVO(psnbankvo);			
		if (!StringUtils.isEmpty(accnum)) {
			basavo.setAccnum(accnum);// 账号
		} else {
			buffer.append("账号不能为空，请检查！");
		}
		//wby 20211023 银行档案增加只查启用状态的数据
//		String pk_bankdoc = getPKfromCode("bd_bankdoc", "pk_bankdoc", "pcombinenum", params[1]);
		String sql = "select * from bd_bankdoc where nvl(dr,0)=0 and enablestate=2 and pcombinenum='" + params[1] + "'";
		BankdocVO bankVO = (BankdocVO)getDao().executeQuery(sql, new BeanProcessor(BankdocVO.class));
		if(bankVO == null) {
			buffer.append("银行档案：联行号为：" + params[1] + "不存在或已停用，请检查！");
		} else {
			basavo.setPk_bankdoc(bankVO.getPk_bankdoc());// 开户银行
			basavo.setPk_banktype(bankVO.getPk_banktype());// 银行类别
		}
		
		if (buffer.length() > 0) {
			throw new BusinessException(buffer.toString());
		}
		
		basavo.setAccopendate(new UFDate("2020-01-01"));// 开户日期
		basavo.setAccname(params[4]);// 户名
		basavo.setAccclass(0);// 账户分类
		basavo.setDataoriginflag(0);// 分布式
		String pk_user = SysInitQuery.getParaString("GLOBLE00000000000000", "ITFUSER");// getPKfromCode("sm_user","cuserid","user_code","jkzdr");
		basavo.setCreator(pk_user);// 创建人
		basavo.setDr(0);
		basavo.setGroupaccount(UFBoolean.FALSE);
		basavo.setIsenableelecbill(UFBoolean.FALSE);
		basavo.setIsinneracc(UFBoolean.FALSE);
		basavo.setIssigned(UFBoolean.FALSE);
		basavo.setPk_org(pk_org);
		basavo.setQrybalanceitf(0);
		basavo.setSharetag(UFBoolean.FALSE);
		basavo.setEnablestate(2);

		subvo.setPk_currtype("1002Z0100000000001K1");// 币种 默认人民币
		if (StringUtils.isEmpty(pk_bankaccbas)) {
			subvo.setStatus(2);
		}
		basavo.setBankaccsub(new BankAccSubVO[] { subvo });
		unionvo.setBankaccbasVO(basavo);
		
		//update by daim 20220421 处理前查询当前用户记录的所有银行卡 并且工资卡和默认卡字段 全部置为null start
		//查询个人银行账户为默认报销卡 pk_psndoc
		sql = "select * from bd_psnbankacc where pk_psndoc='"  + pk_psndoc + "' and isexpenseacc = 'Y'";
	    List<PsnBankaccVO> hlist = (List<PsnBankaccVO>)getDao().executeQuery(sql, new BeanListProcessor(PsnBankaccVO.class));
	    if(hlist != null && hlist.size() > 0) {
	    	for(PsnBankaccVO vo: hlist) {
	    		vo.setIsexpenseacc(new UFBoolean("N")); //非默认报销卡
	    		vo.setPayacc(null); //置空
	    		NCLocator.getInstance().lookup(IVOPersistence.class).updateVO(vo);
	    	}
	    }
	    //update by daim 20220421 处理前查询当前用户记录的所有银行卡 并且工资卡和默认卡字段 全部置为null end

		//个人银行账户已存在，直接修改账户信息
		if (!StringUtils.isEmpty(pk_bankaccbas)) {
			PsnbankUpdateImpl impl = new PsnbankUpdateImpl();
			impl.update(unionvo);
		} else { //个人银行账户不存在,新增银行账户，处理该人员已有的银行账号
			//wby 20211023 新增的个人银行账户为默认报销卡和工资卡1则已存在的个人银行账户有默认报销卡和工资卡1，则修改为非默认报销卡和工资卡0
			//查询个人银行账户为默认报销卡 pk_psndoc
//			sql = "select * from bd_psnbankacc where isexpenseacc='Y' and pk_psndoc='"  + pk_psndoc + "'";
//		    List<PsnBankaccVO> hlist = (List<PsnBankaccVO>)getDao().executeQuery(sql, new BeanListProcessor(PsnBankaccVO.class));
//		    if(hlist != null && hlist.size() > 0) {
//		    	//取消默认报销卡
//		    	for(PsnBankaccVO vo: hlist) {
//		    		vo.setIsexpenseacc(new UFBoolean(false)); //非默认报销卡
//		    		vo.setPayacc(null); //置空
//		    		NCLocator.getInstance().lookup(IVOPersistence.class).updateVO(vo);
//		    	}
//		    }
			
			//新增的银行账号做为新的默认报销卡
			psnbankvo.setIsexpenseacc(new UFBoolean("Y"));// 默认报销卡
			psnbankvo.setPayacc(1); //	1=工资卡1; 2=工资卡2; 3=工资卡3;
			unionvo.setPsnbankaccVO(psnbankvo);
			NCLocator.getInstance().lookup(IPsnBankaccService.class).insertPsnBankacc(unionvo);
			
			
		}

	}
	
	public List<String[]> resolveArray(JSONArray beforefiliter) {
		List<com.alibaba.fastjson.JSONObject> list = com.alibaba.fastjson.JSONArray
				.toJavaObject(com.alibaba.fastjson.JSONObject.parseArray(beforefiliter.toString()), ArrayList.class);
		// 0:银行卡号 1:开户行 2:业务单元 3:人员编码 4:户名
		return list.stream()
				.map(x -> new String[] { x.getString("BANK_CARD"), x.getString("OPENING_BANK"),
						x.getString("NCC_FIN_ORG_CODE"), x.getString("PS_EMP_PK"), x.getString("EMP_NAME") })
				.collect(Collectors.toList());
	}

	private String getPKfromCode(String tableName, String pk, String code, String code_value) throws BusinessException {
		return getPKfromCode(tableName, pk, code, code_value, "");
	}
	
	private String getPKfromCode(String tableName, String pk, String code, String code_value, String otherWhereSql) throws BusinessException {
		String sql = "select " + pk + " from " + tableName + " where nvl(dr,0)=0 and " + code + "='" + code_value
				+ "' ";
		if(!StringUtils.isEmpty(otherWhereSql)) sql += " and " + otherWhereSql;
		String codes = (String) getDao().executeQuery(sql, new ColumnProcessor());
		return codes;
	}
	
	private String isNotNull(String fieldValue) {
		return StringUtils.isEmpty(fieldValue) ? null : fieldValue;
	}

	public IPsndocQueryService getPsndocQueryService() {
		if (iPsndocQueryService == null)
			iPsndocQueryService = NCLocator.getInstance().lookup(IPsndocQueryService.class);
		return iPsndocQueryService;
	}


	private String getQueryVal(String querysql) {
		String queryvo = null;
		try {
			queryvo = (String) getDao().executeQuery(querysql, new ColumnProcessor());
			return queryvo;
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		return null;
	}

}
