package nc.bs.arap.pay.bgtask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import nc.bs.arap.bill.bgtask.AbstractNC63F4F5ToNCCF2F3;
import nc.bs.arap.pay.bgtask.process.NC63F5ToNCCF3MakeBillProcess;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.pa.PreAlertReturnType;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.itf.arap.nc63.bill.IPullNC63Bill;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.log.arap.bill.WYNCCARAPLogger;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.vo.arap.gathering.AggGatheringBillVO;
import nc.vo.arap.gathering.GatheringBillItemVO;
import nc.vo.arap.gathering.GatheringBillVO;
import nc.vo.arap.nc63.gathering.CMPRecBillVO_NC63;
import nc.vo.pf.pub.util.SQLUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;

/**
 * @Description: 后台任务【拉取NC63同步过来的临时表数据生成内转应收单】
 * 
 * @author wby
 * @date 2021-12-01
 * @version with NCC V2005
 */
@SuppressWarnings({"deprecation"})
public class GenNC63F4ToNCCF2TaskPlugin implements IBackgroundWorkPlugin {
	
	@Override
	public PreAlertObject executeTask(BgWorkingContext context) throws BusinessException {
		String returnObj = "";
		//获取临时表数据
		genBill();
		
		PreAlertObject retObj = new PreAlertObject();
		retObj.setReturnType(PreAlertReturnType.RETURNMESSAGE);
		retObj.setMsgTitle("后台任务拉取NC63内转付生成NCC付款单(内转)");
		retObj.setReturnObj(returnObj);
		context.setLogStr(returnObj);
		return retObj;
	}
	
	
	private void genBill() throws BusinessException {
		BaseDAO dao = new BaseDAO();
		
		StringBuffer sqlstr = new StringBuffer("");
		sqlstr.append("select -1 APPROVESTATUS,").append("\r\n");
		sqlstr.append("       'NC63' def11,").append("\r\n");
		sqlstr.append("       'sk' BILLCLASS,").append("\r\n");
		sqlstr.append("       -1 BILLSTATUS,").append("\r\n");
		sqlstr.append("       0 EFFECTSTATUS,").append("\r\n");
		sqlstr.append("       0 GLOBALLOCAL,").append("\r\n");
		sqlstr.append("       0 GROUPLOCAL,").append("\r\n");
		sqlstr.append("       'F2' PK_BILLTYPE,").append("\r\n");
		sqlstr.append("       '1002Z0100000000001K1' PK_CURRTYPE,").append("\r\n");
		sqlstr.append("       'F2-Cxx-01' PK_TRADETYPE,").append("\r\n");
		sqlstr.append("       'N' SDDREVERSALFLAG,").append("\r\n");
		sqlstr.append("       '0001Z010000000079UJJ' SENDCOUNTRYID,").append("\r\n");
		sqlstr.append("       '0001Z010000000079UJJ' TAXCOUNTRYID,").append("\r\n");
		sqlstr.append("       0 SRC_SYSCODE,").append("\r\n");
		sqlstr.append("       0 SYSCODE,").append("\r\n");
		sqlstr.append("       org.pk_financeorg PK_FIORG,").append("\r\n");
		sqlstr.append("       org.pk_vid PK_FIORG_V,").append("\r\n");
		sqlstr.append("       org.pk_financeorg PK_ORG,").append("\r\n");
		sqlstr.append("       org.pk_vid PK_ORG_V,").append("\r\n");
		sqlstr.append("       org.pk_financeorg SETT_ORG,").append("\r\n");
		sqlstr.append("       org.pk_vid SETT_ORG_V,").append("\r\n");
		sqlstr.append("       org.pk_group PK_GROUP,").append("\r\n");
		sqlstr.append("       nc63.settledate BILLDATE,").append("\r\n");
		sqlstr.append("       substr(nc63.settledate, 0, 4) BILLYEAR,").append("\r\n");
		sqlstr.append("       substr(nc63.settledate, 6, 2) BILLPERIOD,").append("\r\n");
		sqlstr.append("       bt.pk_billtypeid PK_TRADETYPEID,").append("\r\n");
		sqlstr.append("       nc63.def2 def5,").append("\r\n");
		sqlstr.append("       nc63.bill_no def3,").append("\r\n");
		sqlstr.append("       nc63.def29 scomment,").append("\r\n");
		sqlstr.append("       nc63.pk_recbill def12,").append("\r\n");
		sqlstr.append("       nc63.nc63ts def18,").append("\r\n");
		sqlstr.append("       ncc.pk_gatherbill pk_gatherbill").append("\r\n");
		sqlstr.append("  from nc63_cmp_recbill nc63").append("\r\n");
		sqlstr.append("  left join org_financeorg org").append("\r\n");
		sqlstr.append("    on nc63.pk_org = org.code").append("\r\n");
		sqlstr.append("  left join bd_billtype bt").append("\r\n");
		sqlstr.append("    on bt.pk_billtypecode = nc63.trade_type").append("\r\n");
		sqlstr.append("  left join ar_gatherbill ncc").append("\r\n");
		sqlstr.append("    on ncc.def3 = nc63.bill_no").append("\r\n");
		sqlstr.append("   and ncc.def11 = 'NC63'").append("\r\n");
		sqlstr.append("   and ncc.def12 = nc63.pk_recbill").append("\r\n");
		sqlstr.append("   and nvl(ncc.dr, 0) = 0").append("\r\n");
		sqlstr.append(" where (nvl(ncc.pk_gatherbill,'xwr')<>'xwr' and nc63.state = 'Y' ").append("\r\n");
		sqlstr.append(" and nc63.nc63ts>decode(ncc.def18,null,'1900-01-01','~','1900-01-01',ncc.def18)) or nc63.state = 'N'"); 

		List<GatheringBillVO> headVOList = (List<GatheringBillVO>)dao.executeQuery(sqlstr.toString(), new BeanListProcessor(GatheringBillVO.class));
		if(headVOList==null || headVOList.size()==0) {
			return;
		}
		
		List<String> nc63HidList = headVOList.stream().map(GatheringBillVO::getDef12).collect(Collectors.toList());
		String wheresql = SQLUtil.buildSqlForIn("nc63.pk_recbill", nc63HidList.toArray(new String[0]));
		//表体
		sqlstr = new StringBuffer("");
		sqlstr.append("select 'sk' BILLCLASS,").append("\r\n");
		sqlstr.append("       1 BUYSELLFLAG,").append("\r\n");
		sqlstr.append("       -1 DIRECTION,").append("\r\n");
		sqlstr.append("       'N' isdiscount,").append("\r\n");
		sqlstr.append("       'N' ISREFUSED,").append("\r\n");
		sqlstr.append("       0 OBJTYPE,").append("\r\n");
		sqlstr.append("       'N' PAUSETRANSACT,").append("\r\n");
		sqlstr.append("       1 RATE,").append("\r\n");
		sqlstr.append("       1 RECACCOUNT,").append("\r\n");
		sqlstr.append("       1 TAXTYPE,").append("\r\n");
		sqlstr.append("       'N' TRIATRADEFLAG,").append("\r\n");
		sqlstr.append("       0 prepay,").append("\r\n");
		sqlstr.append("       0 LOCAL_PRICE,").append("\r\n");
		sqlstr.append("       0 LOCAL_TAXPRICE,").append("\r\n");
		sqlstr.append("       0 QUANTITY_BAL,").append("\r\n");
		sqlstr.append("       '1002Z0100000000001K1' PK_CURRTYPE,").append("\r\n");
		sqlstr.append("       '0001Z010000000079UJJ' RECECOUNTRYID,").append("\r\n");
		sqlstr.append("       WYFW085.Pk_Defdoc def31,").append("\r\n");
		sqlstr.append("       ZJJHXM_63.Pk_Defdoc def42,").append("\r\n");
		sqlstr.append("       cf.pk_cashflow def33,").append("\r\n");
		sqlstr.append("       WYZJ001.factorvalue2 pk_subjcode,").append("\r\n");
		sqlstr.append("       WYZJ001.def1 bankrollprojet,").append("\r\n");
		sqlstr.append("       WYZJ001.def2 cashitem,").append("\r\n");
		sqlstr.append("       rt.pk_recpaytype,").append("\r\n");
		sqlstr.append("       nc63h.settledate BUSIDATE,").append("\r\n");
		sqlstr.append("       nc63.rec_local local_money_bal,").append("\r\n");
		sqlstr.append("       nc63.rec_local LOCAL_MONEY_CR,").append("\r\n");
		sqlstr.append("       nc63.rec_local LOCAL_NOTAX_CR,").append("\r\n");
		sqlstr.append("       nc63.rec_primal MONEY_BAL,").append("\r\n");
		sqlstr.append("       nc63.rec_primal MONEY_CR,").append("\r\n");
		sqlstr.append("       nc63.rec_local NOTAX_CR,").append("\r\n");
		sqlstr.append("       nc63.rec_local OCCUPATIONMNY,").append("\r\n");
		sqlstr.append("       nc63.memo scomment,").append("\r\n");
		sqlstr.append("       ct.pk_customer ORDERCUBASDOC,").append("\r\n");
		sqlstr.append("       ct.pk_customer CUSTOMER,").append("\r\n");
		sqlstr.append("       accasoa.pk_accasoa subjcode,").append("\r\n");
		sqlstr.append("       org.pk_financeorg PK_FIORG,").append("\r\n");
		sqlstr.append("       org.pk_vid PK_FIORG_V,").append("\r\n");
		sqlstr.append("       org.pk_financeorg SETT_ORG,").append("\r\n");
		sqlstr.append("       org.pk_vid SETT_ORG_V,").append("\r\n");
		sqlstr.append("       pjn.pk_project def19,").append("\r\n");
		sqlstr.append("       nc63.pk_recbill_detail def11,").append("\r\n");
		sqlstr.append("       nc63.pk_recbill src_billid").append("\r\n");
		sqlstr.append("  from nc63_cmp_recbilldetail nc63").append("\r\n");
		sqlstr.append("  left join bd_customer ct").append("\r\n");
		sqlstr.append("    on ct.code = nc63.pk_customer").append("\r\n");
		sqlstr.append("  left join (select doc.code, doc.pk_defdoc").append("\r\n");
		sqlstr.append("               from bd_defdoclist dl").append("\r\n");
		sqlstr.append("               left join bd_defdoc doc").append("\r\n");
		sqlstr.append("                 on dl.pk_defdoclist = doc.pk_defdoclist").append("\r\n");
		sqlstr.append("              where dl.code = 'WYFW085') WYFW085").append("\r\n");
		sqlstr.append("    on WYFW085.Code = nc63.pk_recproject").append("\r\n");
		sqlstr.append("  left join (select doc.code, doc.pk_defdoc").append("\r\n");
		sqlstr.append("               from bd_defdoclist dl").append("\r\n");
		sqlstr.append("               left join bd_defdoc doc").append("\r\n");
		sqlstr.append("                 on dl.pk_defdoclist = doc.pk_defdoclist").append("\r\n");
		sqlstr.append("              where dl.code = 'ZJJHXM_63') ZJJHXM_63").append("\r\n");
		sqlstr.append("    on ZJJHXM_63.Code = nc63.bankroll_projet").append("\r\n");
		sqlstr.append("  left join bd_cashflow cf").append("\r\n");
		sqlstr.append("    on cf.code = nc63.cash_item").append("\r\n");
		sqlstr.append("  left join (select b.factorvalue1, b.factorvalue2, ioc.def1, ioc.def2").append("\r\n");
		sqlstr.append("               from fip_docview_b b").append("\r\n");
		sqlstr.append("              inner join fip_docview h").append("\r\n");
		sqlstr.append("                 on b.pk_classview = h.pk_classview").append("\r\n");
		sqlstr.append("              inner join bd_inoutbusiclass ioc").append("\r\n");
		sqlstr.append("                 on b.factorvalue2 = ioc.pk_inoutbusiclass").append("\r\n");
		sqlstr.append("              where nvl(h.dr, 0) = 0").append("\r\n");
		sqlstr.append("                and nvl(b.dr, 0) = 0").append("\r\n");
		sqlstr.append("                and h.viewcode = 'WYZJ001') WYZJ001").append("\r\n");
		sqlstr.append("    on WYZJ001.factorvalue1 = WYFW085.Pk_Defdoc").append("\r\n");
		sqlstr.append("  left join fi_recpaytype rt").append("\r\n");
		sqlstr.append("    on rt.code = '009'").append("\r\n");
		sqlstr.append("  left join NC63_CMP_RECBILL nc63h").append("\r\n");
		sqlstr.append("    on nc63.pk_recbill = nc63h.pk_recbill").append("\r\n");
		sqlstr.append("  left join org_financeorg org").append("\r\n");
		sqlstr.append("    on org.code = nc63h.pk_org").append("\r\n");
		sqlstr.append("  left join bd_project pjn").append("\r\n");
		sqlstr.append("    on pjn.project_code = nc63.zyx28 and pjn.pk_org = org.pk_financeorg").append("\r\n");
		sqlstr.append("  left join (select pk_accasoa, ak.pk_relorg").append("\r\n");
		sqlstr.append("               from bd_account acc").append("\r\n");
		sqlstr.append("               left join bd_accasoa soa").append("\r\n");
		sqlstr.append("                 on acc.pk_account = soa.pk_account").append("\r\n");
		sqlstr.append("               left join org_accountingbook ak").append("\r\n");
		sqlstr.append("                 on ak.pk_curraccchart = soa.pk_accchart").append("\r\n");
		sqlstr.append("              where (acc.code = '1221001' and soa.enablestate = '2')) accasoa").append("\r\n");
		sqlstr.append("    on accasoa.pk_relorg = org.pk_financeorg").append("\r\n");
		sqlstr.append("   where " + wheresql);
		List<GatheringBillItemVO> bodyVOList = (List<GatheringBillItemVO>)dao.executeQuery(sqlstr.toString(), new BeanListProcessor(GatheringBillItemVO.class));
		if(bodyVOList==null || bodyVOList.size()==0) {
			return;
		}
		
		Map<String,List<GatheringBillItemVO>> headBodyMap = new HashMap<String,List<GatheringBillItemVO>>();
		for(GatheringBillItemVO bVO:bodyVOList) {
			String src_billid = bVO.getSrc_billid();
			List<GatheringBillItemVO> bVOs = headBodyMap.get(src_billid);
			if(bVOs==null) {
				bVOs = new ArrayList<GatheringBillItemVO>();
			}
			bVO.setSrc_billid(null);
			bVOs.add(bVO);
			headBodyMap.put(src_billid, bVOs);
		}
		
		List<SuperVO> nc63List = new ArrayList<SuperVO>();
		IPullNC63Bill pullNC63Bill = NCLocator.getInstance().lookup(IPullNC63Bill.class);
		IMDPersistenceQueryService queryService = NCLocator.getInstance().lookup(IMDPersistenceQueryService.class);
		for(GatheringBillVO o:headVOList) {
			AggGatheringBillVO aggVO = new AggGatheringBillVO();
			List<GatheringBillItemVO> bVOs = headBodyMap.get(o.getDef12());
			if(bVOs==null || bVOs.size()==0) {
				CMPRecBillVO_NC63 rsVO = new CMPRecBillVO_NC63();
				rsVO.setPk_recbill(o.getDef12());
				rsVO.setMsg("无表体");
				rsVO.setState("N");
				nc63List.add(rsVO);
				continue;
			}
			aggVO.setParentVO(o);
			aggVO.setChildrenVO(bVOs.toArray(new GatheringBillItemVO[0]));
			//更新环境变量日期
			InvocationInfoProxy.getInstance().setBizDateTime(o.getBilldate().getMillis());
			if(o.getPk_gatherbill()!=null) {
				//修改
				AggGatheringBillVO queryAggVO = queryService.queryBillOfVOByPK(AggGatheringBillVO.class, o.getPk_gatherbill(), false);
				//删除
				SuperVO rsVO = pullNC63Bill.delBill_RequiresNew(queryAggVO);
				if(rsVO.getAttributeValue("msg")==null) {
					//新增
					aggVO.getHeadVO().setPk_gatherbill(null);
					rsVO = pullNC63Bill.makeBill_RequiresNew(aggVO);
					nc63List.add(rsVO);
				} else {
					nc63List.add(rsVO);
				}
			}else {
				//新增
				SuperVO rsVO = pullNC63Bill.makeBill_RequiresNew(aggVO);
				nc63List.add(rsVO);
			}
		}
		if(nc63List.size()>0) {
			String[] fieldNames = {"state","msg"};
			dao.updateVOArray(nc63List.toArray(new CMPRecBillVO_NC63[0]), fieldNames);
		}
	}
	
}