package nc.bs.arap.pay.bgtask.process;

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.process.NC63F4F5ToNCCF2F3MakeBill;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.itf.arap.nc63.bill.IPullNC63Bill;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.vo.arap.nc63.pay.CMPPaybillVO_NC63;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.arap.pay.PayBillItemVO;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.pf.pub.util.SQLUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
/**
 * @Description: 
 * 		【拉取NC633内转付[F5-Cxx-2 内部单位转账（付方）]->NCC付款单[F3-Cxx-D01 付款单（内转）]】
 * @author 谢文如 【碧桂园物业NCC】
 * @date 2020-11-23
 * @version with NCC V2005
 */
@SuppressWarnings("unchecked")
public class NC63F5ToNCCF3MakeBillProcess extends NC63F4F5ToNCCF2F3MakeBill{
	
	public Map<String,Integer> makeBill(LinkedHashMap<String, Object> paraMap) throws BusinessException {
		Map<String,Integer> map = new HashMap<String,Integer>();
		int edit_success = 0;
		int edit_error = 0;
		int add_success = 0;
		int add_error = 0;
		map.put("edit_success", edit_success);
		map.put("edit_error", edit_error);
		map.put("add_success", add_success);
		map.put("add_error", add_error);
		BaseDAO dao = new BaseDAO();
		//锁表
		dao.executeUpdate("select ts from nc63_cmp_paybill for update");
		
		StringBuffer sqlstr = new StringBuffer("");
		sqlstr.append("select 'NC63' def21,").append("\r\n");
		sqlstr.append("       -1 APPROVESTATUS,").append("\r\n");
		sqlstr.append("       -1 BILLSTATUS,").append("\r\n");
		sqlstr.append("       'fk' BILLCLASS,").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("       0 EFFECTSTATUS,").append("\r\n");
		sqlstr.append("       0 GLOBALLOCAL,").append("\r\n");
		sqlstr.append("       0 GROUPLOCAL,").append("\r\n");
		sqlstr.append("       'N' ISFLOWBILL,").append("\r\n");
		sqlstr.append("       'N' ISFORCE,").append("\r\n");
		sqlstr.append("       'N' ISFROMINDEPENDENT,").append("\r\n");
		sqlstr.append("       'N' ISINIT,").append("\r\n");
		sqlstr.append("       'N' ISMANDATEPAY,").append("\r\n");
		sqlstr.append("       'N' ISNETPAYREADY,").append("\r\n");
		sqlstr.append("       'N' ISONLINEPAY,").append("\r\n");
		sqlstr.append("       'N' ISREDED,").append("\r\n");
		sqlstr.append("       'N' ISREFUND,").append("\r\n");
		sqlstr.append("       'N' ISURGENT,").append("\r\n");
		sqlstr.append("       1 LOCAL_MONEY,").append("\r\n");
		sqlstr.append("       1 MONEY,").append("\r\n");
		sqlstr.append("       'N' SDDREVERSALFLAG,").append("\r\n");
		sqlstr.append("       0 SETTLEFLAG,").append("\r\n");
		sqlstr.append("       0 SETTLETYPE,").append("\r\n");
		sqlstr.append("       1 SRC_SYSCODE,").append("\r\n");
		sqlstr.append("       1 SYSCODE,").append("\r\n");
		sqlstr.append("       'F3' PK_BILLTYPE,").append("\r\n");
		sqlstr.append("       'F3-Cxx-D01' PK_TRADETYPE,").append("\r\n");
		sqlstr.append("       '1002Z0100000000001K1' PK_CURRTYPE,").append("\r\n");
		sqlstr.append("       '0001Z010000000079UJJ' RECECOUNTRYID,").append("\r\n");
		sqlstr.append("       '0001Z010000000079UJJ' TAXCOUNTRYID,").append("\r\n");
		sqlstr.append("       nc63.bill_no def25,").append("\r\n");
		sqlstr.append("       nc63.def29 scomment,").append("\r\n");
		sqlstr.append("       bt.pk_billtypeid PK_TRADETYPEID,").append("\r\n");
		sqlstr.append("       nc63.settledate BILLDATE,").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_GROUP,").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("       nc63.pk_paybill def34,").append("\r\n");
		sqlstr.append("       nc63.nc63ts def35,").append("\r\n");
		sqlstr.append("       ncc.pk_paybill pk_paybill").append("\r\n");
		sqlstr.append("  from nc63_cmp_paybill 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.pk_tradetypeid").append("\r\n");
		sqlstr.append("  left join ap_paybill ncc").append("\r\n");
		sqlstr.append("    on ncc.def25 = nc63.bill_no").append("\r\n");
		sqlstr.append("   and ncc.def21 = 'NC63'").append("\r\n");
		sqlstr.append("   and ncc.def34 = nc63.pk_paybill").append("\r\n");
		sqlstr.append("   and nvl(ncc.dr, 0) = 0").append("\r\n");
		sqlstr.append(" where (nvl(ncc.pk_paybill,'xwr')<>'xwr' and nc63.state = 'Y' ").append("\r\n");
		sqlstr.append(" and nc63.nc63ts>decode(ncc.def35,null,'1900-01-01','~','1900-01-01',ncc.def35)) or nc63.state = 'N'"); 

		List<PayBillVO> headVOList = (List<PayBillVO>)dao.executeQuery(sqlstr.toString(), new BeanListProcessor(PayBillVO.class));
		if(headVOList==null || headVOList.size()==0) {
			return map;
		}
		
		List<String> nc63HidList = headVOList.stream().map(PayBillVO::getDef34).collect(Collectors.toList());
		String wheresql = SQLUtil.buildSqlForIn("nc63.pk_paybill", nc63HidList.toArray(new String[0]));
		//表体
		sqlstr = new StringBuffer("");
		sqlstr.append("select 0 AGENTRECEIVELOCAL,").append("\r\n");
		sqlstr.append("       0 AGENTRECEIVEPRIMAL,").append("\r\n");
		sqlstr.append("       'fk' BILLCLASS,").append("\r\n");
		sqlstr.append("       2 BUYSELLFLAG,").append("\r\n");
		sqlstr.append("       'N' DIRECT_CHECKNO,").append("\r\n");
		sqlstr.append("       1 DIRECTION,").append("\r\n");
		sqlstr.append("       0 FORCEMONEY,").append("\r\n");
		sqlstr.append("       0 GLOBALAGENTRECEIVELOCAL,").append("\r\n");
		sqlstr.append("       0 GLOBALBALANCE,").append("\r\n");
		sqlstr.append("       0 GLOBALDEBIT,").append("\r\n");
		sqlstr.append("       0 GLOBALNOTAX_DE,").append("\r\n");
		sqlstr.append("       0 GLOBALRATE,").append("\r\n");
		sqlstr.append("       0 GLOBALTAX_DE,").append("\r\n");
		sqlstr.append("       0 GROUPAGENTRECEIVELOCAL,").append("\r\n");
		sqlstr.append("       0 GROUPBALANCE,").append("\r\n");
		sqlstr.append("       0 GROUPDEBIT,").append("\r\n");
		sqlstr.append("       0 GROUPNOTAX_DE,").append("\r\n");
		sqlstr.append("       0 GROUPRATE,").append("\r\n");
		sqlstr.append("       0 GROUPTAX_DE,").append("\r\n");
		sqlstr.append("       'Y' ISDISCOUNT,").append("\r\n");
		sqlstr.append("       'N' ISREFUSED,").append("\r\n");
		sqlstr.append("       'N' ISURGENT,").append("\r\n");
		sqlstr.append("       0 LOCAL_MONEY_BAL,").append("\r\n");
		sqlstr.append("       0 LOCAL_PRICE,").append("\r\n");
		sqlstr.append("       0 LOCAL_TAX_DE,").append("\r\n");
		sqlstr.append("       0 LOCAL_TAXPRICE,").append("\r\n");
		sqlstr.append("       0 MONEY_BAL,").append("\r\n");
		sqlstr.append("       0 NOSUBTAX,").append("\r\n");
		sqlstr.append("       0 NOSUBTAXRATE,").append("\r\n");
		sqlstr.append("       0 TAX_DE,").append("\r\n");
		sqlstr.append("       0 TAXPRICE,").append("\r\n");
		sqlstr.append("       0 TAXRATE,").append("\r\n");
		sqlstr.append("       1 TAXTYPE,").append("\r\n");
		sqlstr.append("       1 OBJTYPE,").append("\r\n");
		sqlstr.append("       0 OCCUPATIONMNY,").append("\r\n");
		sqlstr.append("       0 PREPAY,").append("\r\n");
		sqlstr.append("       0 QUANTITY_BAL,").append("\r\n");
		sqlstr.append("       0 SETTLEMONEY,").append("\r\n");
		sqlstr.append("       1 RATE,").append("\r\n");
		sqlstr.append("       'N' PAUSETRANSACT,").append("\r\n");
		sqlstr.append("       '1002Z0100000000001K1' PK_CURRTYPE,").append("\r\n");
		sqlstr.append("       '0001Z010000000079UJJ' SENDCOUNTRYID,").append("\r\n");
		sqlstr.append("       'F3' PK_BILLTYPE,").append("\r\n");
		sqlstr.append("       'F3-Cxx-D01' PK_TRADETYPE,").append("\r\n");
		sqlstr.append("       '' PK_TRADETYPEID,").append("\r\n");
		sqlstr.append("       rt.pk_recpaytype PK_RECPAYTYPE,").append("\r\n");
		sqlstr.append("       sr.pk_supplier SUPPLIER,").append("\r\n");
		sqlstr.append("       WYFW085.Pk_Defdoc def41,").append("\r\n");
		sqlstr.append("       ZJJHXM_63.Pk_Defdoc def42,").append("\r\n");
		sqlstr.append("       cf.pk_cashflow def43,").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("       nc63.memo SCOMMENT,").append("\r\n");
		sqlstr.append("       nc63.pay_local LOCAL_MONEY_DE,").append("\r\n");
		sqlstr.append("       nc63.pay_local LOCAL_NOTAX_DE,").append("\r\n");
		sqlstr.append("       nc63.pay_primal MONEY_DE,").append("\r\n");
		sqlstr.append("       nc63.pay_primal NOTAX_DE,").append("\r\n");
		sqlstr.append("       accasoa.pk_accasoa subjcode,").append("\r\n");
		sqlstr.append("       pjn.pk_project def39,").append("\r\n");
		sqlstr.append("       nc63.pk_paybill_detail def38,").append("\r\n");
		sqlstr.append("       nc63.pk_paybill src_billid").append("\r\n");
		sqlstr.append("  from nc63_cmp_paybilldetail nc63").append("\r\n");
		sqlstr.append("  left join bd_supplier sr").append("\r\n");
		sqlstr.append("    on sr.code = nc63.pk_supplier").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 (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 nc63_cmp_paybill nc63h").append("\r\n");
		sqlstr.append("    on nc63.pk_paybill = nc63h.pk_paybill").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 (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("  left join bd_project pjn").append("\r\n");
		sqlstr.append("    on pjn.project_code = nc63.zyx26 and pjn.pk_org = org.pk_financeorg").append("\r\n");
		sqlstr.append("   where "+wheresql);
		List<PayBillItemVO> bodyVOList = (List<PayBillItemVO>)dao.executeQuery(sqlstr.toString(), new BeanListProcessor(PayBillItemVO.class));
		
		if(bodyVOList==null || bodyVOList.size()==0) {
			return map;
		}
		Map<String,List<PayBillItemVO>> headBodyMap = new HashMap<String,List<PayBillItemVO>>();
		for(PayBillItemVO bVO:bodyVOList) {
			String src_billid = bVO.getSrc_billid();
			List<PayBillItemVO> bVOs = headBodyMap.get(src_billid);
			if(bVOs==null) {
				bVOs = new ArrayList<PayBillItemVO>();
			}
			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(PayBillVO o:headVOList) {
			AggPayBillVO aggVO = new AggPayBillVO();
			List<PayBillItemVO> bVOs = headBodyMap.get(o.getDef34());
			if(bVOs==null || bVOs.size()==0) {
				CMPPaybillVO_NC63 rsVO = new CMPPaybillVO_NC63();
				rsVO.setPk_paybill(o.getDef34());
				rsVO.setMsg("无表体");
				rsVO.setState("N");
				nc63List.add(rsVO);
				continue;
			}
			aggVO.setParentVO(o);
			aggVO.setChildrenVO(bVOs.toArray(new PayBillItemVO[0]));
			//更新环境变量日期
			InvocationInfoProxy.getInstance().setBizDateTime(o.getBilldate().getMillis());
			if(o.getPk_paybill()!=null) {
				//修改
				AggPayBillVO queryAggVO = queryService.queryBillOfVOByPK(AggPayBillVO.class, o.getPk_paybill(), false);
				//删除
				SuperVO rsVO = pullNC63Bill.delBill_RequiresNew(queryAggVO);
				if(rsVO.getAttributeValue("msg")==null) {
					//新增
					aggVO.getHeadVO().setPk_paybill(null);
					rsVO = pullNC63Bill.makeBill_RequiresNew(aggVO);
					nc63List.add(rsVO);
					if("Y".equals(rsVO.getAttributeValue("state"))) {
						edit_success++;
					}else {
						edit_error++;
					}
				}else {
					edit_error++;
					nc63List.add(rsVO);
				}
			}else {
				//新增
				SuperVO rsVO = pullNC63Bill.makeBill_RequiresNew(aggVO);
				nc63List.add(rsVO);
				if("Y".equals(rsVO.getAttributeValue("state"))) {
					add_success++;
				}else {
					add_error++;
				}
			}
		}
		if(nc63List.size()>0) {
			String[] fieldNames = {"state","msg"};
			dao.updateVOArray(nc63List.toArray(new CMPPaybillVO_NC63[0]), fieldNames);
		}
		map.put("edit_success", edit_success);
		map.put("edit_error", edit_error);
		map.put("add_success", add_success);
		map.put("add_error", add_error);
		
		return map;
	}
	
}
