package nc.bs.uapbd.mdg.process;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import nc.bs.bd.baseservice.persistence.IPersistenceUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.hr.frame.persistence.IPersistenceDAO;
import nc.impl.pubapp.env.BSContext;
import nc.itf.sap.log.IExtLogService;
import nc.net.pu.utils.HttpReqUtil;
import nc.net.servlet.IReturnStatus;
import nc.ui.bd.pub.extend.PrivateServiceContext;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.mmf.framework.base.MMValueConvert;
import nc.vo.bd.bankaccount.BankAccbasVO;
import nc.vo.bd.bankaccount.cust.CustBankaccUnionVO;
import nc.vo.bd.supplier.SupCountryTaxesVO;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.PubAppTool;
import nc.vo.sap.log.SapPurchaseLogVO;
import nc.vo.uapbd.mdg.JsonTransParamVo;

public class MDGSupplierSynNCPorcess {
	public static String process(JSONObject jsonobj) throws BusinessException{
		String rsdata = null;
		ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
		ResultVO result = new ResultVO();
		result.setResult("");
		esb.setResultInfo(result);
			try {
				InvocationInfoProxy.getInstance().setProperty("isfrommdg", "Y");
				BSContext.getInstance().setSession("isfrommdg", "Y");
				MDGSupplierSynNCPorcess.genSupplier(jsonobj);
				result.setCode(IReturnStatus.SUCCEED);// 成功
				com.alibaba.fastjson.JSONObject resJsonObject=new com.alibaba.fastjson.JSONObject();
				result.setResult(resJsonObject);
				result.setMessage("生成供应商成功");
				HttpReqUtil.createResultEsbVO(esb);
				esb.setResultInfo(result);
			} catch (Exception e) {
				result.setCode(IReturnStatus.ERROR);// 异常
				result.setError(e.getMessage());
				result.setMessage(HttpReqUtil.getExceptionDetail(e));
				HttpReqUtil.createResultEsbVO(esb);// 初始化响应对象
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
				esb.getEsbInfo().setReturnMsg("异常");
				esb.setResultInfo(result);// 设置响应内容
			}finally {
				rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);
			}
		return rsdata;
	}

	private static String genSupplier(JSONObject obj) throws BusinessException {
		SapPurchaseLogVO log = new SapPurchaseLogVO();
		Object billdata = null;
		Object pk_org = null;
		Object billid = null;
		Object billno = "";
		Object mdgcode = "";
		String flag =" Y";
		String msg = null;
		//add by longht 2021-09-14 优化代码-执行同步 前，先删除前N天的历史数据，为空则默认为3个月 及更新中间表逻辑  start
		String  pk = null;
		if(null != obj.get("pk"));
			pk = obj.get("pk").toString();
		//add by longht 2021-09-14 优化代码-执行同步 前，先删除前N天的历史数据，为空则默认为3个月 及更新中间表逻辑  end
		try {
			billdata=obj;
			JsonTransParamVo paramVO = new JsonTransParamVo();
			paramVO.setHeadVOClass(SupplierVO.class);
			paramVO.sethCfgCode("supplier");
			paramVO.getClassMap().put("supptaxtypes", SupCountryTaxesVO.class);
			paramVO.getClassCfgCodeMap().put("supptaxtypes", "supplier_supcountrytaxes");
			paramVO.getRemoveKys().add("suppbanks");
			paramVO.setBilldata(obj.toString());
			SupplierVO supplierVO = (SupplierVO) HttpReqUtil.processNCAction(paramVO);
			mdgcode = supplierVO.getDef9();
			billno = supplierVO.getCode();
			pk_org = supplierVO.getPk_org();
			String[]  pk_suppliers = HttpReqUtil.getSupplierBaseInfoQryService().querySupplierPKsByCondition(null, "nvl(dr,0)=0  and  def9 ='" + supplierVO.getDef9().trim() + "'");
			boolean isAddSupp = false;
			//如果不存在则新增
			if(MMValueCheck.isEmpty(pk_suppliers)){
				isAddSupp = true;
				//执行新增
				supplierVO = HttpReqUtil.getSupBaseInfoExtendService().insertSupplierWithExtendVO(supplierVO, new HashMap<String, Object>(), new PrivateServiceContext(), false);
			}else if(pk_suppliers.length > 1){
				throw new BusinessException("根据供应商MDG编码:" + supplierVO.getDef9() + "查询出多个供应商信息！");
			}else{
				SupplierVO[] updateSupplierVOs = HttpReqUtil.getSupplierBaseInfoQryService().querySupBaseInfoByPks(null, pk_suppliers);

				if(updateSupplierVOs == null){
					throw new BusinessException("根据NCC主键查询不出供应商信息！");
				}
				if(MMValueCheck.isEmpty(supplierVO.getCode())) {
					supplierVO.setCode(updateSupplierVOs[0].getCode());
				}
				HttpReqUtil.converNCVO("supplier", updateSupplierVOs[0],supplierVO);
				supplierVO = HttpReqUtil.getSupBaseInfoExtendService().updateSupplierWithExtendVO(updateSupplierVOs[0], new HashMap<String, Object>(), new PrivateServiceContext(), false);
			}
			billid = supplierVO.getPk_supplier();
			String custbanks = obj.getJSONArray("custbanks").toJSONString();
			List list=(List) filterNone(custbanks);
			if((!obj.containsKey("custbanks") || MMValueCheck.isEmpty(list))) {
				log.setResultdata_sn("银行账户信息为空！");
				msg = "银行账户信息为空！";
				return "Y";
			}
			BankAccbasVO[] bankAccbasVOs = HttpReqUtil.dealBankAccbasVOs(new String[] {"supplier_bankaccbas","supplier_bankaccbas_sub"}, obj.toString());

			if (MMValueCheck.isNotEmpty(bankAccbasVOs)) {
				if(isAddSupp){
					//新增供应商同时新增银行账户
					HttpReqUtil.insertCustBankacc(supplierVO.getPk_supplier(), bankAccbasVOs,3);
				}else{
					//修改供应商信息时，银行账户有可能是新增or修改
					CustBankaccUnionVO[] custBankaccUnionVOs = HttpReqUtil.getCustBankaccQueryService().queryCustBankaccUnionVOsByCust(supplierVO.getPk_supplier(), 3, false);
					List<BankAccbasVO> addBankVOs = new ArrayList<BankAccbasVO>();
					List<CustBankaccUnionVO> updateBankVOs = new ArrayList<CustBankaccUnionVO>();
					Map<String,CustBankaccUnionVO> bankMap = new HashMap<String,CustBankaccUnionVO>();
					BankAccbasVO bankAccbasVO;
					CustBankaccUnionVO custBankaccUnionVO;
					if (MMValueCheck.isNotEmpty(custBankaccUnionVOs)) {
						for(CustBankaccUnionVO vo:custBankaccUnionVOs){
							bankAccbasVO = vo.getBankaccbasVO();
							bankMap.put(bankAccbasVO.getAccnum(), vo);
						}
						for(BankAccbasVO vo:bankAccbasVOs){
							custBankaccUnionVO = bankMap.get(vo.getAccnum());
							if(custBankaccUnionVO != null){
								//修改
								bankAccbasVO = custBankaccUnionVO.getBankaccbasVO();
								if(bankAccbasVO != null){
									HttpReqUtil.converNCVO("supplier_bankaccbas",bankAccbasVO,vo);
									bankAccbasVO.setBankaccsub(null);//把子户信息清空才会拿旧子户的更新
									updateBankVOs.add(custBankaccUnionVO);
								}
							}else{
								//新增
								addBankVOs.add(vo);
							}
						}
					}else{
						//新增
						addBankVOs = Arrays.asList(bankAccbasVOs);
					}
					if(MMValueCheck.isNotEmpty(updateBankVOs)) {
						//修改银行账户
						HttpReqUtil.getCustBankaccService().updateCustBankaccs(updateBankVOs.toArray(new CustBankaccUnionVO[0]));
					}
					if(MMValueCheck.isNotEmpty(addBankVOs)) {
						//新增银行账户
						HttpReqUtil.insertCustBankacc(supplierVO.getPk_supplier(), addBankVOs.toArray(new BankAccbasVO[0]),3);
					}
				}
			}
			log.setIssuccess_sn("Y");
			log.setResultdata_sn("生成成功");
			msg="生成成功！";
		} catch (Exception e) {
			flag="N";
			log.setResultdata_sn(e.getMessage());
			log.setResultdata_sn(HttpReqUtil.getExceptionDetail(e));
			//wby 20211025 调整异常信息
			msg = e.getMessage() == null? e.toString() : e.getMessage();
		} finally {
			log.setIssuccess_sn(flag);
	    	log.setPk_org(pk_org+"");
	    	log.setBillid(billid+"");
	    	log.setDef2(mdgcode+"");
	    	log.setBillno(billno+"");
	    	log.setPk_billtypecode("SUPPLIER");
	    	log.setPk_transtypecode("");
	    	log.setSend_data_sn(billdata+"");
	    	log.setDef1(MDGSupplierSynNCPorcess.class.getCanonicalName());
	    	try {
				IExtLogService logService = NCLocator.getInstance().lookup(IExtLogService.class);
				logService.insertLog_RequiresNew(log);
				//add by longht 2021-09-14 优化代码-执行同步 前，先删除前N天的历史数据，为空则默认为3个月 及更新中间表逻辑  start
				//baseDAO.executeUpdate("update ncc_mdg_bd_supplier set flagstatus='"+(MMValueConvert.toUFBoolean(flag).booleanValue()?"2":"1")+"',msg='"+log.getMsg_sn()+"'  where  billno='"+billno+"'");
				if(!PubAppTool.isNull(msg) && msg.length() > 2000) {
					msg = msg.substring(0, 2000);
				}
				if(PubAppTool.isNull(pk)) {
					NCLocator.getInstance().lookup(IExtLogService.class).updatedb_RequiresNew("update ncc_mdg_bd_supplier set flagstatus='" + (MMValueConvert.toUFBoolean(flag).booleanValue()?"2":"1")+"',msg='" + msg + "'  where  billno='" + billno + "'", null);
				}else {
					NCLocator.getInstance().lookup(IExtLogService.class).updatedb_RequiresNew("update ncc_mdg_bd_supplier set flagstatus='" + (MMValueConvert.toUFBoolean(flag).booleanValue()?"2":"1")+"',msg='" + msg + "'  where  pk='" + pk + "'", null);
				}
				//add by longht 2021-09-14 优化代码-执行同步 前，先删除前N天的历史数据，为空则默认为3个月 及更新中间表逻辑  end
			} catch (Exception e) {
				ExceptionUtils.wrappBusinessException("同步供应商插入日志表出错：" + e.getMessage());
			}
		}
		return null;
	}
	
	/**
	 * 过滤json结构数据中为null的节点
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static Object filterNone(String jsonStr) throws Exception{
		if(jsonStr==null||jsonStr.equals("")||jsonStr.equals("null"))
	        return null;
	    if(jsonStr.indexOf("[")==0){
	        List<Object> lists = new ArrayList<Object>();
	        List<HashMap> list = JSON.parseArray(jsonStr, HashMap.class);
	        for(int i=0;i<list.size();i++){
	            Map<String,Object> map = list.get(i);
	            for (Map.Entry<String, Object> entrys : map.entrySet()) {
	                Map<String,Object> maps = new HashMap<String, Object>();
	                Object objs = filterNone(entrys.getValue().toString());
	                if(objs!=null){
	                	maps.put(entrys.getKey(),objs);
	                    lists.add(maps);
	                }
	            }
	        }
	        if(lists.size()==0)
	            return null;
            return lists;
	    }
	    if(jsonStr.indexOf("{")==0){
	        Map<String, Object> targetMap = new HashMap<String, Object>();
	        LinkedHashMap<String, Object> jsonMap = JSON.parseObject(jsonStr, new TypeReference<LinkedHashMap<String, Object>>(){});
	        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
	            Object obj = filterNone(entry.getValue().toString());
	            if(obj==null)
	                continue;
                targetMap.put(entry.getKey(),obj);
	        }
	        if(targetMap.isEmpty())
	        	return null;
	        return targetMap;
	    }
        return jsonStr;
	}

}
