package nc.impl.wa.grade;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import nc.bs.framework.common.NCLocator;
import nc.bs.framework.redis.util.StringUtil;
import nc.hr.frame.persistence.SimpleDocServiceTemplate;
import nc.hr.utils.ResHelper;
import nc.itf.hr.wa.IItemQueryService;
import nc.itf.hr.wa.IWaGradeQueryService;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.md.persist.framework.MDPersistenceService;
import nc.vo.bd.ref.RefInfoVO;
import nc.vo.hr.infoset.InfoItemVO;
import nc.vo.hr.tools.pub.GeneralVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.uif2.LoginContext;
import nc.vo.wa.grade.AggWaGradeVO;
import nc.vo.wa.grade.CrtVO;
import nc.vo.wa.grade.IWaGradeCommonDef;
import nc.vo.wa.grade.PsnhiHeaderVO;
import nc.vo.wa.grade.WaCriterionVO;
import nc.vo.wa.grade.WaGradeComparator;
import nc.vo.wa.grade.WaGradeVO;
import nc.vo.wa.grade.WaGradeVerVO;
import nc.vo.wa.grade.WaPrmlvVO;
import nc.vo.wa.grade.WaPsnhiBVO;
import nc.vo.wa.grade.WaSeclvVO;
import nc.vo.wa.grade.WaStdHiSetVO;
import nc.vo.wa.item.WaItemVO;
import nccloud.commons.lang.StringUtils;

/**
 * 薪资标准设置<BR>
 * <BR>
 * 
 * @author: xuhw
 * @date: 2009-11-10
 * @since: eHR V6.0
 * @走查人:
 * @走查日期:
 * @修改人:
 * @修改日期:
 */
public class WaGradeQueryImpl implements IWaGradeQueryService
{
	private final String DOC_NAME = "wagrade";
	private SimpleDocServiceTemplate serviceTemplate;
	private WaGradeDAO gradeDAO;

	@Override
	public Object[] queryWaGradeVO(LoginContext context, String strCondition) throws BusinessException
	{
		// 对薪资标准设置表主表根据所属组织和编码进行排序
		String strOrderBy = WaGradeVO.PK_ORG + "," + WaGradeVO.CODE;

		AggWaGradeVO[] billVOs = getServiceTemplate().queryByCondition(context, AggWaGradeVO.class, strCondition, strOrderBy);
		if (billVOs == null)
		{
			return null;
		}
		// 对薪资标准设置标子表根据序号进行排序
		WaPrmlvVO[] prmlvs = null;
		WaSeclvVO[] seclvs = null;
		for (int i = 0; i < billVOs.length; i++)
		{
			prmlvs = (WaPrmlvVO[]) billVOs[i].getTableVO(IWaGradeCommonDef.WA_PRMLV);
			seclvs = (WaSeclvVO[]) billVOs[i].getTableVO(IWaGradeCommonDef.WA_SECLV);
			if (prmlvs != null)
			{
				Arrays.sort(prmlvs, new WaGradeComparator());
			}
			if (seclvs != null)
			{
				Arrays.sort(seclvs, new WaGradeComparator());
			}
			billVOs[i].setTableVO(IWaGradeCommonDef.WA_PRMLV, prmlvs);
			billVOs[i].setTableVO(IWaGradeCommonDef.WA_SECLV, seclvs);
			
			WaItemVO itemvo = NCLocator.getInstance().lookup(IItemQueryService.class).queryWaItemVOByPk(billVOs[i].getParentVO().getPk_wa_item());
			if (itemvo == null) {
				/*res 请检查引用的主键为{0}的薪资项目是否存在！*/
				throw new BusinessException(ResHelper.getString("60130paystd","060130paystd0219",billVOs[i].getParentVO().getPk_wa_item()));
			}
			billVOs[i].getParentVO().setIflddecimal(itemvo.getIflddecimal());
		}

		return billVOs;
	}
 
	/**
	 * 查询薪资规则值表，组合CrtVO
	 * 
	 * @author xuhw on 2009-12-1
	 * @see nc.itf.hr.wa.IWaGradeQueryService#queryCriterionByClassid(java.lang.String,
	 *      boolean)
	 */
	public CrtVO[] queryCriterionByClassid(String strGrdPk,String strPKGradever ,boolean isMult) throws BusinessException
	{

		WaCriterionVO[] criterions = null;
		CrtVO[] crtvo = null;

		criterions = getGradeDao().queryByClsPkAndVerPk(strGrdPk,strPKGradever, isMult);
		
		String strOrdGrdpk = "";
		CrtVO one = null;
		Vector<CrtVO> v = new Vector<CrtVO>();
		boolean isNotAdded = true;
		int intCriterion = 0;
		if (criterions != null)
		{
			intCriterion = criterions.length;
		}
		for (int i = 0; i < intCriterion; i++)
		{
			if (strOrdGrdpk.equals(criterions[i].getPk_wa_prmlv()))
			{// 同一个级别
				one.add(criterions[i]);
				isNotAdded = true;
			}
			else
			{
				if (one != null)
				{
					v.addElement(one);
					isNotAdded = false;
				}
				one = new CrtVO();
				strOrdGrdpk = criterions[i].getPk_wa_prmlv();
				one.add(criterions[i]);
				isNotAdded = true;
			}
		}
		if (one != null && isNotAdded)
		{
			v.addElement(one);
		}
		if (v.size() > 0)
		{
			crtvo = new CrtVO[v.size()];
			v.copyInto(crtvo);
		}

		return crtvo;
	}

	/**
	 * 取得生效的或者是未生效的最新一个薪资标准版本
	 * @param strGrdPk
	 * @param strPKGradever
	 * @param isMult
	 * @return
	 * @throws BusinessException
	 */
	public WaGradeVerVO queryEffectOrCurrentGradeVerVO(String strGrdPk,String strPKGradever ,boolean isMult) throws BusinessException
	{
	    WaGradeVerVO gradevervo =  new WaGradeVerVO();

	    List<WaGradeVerVO> lisGradeVerVO = (List<WaGradeVerVO>)getGradeDao().getBaseDao().retrieveByClause(WaGradeVerVO.class, " pk_wa_grd = '"+strGrdPk+"' and effect_flag = 'Y'");
	    
	    if (lisGradeVerVO == null || lisGradeVerVO.size() == 0) {
	    	lisGradeVerVO = (List<WaGradeVerVO>)getGradeDao().getBaseDao().retrieveByClause(WaGradeVerVO.class, " pk_wa_grd = '"+strGrdPk+"' order by ver_create_date desc");
		}
	    
        if (lisGradeVerVO!=null &&!lisGradeVerVO.isEmpty())
        {
            gradevervo = lisGradeVerVO.toArray(new WaGradeVerVO[0])[0];
        }
	    CrtVO[] crtVOs = queryCriterionByClassid(strGrdPk, gradevervo.getPk_wa_gradever(), isMult);
        gradevervo.setCrtVOs(crtVOs);
        if (!StringUtils.isBlank(strGrdPk))
        { WaGradeVO gradeVO = (WaGradeVO)getGradeDao().getBaseDao().retrieveByPK(WaGradeVO.class, strGrdPk, new String[]{"ts"});
        if (gradeVO != null)
        {
        	gradevervo.setGradets(gradeVO.getTs().toString());}	
        }
        
        return gradevervo;
	}
	
	/**
	 * 取得生效的薪资标准版本
	 * @param strGrdPk
	 * @param strPKGradever
	 * @param isMult
	 * @return
	 * @throws BusinessException
	 */
	public WaGradeVerVO queryEffectGradeVerVO(String strGrdPk,String strPKGradever ,boolean isMult) throws BusinessException
	{
	    WaGradeVerVO gradevervo =  new WaGradeVerVO();

	    List<WaGradeVerVO> lisGradeVerVO = (List<WaGradeVerVO>)getGradeDao().getBaseDao().retrieveByClause(WaGradeVerVO.class, " pk_wa_grd = '"+strGrdPk+"' and effect_flag = 'Y'");
	    
        if (lisGradeVerVO!=null &&!lisGradeVerVO.isEmpty())
        {
            gradevervo = lisGradeVerVO.toArray(new WaGradeVerVO[0])[0];
        }
	    CrtVO[] crtVOs = queryCriterionByClassid(strGrdPk, gradevervo.getPk_wa_gradever(), isMult);
        gradevervo.setCrtVOs(crtVOs);
        if (!StringUtils.isBlank(strGrdPk))
        { WaGradeVO gradeVO = (WaGradeVO)getGradeDao().getBaseDao().retrieveByPK(WaGradeVO.class, strGrdPk, new String[]{"ts"});
        if (gradeVO != null)
        {
        	gradevervo.setGradets(gradeVO.getTs().toString());}	
        }
        
        return gradevervo;
	}
	
	/**
	 * 根据薪资标准类别主键，取得人员相关属性
	 * 
	 * @author xuhw on 2009-12-7
	 * @param strGrdPk
	 * @return PsnhiHeaderVO[]
	 * @throws BusinessException
	 */
	public PsnhiHeaderVO[] findPsnHiByStdPK(String strGrdPk) throws BusinessException
	{
		return getGradeDao().queryPsnHiByStdPK(strGrdPk);
	}
	/**
	 * 根据薪资标准类别主键，取得关联项目信息
	 * @param strGrdPk
	 * @return
	 * @throws BusinessException
	 */
	public WaItemVO getItemVOByGrdPk(String strGrdPk) throws BusinessException{
		return getGradeDao().getItemVOByGrdPk(strGrdPk);
	}

	/**
	 * 根据薪资标准类别主键，取得薪资人员属性值设定表内容
	 * 
	 * @author xuhw on 2009-12-7
	 * @param strGrdPk
	 * @return WaStdHiSetVO[]
	 * @throws BusinessException
	 */
	public WaStdHiSetVO[] queryStdHiByGrdPk(String strGrdPk, int classType) throws BusinessException
	{
		WaPsnhiBVO[] waStdHiVOs = null;
		WaStdHiSetVO[] waStdHiSetVOs = null;

		waStdHiVOs = getGradeDao().queryStdHiByGrdPk(strGrdPk, classType);
		String strOrdRow = "";
		String strPKgldlv = null;
		WaStdHiSetVO one = null;
		Vector<WaStdHiSetVO> vecWaStdHiSet = new Vector<WaStdHiSetVO>();
		boolean isNotAdded = true;
		int intCriterion = 0;
		if (waStdHiVOs != null)
		{
			intCriterion = waStdHiVOs.length;
		}
		for (int i = 0; i < intCriterion; i++)
		{
			if (strOrdRow.equals(waStdHiVOs[i].getSortgroup()))
			{
				// 同一个行
				one.add(waStdHiVOs[i]);
				isNotAdded = true;
			}
			else
			{
				if (one != null)
				{
					vecWaStdHiSet.addElement(one);
					isNotAdded = false;
				}
				one = new WaStdHiSetVO();
				// 画面上一行对应一个waStdHiVOsVO对象
				strOrdRow = waStdHiVOs[i].getSortgroup();
				strPKgldlv = waStdHiVOs[i].getPk_wa_grdlv();// TODO
				// WaCriterionVO criterionVo =
				// dao.queryCriterionByCrtPk(strPKCrt);
				one.setWaGrdlvPK(strPKgldlv);
				// if (criterionVo != null)
				// {
				// one.setCrtValue(String.valueOf(criterionVo.getCriterionvalue()));
				// }
				one.add(waStdHiVOs[i]);
				isNotAdded = true;
			}
		}
		if (one != null && isNotAdded)
		{
			vecWaStdHiSet.addElement(one);
		}
		if (vecWaStdHiSet.size() > 0)
		{
			waStdHiSetVOs = new WaStdHiSetVO[vecWaStdHiSet.size()];
			vecWaStdHiSet.copyInto(waStdHiSetVOs);
		}

		return waStdHiSetVOs;
	}
	
	@Override
	public WaPsnhiBVO[] queryWaPsnhiBVOsByGrdPk(String strGrdPk, int classType)
			throws BusinessException {
		return getGradeDao().queryStdHiByGrdPk(strGrdPk, classType);
	}

	/**
	 * 根据薪资标准类别值主键 查询内容
	 * 
	 * @author xuhw on 2009-12-7
	 * @param strCrtkey
	 * @param isMultSec
	 * @return WaCriterionVO
	 * @throws nc.vo.pub.BusinessException
	 */
	public WaCriterionVO findCriterionByCrtKey(String strCrtkey, boolean isMultSec) throws nc.vo.pub.BusinessException
	{
		return getGradeDao().queryCriterionVOByCrtKey(strCrtkey, isMultSec);
	}

	/**
	 * 根据薪资标准类别值主键 查询内容 多条记录
	 * 
	 * @author xuhw on 2009-12-7
	 * @param strCrtkey
	 * @param isMultSec
	 * @return WaCriterionVO[]
	 * @throws nc.vo.pub.BusinessException
	 */
	public WaCriterionVO[] findCriterionByGrdKey(String strCrtkey, boolean isMultSec) throws nc.vo.pub.BusinessException
	{
		return getGradeDao().queryCriterionVOsByCrtKey(strCrtkey, isMultSec);
	}

	/**
	 * 通过主key返回聚合VO
	 * 
	 * @param strPkWaGrd
	 * @exception BusinessException
	 *                异常说明。
	 */
	public AggWaGradeVO queryAggWagradeByGrdPK(String strPkWaGrd) throws BusinessException
	{
		AggWaGradeVO aggvo = this.getMDQueryService().queryBillOfVOByPK(AggWaGradeVO.class, strPkWaGrd, false);
		WaCriterionVO[] criterionvos = findCriterionByGrdKey(strPkWaGrd, true);
		aggvo.setTableVO(IWaGradeCommonDef.WA_CRT, criterionvos);
		//给项目精度字段赋值
		WaItemVO itemvo = NCLocator.getInstance().lookup(IItemQueryService.class).queryWaItemVOByPk(aggvo.getParentVO().getPk_wa_item());
		aggvo.getParentVO().setIflddecimal(itemvo.getIflddecimal());
		return aggvo;
	}

	@Override
	public InfoItemVO queryInfoItemByInf(String tableCode, String infoCode) throws BusinessException
	{
		return getGradeDao().queryInfoItemByInf(tableCode, infoCode);
	}

	/**
	 * @author xuhw on 2010-6-2
	 * @throws BusinessException
	 * @see nc.itf.hr.wa.IWaGradeQueryService#queryBdRefInfoList()
	 */
	@Override
	public Map<String, RefInfoVO> queryBdRefInfoList() throws BusinessException
	{
		return getGradeDao().queryBdRefInfoList();
	}

	/**
	 * @author suihang on 2011-10-26
	 * @throws BusinessException
	 * @see nc.itf.hr.wa.IWaGradeQueryService#queryBdRefInfoList()
	 */
	@Override
	public GeneralVO[] queryBdEnumValues(String strPk) throws BusinessException
	{
		return getGradeDao().queryBdEnumValues(strPk);
	}
	   /**
     * 查询薪资标准类别值
     * @author xuhw on 2009-11-28
     * @param clsPk
     * @param isMultSec
     * @return
     * @throws BusinessException
     */
    public WaCriterionVO[] queryByClsPk(String clsPk, boolean isMultSec, int sortTpye) throws BusinessException
    {
        return getGradeDao().queryByClsPk(clsPk, isMultSec, sortTpye);
    }

    /**
     * 根据薪资标准类别值主键 查询内容
     * 
     * @author xuhw on 2009-12-7
     * @param strCrtkey
     * @return
     * @throws BusinessException
     */
    public WaCriterionVO queryCriterionVOByCrtKey(String strCrtkey) throws BusinessException
    {

        return getGradeDao().queryCriterionVOByCrtKey(strCrtkey);
    }
    
    
	/**
	 * 返回元数据查询服务对象
	 * 
	 * @return
	 */
	private IMDPersistenceQueryService getMDQueryService()
	{
		return MDPersistenceService.lookupPersistenceQueryService();
	}

	private SimpleDocServiceTemplate getServiceTemplate()
	{
		if (serviceTemplate == null)
		{
			serviceTemplate = new SimpleDocServiceTemplate(DOC_NAME);
		}
		return serviceTemplate;
	}

	private WaGradeDAO getGradeDao()
	{
		if (gradeDAO == null)
		{
			gradeDAO = new WaGradeDAO();
		}

		return gradeDAO;
	}

	//20150902 shenliangc 解决SONAR问题，将职级主键和对应的职级列别名称统一查询出来。
	@Override
	public HashMap<String, String> queryJoblevelsysNameByJoblevelPk()
			throws BusinessException {
		return getGradeDao().queryJoblevelsysNameByJoblevelPk();
	}

	@Override
	public List<String> queryWaGradeOrg(String pk_wa_grade) throws BusinessException {
		return getGradeDao().queryWaGradeOrg(pk_wa_grade);
	}

	@Override
	public WaGradeVerVO queryWaGradeVerVO(String pk_wa_gradever) throws BusinessException {
		return getGradeDao().queryWaGradeVerVO(pk_wa_gradever);
	}

	@Override
	public String queryWaGradePK(String strCondition) throws BusinessException {
		return getGradeDao().queryWaGradePK(strCondition);
	}

	@Override
	public String queryParentPrml(String pkWaPrmlv) throws BusinessException {
		String sql = "select levelname from wa_prmlv where pk_wa_prmlv = '"+pkWaPrmlv+"' and dr = 0";
		return (String) getGradeDao().getBaseDao().executeQuery(sql, new ColumnProcessor());
	}

	@Override
	public UFBoolean checkWaGrade(String pkWagradeTop, String standard_type, String pkWagrade)
			throws BusinessException {
		String sql = "select pk_wa_grd from wa_grade where wa_grade.pk_wagrade_top = '"+pkWagradeTop+"' and wa_grade.standard_type = '"+standard_type+"' and nvl(wa_grade.dr,0) = 0";
		if(StringUtil.isNotBlank(pkWagrade)) {
			sql = sql + " and wa_grade.pk_wa_grd <> '"+pkWagrade+"'";
		}
		List<String> list = (List<String>) getGradeDao().getBaseDao().executeQuery(sql, new ColumnListProcessor());
		if(list != null && list.size() > 0) {
			return UFBoolean.TRUE;
		}
		return UFBoolean.FALSE;
	}
 
}
