package nc.impl.wa.paydata;

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

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.hr.utils.SQLHelper;
import nc.itf.hr.wa.IPaydataExService;
import nc.itf.hr.wa.IPaydataQueryService;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.AppContext;
import nc.vo.wa.classitempower.ItemPowerUtil;
import nc.vo.wa.func.WherePartUtil;
import nc.vo.wa.paydata.DataSVO;
import nc.vo.wa.paydata.DataVO;
import nc.vo.wa.periodsate.WaPeriodstateVO;
import nc.vo.wa.pub.WaLoginContext;
import nc.vo.wa.pub.WaLoginVO;
import nccloud.message.vo.NCCMessage;
import nccloud.message.vo.NCCNoticeMessageVO;

public class PaydataExServiceImpl implements IPaydataExService {
	
	private BaseDAO baseDAO;
	
	public BaseDAO getBaseDAO() {
		if(baseDAO == null) {
			baseDAO = new BaseDAO();
		}
		return baseDAO;
	}

	@Override
	public void onSendMsg(WaLoginVO waLoginVO, String whereCondition) throws BusinessException {
		IPaydataQueryService service = NCLocator.getInstance().lookup(IPaydataQueryService.class);
		//查询所有人员工资信息
		DataVO[] dataVOs = service.queryDataVOsByCond(waLoginVO.toWaLoginContext(), whereCondition, null);
		
		List<NCCMessage> nccMessages = new ArrayList();
		if(dataVOs != null && dataVOs.length > 0) {
			for(DataVO dataVO : dataVOs) {
				NCCMessage nccMessage = getNCCMessage(dataVO);
				if(nccMessage != null) {
					nccMessages.add(nccMessage);
				}
			}
		}
		
		if(nccMessages.size()>0) {
			try {
				String[] pk_message = nccloud.message.util.MessageCenter.sendMessage(nccMessages.toArray(new NCCMessage[nccMessages.size()]));
				System.out.println("====");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	private NCCMessage getNCCMessage(DataVO dataVO) {
		NCCNoticeMessageVO nccNoticeMessageVO = new NCCNoticeMessageVO();
		
		String subject = dataVO.getCyear()+"年度"+dataVO.getCperiod()+"月度工资已发放，请注意查收";
		
		nccNoticeMessageVO.setSubject(subject);
		nccNoticeMessageVO.setContent(subject);
		nccNoticeMessageVO.setPk_group(AppContext.getInstance().getPkGroup());
		
		String sql = "select cuserid from sm_user where pk_psndoc = '"+dataVO.getPk_psndoc()+"'";
		String receiver = "";
		try {
			receiver = (String) getBaseDAO().executeQuery(sql, new ColumnProcessor());
		} catch (DAOException e) {
			e.printStackTrace();
		}
		if(receiver == null || "".equals(receiver)) {
			return null;
		}
		nccNoticeMessageVO.setReceiver(receiver);
		
		nccNoticeMessageVO.setSender("NC_USER0000000000000");
		nccNoticeMessageVO.setContenttype("BIZ");
		nccNoticeMessageVO.setMsgsourcetype("notice");
		nccNoticeMessageVO.setMsgtype("nc");
		nccNoticeMessageVO.setPriority(0);
		nccNoticeMessageVO.setReceipt(UFBoolean.FALSE);
		nccNoticeMessageVO.setResendtimes(0);
		nccNoticeMessageVO.setSendstate(UFBoolean.TRUE);
		nccNoticeMessageVO.setCanBatch(UFBoolean.FALSE);
		nccNoticeMessageVO.setSendtime(new UFDateTime());
		nccNoticeMessageVO.setWorkflowtype(null);
		nccNoticeMessageVO.setActions(null);
		nccNoticeMessageVO.setBillid(null);
		nccNoticeMessageVO.setBillno(null);
		nccNoticeMessageVO.setBilltype(null);
		nccNoticeMessageVO.setDetail(null);
		nccNoticeMessageVO.setDomainflag(null);
		nccNoticeMessageVO.setFunccode(null);
		nccNoticeMessageVO.setFuncid(null);
		nccNoticeMessageVO.setPk_message(null);
		nccNoticeMessageVO.setPk_org(null);
		nccNoticeMessageVO.setParams(null);
		nccNoticeMessageVO.setPk_detail(null);
		
		NCCMessage nccMessage = new NCCMessage();
		nccMessage.setMessage(nccNoticeMessageVO);
		nccMessage.setMessageType("notice");
		
		return nccMessage;
	}

	
	
	private String getPeriodstateCond(String pk_wa_class, String cyear, String cperiod) { return " pk_wa_class = '" + pk_wa_class + "' and exists (select wa_period.pk_wa_period  from wa_period  where wa_period.pk_wa_period = wa_periodstate.pk_wa_period and wa_period.cyear =  '" + cyear + "' and wa_period.cperiod =  '" + cperiod + "' and  wa_periodstate.pk_wa_class =  '" + pk_wa_class + "')"; }

	@Override
	public Boolean checkPeriodstate(WaLoginVO waLoginVO) throws BusinessException {
		Boolean resultFlag = Boolean.FALSE;
		String cond = getPeriodstateCond(waLoginVO.getPk_prnt_class(), waLoginVO.getCyear(), waLoginVO.getCperiod());
		String sql = "select * from wa_periodstate where "+ cond;
		WaPeriodstateVO waPeriodstateVO = (WaPeriodstateVO) getBaseDAO().executeQuery(sql, new BeanProcessor(WaPeriodstateVO.class));	
		if(waPeriodstateVO != null && waPeriodstateVO.getPayoffflag().booleanValue()) {
			resultFlag = Boolean.TRUE;
		}
		return resultFlag;
	}

	@Override
	public DataVO queryWaData(String pk_wa_data) throws BusinessException {
		return (DataVO) getBaseDAO().retrieveByPK(DataVO.class, pk_wa_data);
	}

	@Override
	public Map<String, Object> querySql(String sql) throws BusinessException {
		return (Map<String, Object>) getBaseDAO().executeQuery(sql, new MapProcessor());
	}
	
	@Override
	public DataSVO[] getDataSVOs(WaLoginContext loginContext) throws BusinessException {
		// TODO 增加人员权限
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select wa_datas.pk_wa_data, "); // 1
		sqlBuffer.append("       wa_datas.pk_wa_datas, "); // 2
		sqlBuffer.append("       wa_datas.pk_wa_classitem, "); // 3
		sqlBuffer.append("       wa_datas.ts, "); // 4
		sqlBuffer.append("       wa_datas.value, "); // 5
		sqlBuffer.append("       wa_datas.to_next, "); // 5
		sqlBuffer.append("       wa_datas.modifier, "); // 5
		sqlBuffer.append("       wa_datas.caculatevalue, "); // 6
		sqlBuffer.append("       wa_datas.notes, "); // 7
		sqlBuffer.append("       wa_item.itemkey itemkey, "); // 8
		sqlBuffer.append("        " + SQLHelper.getMultiLangNameColumn("wa_classitem.name") + "  itemname, "); // 8
		sqlBuffer.append("        " + SQLHelper.getMultiLangNameColumn("bd_psndoc.name") + "  " + "psnname" + ", "); // 9
		sqlBuffer.append("       wa_classitem.iflddecimal, "); // 10
		sqlBuffer.append("       bd_psndoc.code " + "psncode" + ", "); // 11
		sqlBuffer.append("       hi_psnjob.clerkcode, "); // 3
		sqlBuffer.append("       wa_data.checkflag "); // 12
		sqlBuffer.append("  from wa_datas ");
		sqlBuffer.append(" inner join wa_data on wa_datas.pk_wa_data = wa_data.pk_wa_data ");
		sqlBuffer.append(" inner join hi_psnjob on wa_data.pk_psnjob = hi_psnjob.pk_psnjob ");
		sqlBuffer.append(" inner join bd_psndoc on wa_data.pk_psndoc = bd_psndoc.pk_psndoc ");
		sqlBuffer.append(" inner join wa_classitem on wa_datas.pk_wa_classitem = wa_classitem.pk_wa_classitem ");
		sqlBuffer.append(" inner join wa_item on wa_classitem.pk_wa_item = wa_item.pk_wa_item ");

		sqlBuffer.append(
				WherePartUtil.addWhereKeyWord2Condition(getCommonWhereCondtion4Data(loginContext.getWaLoginVO())));
//		String powerSql = WaPowerSqlHelper.getWaPowerSql(loginContext.getPk_group(), IHRWADataResCode.WADATA,
//				IHRWAActionCode.SpecialPsnAction, "hi_psnjob");
//		if (!StringUtils.isBlank(powerSql)) {
//			sqlBuffer.append(" and " + powerSql);
//		}
//		powerSql = WaPowerSqlHelper.getWaPowerSql(loginContext.getPk_group(), HICommonValue.RESOUCECODE_6007PSNJOB,
//				IHRWADataResCode.WADEFAULT, "wa_data");
//		if (!StringUtil.isEmptyWithTrim(powerSql)) {
//			sqlBuffer.append(" and " + powerSql);
//		}
		sqlBuffer.append("  and  wa_item.pk_wa_item in (" + ItemPowerUtil.getItemPower(loginContext) + ")");
		sqlBuffer.append(" order by wa_datas.pk_wa_data, wa_datas.pk_wa_classitem");
		List<DataSVO> list = (List<DataSVO>) getBaseDAO().executeQuery(sqlBuffer.toString(), new BeanListProcessor(DataSVO.class));
		return list.toArray(new DataSVO[0]);
	}
	
	public static String getCommonWhereCondtion4Data(WaLoginVO waLoginVO) {
	     StringBuffer sqlBuffer = new StringBuffer();
	     if (waLoginVO.getBatch() != null && waLoginVO.getBatch().intValue() > 100) {
	       sqlBuffer.append("  wa_data.pk_wa_class in (select pk_childclass from wa_inludeclass where pk_parentclass = '" + waLoginVO.getPk_prnt_class() + "' and batch > 100) ");
	     } else {
	       sqlBuffer.append("  wa_data.pk_wa_class = '" + waLoginVO.getPk_wa_class() + "' ");
	     } 
	     sqlBuffer.append("   and wa_data.cyear = '" + waLoginVO.getPeriodVO().getCyear() + "' ");
	     sqlBuffer.append("   and wa_data.cperiod = '" + waLoginVO.getPeriodVO().getCperiod() + "' ");
	     sqlBuffer.append("   and wa_data.stopflag = 'N'");
	     
//	     String powerSql = WaPowerSqlHelper.getWaPowerSql(waLoginVO.getPk_group(), "6007psnjob", "wadefault", "wa_data");
//	     
//	     if (!StringUtil.isEmptyWithTrim(powerSql)) {
//	       sqlBuffer.append(" and " + powerSql);
//	     }
//	     powerSql = WaPowerSqlHelper.getWaPowerSql(waLoginVO.getPk_group(), "wa_data", "SpecialPsnAction", "hi_psnjob");
//	     if (!StringUtils.isBlank(powerSql)) {
//	       sqlBuffer.append(" and " + powerSql);
//	     }
	     
	     return sqlBuffer.toString();
	   }
}
