package nc.impl.hi.psndoc;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.logging.Logger;
import nc.hr.utils.InSQLCreator;
import nc.hr.utils.ResHelper;
import nc.hr.utils.SQLHelper;
import nc.itf.hi.IPsndocTrainService;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.vo.hi.psndoc.TrainVO;
import nc.vo.hi.wadoc.PsndocWadocVO;
import nc.vo.pub.BusinessException;
import nc.vo.uif2.LoginContext;
import nccloud.commons.lang.ArrayUtils;

public class PsndocTrainServiceImpl implements IPsndocTrainService {
	
	private final int PSNNAME = 1;
	private final int PSNCODE = 0;
	
	private BaseDAO baseDAO;
	public BaseDAO getBaseDAO() {
		if(baseDAO == null) {
			baseDAO = new BaseDAO();
		}
		return baseDAO;
	}

	@Override
	public TrainVO[] importData2DB(TrainVO[] trainVOs, LoginContext context)
			throws BusinessException {
		return extendInertVoinfo(trainVOs, context);
	}

	/**
	 * 对导入的数据集进行分析处理<BR>
	 * 1)判断导入数据的各项目是否合法<BR>
	 * 合法：导入数据库<BR>
	 * 非法：判断原因存储，回显给用户<BR>
	 * 2)返回 导入后信息<BR>
	 *
	 * @author xuhw on 2010-4-21
	 * @param psndocWadocVOs
	 * @return
	 * @throws BusinessException
	 */
	private TrainVO[] extendInertVoinfo(TrainVO[] trainVOs, LoginContext context)
			throws BusinessException{
		// 数据合法的记录集合
		List<TrainVO> successImportList = new ArrayList<TrainVO>();
		// 不合法的记录集合
		List<TrainVO> failtureImportList = new ArrayList<TrainVO>();
		TrainVO aftProVO = null;
		if (ArrayUtils.isEmpty(trainVOs)) {
			return trainVOs;
		}
		int inttt = 0;
		for (TrainVO trainVO : trainVOs) {
			
			aftProVO = this.expandInertVOInfo(trainVO,context);
			if(aftProVO == null){
				//added by zengcheng 2012-07-12，没有查到人，则需要放入不合法的记录，一般都是因为非谈判薪酬，然后金额不符合级档的规定
				failtureImportList.add(aftProVO);
				continue;
			}
			if (aftProVO == null) {
				failtureImportList.add(trainVO);
				continue;
			}
			successImportList.add(aftProVO);
		}
		
		if(successImportList.size() > 0) {
			getBaseDAO().insertVOArray(successImportList.toArray(new TrainVO[0]));
		}
		return queryWaFailedReason(failtureImportList, context);
	}
	
	private TrainVO expandInertVOInfo(TrainVO trainVO, LoginContext context) throws BusinessException{
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("	select  ");
		sbSql.append("	 "+ SQLHelper.getMultiLangNameColumn("bd_psndoc.name")+ "  as psnName,  ");
		sbSql.append("	bd_psndoc.code as psnCode,   ");
		sbSql.append("	hi_psnorg.pk_psnorg,");
		sbSql.append("	hi_psnjob.pk_psnjob ");
		sbSql.append("	from  ");
		sbSql.append("	bd_psndoc   ");
		sbSql.append("	inner join hi_psnorg on bd_psndoc.pk_psndoc = hi_psnorg.pk_psndoc  ");
		sbSql.append("  inner join hi_psnjob on hi_psnjob.pk_psndoc = bd_psndoc.pk_psndoc and hi_psnorg.pk_psnorg = hi_psnjob.pk_psnorg");
		sbSql.append("	where  ");
		sbSql.append("	bd_psndoc.code = '").append(trainVO.getPsnCode()).append("' and  ");
		sbSql.append("	hi_psnorg.indocflag = 'Y' and  ");
		sbSql.append("	hi_psnorg.lastflag = 'Y'  and hi_psnjob.lastflag = 'Y' and hi_psnjob.endflag = 'N' and hi_psnorg.endflag = 'N' and hi_psnjob.ismainjob = 'Y' ");
		TrainVO[] trainVOs = this.executeQueryVOs(sbSql.toString());
		if(trainVOs != null && trainVOs.length > 0) {
			trainVO.setPk_psnjob(trainVOs[0].getPk_psnjob());
			trainVO.setPk_psnorg(trainVOs[0].getPk_psnorg());
			return trainVO;
		}
		return null;
	}
	
	/**
	 * 查询理由<BR>
	 * <BR>
	 *
	 * @author xuhw on 2010-4-22
	 * @param failtureImportList
	 * @param content
	 * @return
	 * @throws BusinessException
	 */
	private TrainVO[] queryWaFailedReason(List<TrainVO> failtureImportList, LoginContext context)
			throws BusinessException{
		try {
			// 员工信息中无此员工编码的人员
			List<TrainVO> vNotInBdpsndocByCode = checkFailedInResult(failtureImportList, this
					.queryInBdpsndocByCode(failtureImportList, context));
			failtureImportList = new ArrayList<TrainVO>();
			failtureImportList.addAll(vNotInBdpsndocByCode);
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage(), ex);
		}
		return failtureImportList.toArray(new TrainVO[0]);
	}
	
	/**
	 * 从结果中剔除已经能够判断错误原因的人员的人员
	 *
	 * @param results
	 *            待确认错误原因的人员
	 * @param inQueryResult
	 *            已经存在的人员
	 * @return 剔除了已经存在人员的结果
	 */
	private List<TrainVO> checkFailedInResult(List<TrainVO> failtureImportList,
			TrainVO[] inQueryResult){

		List<TrainVO> psnReasonPersons = new ArrayList<TrainVO>();
		List<TrainVO> otherReasonPsn = new ArrayList<TrainVO>();

		int length = 0;
		if (!ArrayUtils.isEmpty(inQueryResult)) {
			length = inQueryResult.length;
		}
		for (int i = 0; i < failtureImportList.size(); i++) {
			Logger.debug(new Date() + " : checkFailedInResult ----> + " + i);
			TrainVO trainVO = failtureImportList.get(i);
			trainVO.setReason("员工信息中编码为[{"+trainVO.getPsnCode()+"}]的员工不存在！\n");
			trainVO.setError_flag(PSNCODE);
			psnReasonPersons.add(trainVO);
			for (int j = 0; j < length; j++) {
				String psncode = inQueryResult[j].getPsnCode();
				String psnName = inQueryResult[j].getPsnName();
				if (psncode.equals(trainVO.getPsnCode())) {
					if (!psnName.equals(trainVO.getPsnName())) {
						trainVO.setReason("员工信息中无姓名为[{"+trainVO.getPsnName()+"}]的员工不存在！\n");
						trainVO.setError_flag(PSNNAME);
					} else {
						psnReasonPersons.remove(trainVO);
						trainVO.setReason(null);
						otherReasonPsn.add(trainVO);
					}
				}
			}
		}

		failtureImportList.clear();//removeAll(failtureImportList);
		failtureImportList.addAll(otherReasonPsn);
		return psnReasonPersons;
	}
	
	/**
	 * 查询人员编码确定的人是否在人员档案中
	 * 
	 * @author xuhw on 2010-4-21
	 * @param results
	 * @param context
	 * @return
	 * @throws BusinessException 
	 * @throws Exception
	 */
	public TrainVO[] queryInBdpsndocByCode(List<TrainVO> failtureImportList, LoginContext context) throws BusinessException
	{

		if (failtureImportList == null || failtureImportList.size() == 0)
		{
			return new TrainVO[0];
		}
		String in = new InSQLCreator().getInSQL(failtureImportList.toArray(new TrainVO[0]), TrainVO.PSNCODE);
//		List<CircularlyAccessibleValueObject[]> list = FormatVO.seperateValueObject(failtureImportList.toArray(new PsndocWadocVO[0]));
//		String in = "";
//		for (CircularlyAccessibleValueObject[] circularlyAccessibleValueObjects : list)
//		{
//			if(!StringUtils.isEmpty(in)){
//				in += ",";
//			}
//			in += FormatVO.formatArrayToString(circularlyAccessibleValueObjects, PsndocWadocVO.PSNCODE, "'");
//		}
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("	select  ");
		sbSql.append("	 "+ SQLHelper.getMultiLangNameColumn("bd_psndoc.name")+ "  as psnname,  ");
		sbSql.append("	bd_psndoc.code as psncode   ");
		sbSql.append("	from  ");
		sbSql.append("	bd_psndoc   ");
		sbSql.append("	inner join hi_psnorg on bd_psndoc.pk_psndoc = hi_psnorg.pk_psndoc  ");
		sbSql.append("	where  ");
		sbSql.append("	bd_psndoc.code in (").append(in).append(") and  ");
		//sbSql.append("	bd_psndoc.pk_org = '").append(context.getPk_org()).append("' and  ");
		
		//sbSql.append("	bd_psndoc.pk_group = '").append(context.getPk_group()).append("'  and  ");  //跨集团兼职人员定调资数据无法导入
		sbSql.append("	hi_psnorg.indocflag = 'Y' and  ");
		// sbSql.append("	hi_psnorg.endflag = 'N' and  ");
		sbSql.append("	hi_psnorg.lastflag = 'Y'   ");
		return this.executeQueryVOs(sbSql.toString());
	}
	
	public TrainVO[] executeQueryVOs(String sql) throws DAOException {
		List<TrainVO> list = (List)getBaseDAO().executeQuery(sql, new BeanListProcessor(TrainVO.class));
		if (list == null || list.size() == 0) {
			return (TrainVO[])(Object[])Array.newInstance(TrainVO.class, 0);
		}
		return (TrainVO[])list.toArray((Object[])Array.newInstance(TrainVO.class, list.size()));
	}
	
}
