package nc.impl.fa.byzimpl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
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.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.itf.fa.byzitf.IAssetInfoToByzService;
import nc.itf.fa.byzitf.ICardtoByzHanld;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.pubitf.para.ISysInitDAO;
import nc.vo.fa.assetcard.AggCardVO;
import nc.vo.fa.assetcard.CardVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

public class AssetcardInfoSendToBYZTask implements IBackgroundWorkPlugin {
	ISysInitDAO InitDAO = NCLocator.getInstance().lookup(ISysInitDAO.class);

	@Override
	public PreAlertObject executeTask(BgWorkingContext bgwc) throws BusinessException {
		LinkedHashMap<String, Object> keyMap = bgwc.getKeyMap();
		List<Map<String, String>> list = selectCardByDateAndOrg(keyMap.get("business_date_start"),
				keyMap.get("business_date_end"), keyMap.get("org"), keyMap.get("asset_code"));

		//IAssetInfoToByzService byz = NCLocator.getInstance().lookup(IAssetInfoToByzService.class);
		String[] keyList = new String[list.size()];
		int i = 0;
		for (Map<String, String> map : list) {
			keyList[i] = map.get("pk_card");
			i++;
		}

		/*
		 * for(int i=0;i<list.size();++i) { //{"pk_card=YYYXXXXX"} String str
		 * =((Object)list.get(i)).toString().replaceAll("\\pk_card=", ""); keyList[i] =
		 * str.replace(str.charAt(str.length()-1)+"", "").replaceFirst("\\{", ""); }
		 */

		List<AggCardVO> aggList = new ArrayList<AggCardVO>();
		AggCardVO[] aggvo = new BillQuery<AggCardVO>(AggCardVO.class).query(keyList);
		try {
			if (aggvo == null || aggvo.length == 0)
				return null;
			for (int j = 0; j < aggvo.length; j++) {// 增加标识作为后台任务执行的资产卡片
				CardVO headVO = (CardVO) aggvo[j].getParentVO();
				//if (isTime(headVO.getBusiness_date() + ""))
					//continue;
				headVO.setDef70("IDISARC");
				aggvo[j].setParentVO(headVO);
				aggList.add(aggvo[j]);
			}
			
			if(aggList==null||aggList.size()==0)
				return null;
			
			AggCardVO[] sendAgg=aggList.toArray(new AggCardVO[0]);
					
			//byz.sendArc(sendAgg);
			//add by djy 分配提交事务 20220420
			int splitSize = 50;// 分割的块大小
			Object[] subAry = splitAry(sendAgg, splitSize);// 分割后的子块数组
			for (Object obj : subAry) {
				AggCardVO[] aggvos = (AggCardVO[]) obj;
				NCLocator.getInstance().lookup(ICardtoByzHanld.class).sendCardToByz_RequiresNew(aggvos);
			}
			
			
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}

		return null;
	}

	private List<Map<String, String>> selectCardByDateAndOrg(Object business_date_start, Object business_date_end,
			Object org, Object card_code) throws BusinessException {
		String ctime = InitDAO.getSysInitTempVO("cztime").getDefaultvalue();
		StringBuffer sb = new StringBuffer("select pk_card from "
				+ "(select fa_card.pk_card,fa_card.pk_org,fa_card.business_date,fa_card.asset_code from fa_card inner join fa_cardsub on fa_card.pk_card=fa_cardsub.pk_card and fa_card.dr=0 and fa_cardsub.def21!='Y'"
				+ " and fa_card.business_date>='"+ctime+"')"
				+ " where pk_org in(select pk_org from org_orgs where def52 ='true' and dr=0 and enablestate=2)");
//				+ " and business_date >='");
//		if(business_date_start == null) {
//			business_date_start = new UFDate();
//		}
		if (business_date_start != null)
			sb.append(" and business_date >='").append(business_date_start.toString().replaceAll("\\r|\\n", "") + "'");
		if (business_date_start != null)
			sb.append(" and business_date <='").append(business_date_end.toString().replaceAll("\\r|\\n", "") + "'");
//		if(business_date_end == null) {//如果没有填写结束日期,则默认时间至今日
//			business_date_end = new UFDate();
//		}
//		sb.append(business_date_start.toString().replaceAll("\\r|\\n", "")).append("' and business_date <='").append(business_date_end.toString().replaceAll("\\r|\\n", "").substring(0, 10)+" 23:59:59'");
		if (org != null) {
			sb.append(" and pk_org in('").append(org.toString().replaceAll("\\r|\\n", "") + "')");
		}
		if (card_code != null) {
			sb.append("and asset_code ='").append(card_code.toString().replaceAll("\\r|\\n", "") + "'");
		}
//		sb.append("and nvl(dr,0) = 0"); 
		BaseDAO dao = new BaseDAO();
		try {
			List<Map<String, String>> list = (List<Map<String, String>>) dao.executeQuery(sb.toString(),
					new MapListProcessor());
			return list;
		} catch (DAOException e) {
			e.printStackTrace();
		}

		return null;
	}

//	private boolean isTime(String time) throws Exception {
//		boolean flag = false;
//		String ctime = InitDAO.getSysInitTempVO("cztime").getDefaultvalue();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Date timedate = sdf.parse(time);
//		Date ctimedate = sdf.parse(ctime);
//		if (timedate.compareTo(ctimedate) < 0)
//			return true;
//		return flag;
//	}
	
	private static Object[] splitAry(AggCardVO[] ary, int subSize) {
		int count = ary.length % subSize == 0 ? ary.length / subSize : ary.length / subSize + 1;

		List<List<AggCardVO>> subAryList = new ArrayList<List<AggCardVO>>();

		for (int i = 0; i < count; i++) {
			int index = i * subSize;
			List<AggCardVO> list = new ArrayList<AggCardVO>();
			int j = 0;
			while (j < subSize && index < ary.length) {
				list.add(ary[index++]);
				j++;
			}
			subAryList.add(list);
		}

		Object[] subAry = new Object[subAryList.size()];

		for (int i = 0; i < subAryList.size(); i++) {
			List<AggCardVO> subList = subAryList.get(i);
			AggCardVO[] subAryItem = new AggCardVO[subList.size()];
			for (int j = 0; j < subList.size(); j++) {
				subAryItem[j] = subList.get(j);
			}
			subAry[i] = subAryItem;
		}
		return subAry;
	}
}
