package nc.net.uapbd.activity;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bcmanage.bs.IBusiCenterManageService;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.uap.tools.formula.ExtFormulaParser;
import nc.itf.uap.IVOPersistence;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.net.pu.utils.PubUtils;
import nc.net.servlet.NewEsbJsonServlet;
import nc.pub.sap.constant.SapConstants;
import nc.pubitf.para.SysInitQuery;
import nc.service.rest.util.JsonTools;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.SuperVO;
import nc.vo.sap.log.SapPurchaseLogVO;
import uap.json.JSONArray;
import uap.json.JSONObject;

public class MDMToNccStationServlet extends NewEsbJsonServlet {

	BaseDAO baseDao = new BaseDAO();
	String issuccess_sn = null;


	@Override
	public void execFunction(HttpServletRequest request, HttpServletResponse response, JSONObject object)
			throws Exception {
		issuccess_sn = "Y";
		//initInvocationInfo();
		// 批量：记录成功与失败的postcode
		Map<String, Object> outlook = new HashMap<String, Object>();
		String puuid = object.getJSONObject("ESB")
				.getJSONObject("DATA").getJSONObject("DATAINFOS")
				.getString("PUUID");
		

		try {
			ExtFormulaParser extFormulaParser = new ExtFormulaParser();
			Map<String,Map<String,Object>> mapItems = ReceiveUtils.convert2MapExcludePsn((com.alibaba.fastjson.JSONObject.parseObject(object.toString()))
					.getJSONObject("ESB")
					.getJSONObject("DATA")
					.getJSONObject("DATAINFOS")
					.getJSONArray("DATAINFO")
//					.getJSONObject(0)
//					.getJSONObject("CODEVALUE")
//					.getJSONArray("SPECIALITY")
//					.getJSONObject(0)
//					.getJSONArray("PROPERTY")
					);
			
			//获取公式
			HashMap<String, ArrayList<String>> formulaone = JsonTools.getFormulas("MDM2NccStation", 0);
			ArrayList<String> formulas = formulaone.get(SapConstants.FORMULA_KEY);
			
			mapItems.forEach((k,v)->{
				String code = null;
				try {
				List<Map<String,Object>> list = Stream.of(v).collect(Collectors.toList());
				JSONArray item = new JSONArray(com.alibaba.fastjson.JSONObject.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(list)).toString());
				List<CircularlyAccessibleValueObject> headVOs=JsonTools.setRecValues((Class<? extends CircularlyAccessibleValueObject>) Class.forName("nc.vo.om.job.JobVO"),item,formulaone);
				extFormulaParser.execFormulas(formulas.toArray(new String[formulas.size()]), headVOs.toArray(new CircularlyAccessibleValueObject[headVOs.size()]));
				CircularlyAccessibleValueObject headVO = headVOs.get(0);
				// 业务逻辑处理 pk_post1001H91000000001ALNP
				code = (String) headVO.getAttributeValue("jobcode");
				String sql = "select pk_job from om_job where jobcode = ?";
				SQLParameter params = new SQLParameter();
				params.addParam(code);
				String pk = (String) baseDao.executeQuery(sql, params, new ColumnProcessor());
//				headVO.setAttributeValue("pk_eps", "1001Q7100000000029TD");
				headVO.setAttributeValue("pk_org","0001H810000000000HS2");
				headVO.setAttributeValue("pk_group","0001H810000000000HS2");
//				headVO.setAttributeValue("pk_dept", getPKfromCode("org_dept","pk_dept","code",(String) headVO.getAttributeValue("pk_dept")));
//				headVO.setAttributeValue("pk_org", getPKfromCode("org_dept","pk_org","pk_dept",(String) headVO.getAttributeValue("pk_dept")));
//				headVO.setAttributeValue("enablestate", 2);
				headVO.setAttributeValue("dr", 0);
				headVO.setAttributeValue("enablestate", item.getJSONObject(0).getString("POSTION_STATUS").equals("A")?2:3);
				// 判断新增与更新
				if (pk != null) {
					// 新增 给vo设置主键
					headVO.setPrimaryKey(pk);
					NCLocator.getInstance().lookup(IVOPersistence.class).updateVO((SuperVO) headVO);

				} else {
					//新增时设置一些字段让前台能够显示
					NCLocator.getInstance().lookup(IVOPersistence.class).insertVO((SuperVO) headVO);

				}
				outlook.put(k, "成功");
				List<SapPurchaseLogVO> logvo_list = new ArrayList<SapPurchaseLogVO>();
				SapPurchaseLogVO logvo = PubUtils.createSNLog("MDM2NccStation", "", code, "", object.toString(), object.toString(),
						null, "成功", issuccess_sn, this.getClass().getName());
				logvo_list.add(logvo);
				PubUtils.getSaplog().insertPurchaseLog_RequiresNew(logvo_list);
			} catch (Exception e) {
				Map<String, String> error = new HashMap<String, String>();
				error.put(code, e.getMessage());
				outlook.put(code, e.getMessage());
				List<SapPurchaseLogVO> logvo_list = new ArrayList<SapPurchaseLogVO>();
				SapPurchaseLogVO logvo = PubUtils.createSNLog("MDM2NccStation", "", code, "", "", object.toString(),
						null, error.toString(), "N", this.getClass().getName());
				logvo_list.add(logvo);
				PubUtils.getSaplog().insertPurchaseLog_RequiresNew(logvo_list);
				issuccess_sn = "N";
//				sendResponse(response, ReceiveUtils.responseMsg("S成功", "接口调用异常"+e.getMessage(), "", "", "", "失败", "失败", "",outlook));
			}
			});


		} catch (Exception e) {
//			ResultVO result = new ResultVO();
//			result.setCode(IReturnStatus.ESB_ERROR);// 失败
//			result.setMessage("接口调用异常"+e.getMessage());
//			ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
//			createResultEsbVO(esb);
//			esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_FAILING);
//			esb.setResultInfo(result);
			sendResponse(response, ReceiveUtils.responseMsg("S", "接口调用异常"+e.getMessage(), puuid,outlook));
		} finally {
//			ResultVO result = new ResultVO();
//			result.setCode(IReturnStatus.ESB_SUCCEED);// 成功
//			StringBuffer rtnMessage = new StringBuffer("失败：\n");
//			Integer errorTimes = 0;
//			Integer successTimes = 0;
//			for (String key : outlook.keySet()) {
//				if (!outlook.get(key).getClass().getName().equals("java.lang.String")) {
//					errorTimes += 1;
//					rtnMessage.append(((Map) outlook.get(key)).get(code));
//					rtnMessage.append("\n");
//				} else {
//					successTimes += 1;
//				}
//			}
//			rtnMessage.append("共失败个数：");
//			rtnMessage.append(errorTimes);
//			rtnMessage.append("\n共成功次数：");
//			rtnMessage.append(successTimes);
//			result.setMessage(rtnMessage.toString());
//			ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
//			createResultEsbVO(esb);
//			esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_SUCCEED);
//			esb.setResultInfo(result);
			if("N".equals(issuccess_sn)) {
				sendResponse(response, ReceiveUtils.responseMsg("N", "接口调用异常", puuid,outlook));
			}else {
			sendResponse(response, ReceiveUtils.responseMsg("S", "接口调用成功", puuid,outlook));
			}
		}

	}
	private void initInvocationInfo() {
		NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(), "pfxx".getBytes());
		try {
			IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
			InvocationInfoProxy.getInstance().setUserDataSource(busiCenterManageService.getAvailableBusiCenterDsNames()[0]);
			InvocationInfoProxy.getInstance().setGroupId(SysInitQuery.getParaString("GLOBLE00000000000000", "GROUP"));
			InvocationInfoProxy.getInstance().setUserId(SysInitQuery.getParaString("GLOBLE00000000000000", "ITFUSER"));
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	private String getPKfromCode(String tableName, String pk,String code, String code_value) throws BusinessException {
		String sql = "select "+pk+" from "+tableName+" where nvl(dr,0)=0 and "+code+"='"+code_value+"' ";
		String codes = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());
		return codes;
	}
	
}
