package ncc.bd.rest.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.UUID;

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

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.logging.Logger;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.vo.bd.asslinenum.AssLineNumVO;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.AppContext;
import ncc.net.servlet.NccEsbJsonServletUtil;
import ncc.net.servlet.status.WyReturnStatus;
import ncc.pub.wy.constant.WyConstants;
import ncc.vo.bd.asslinenum.AssLineNumLogVO;
import ncc.vo.esb.WyEsbInfoVO;
import ncc.vo.esb.WyQueryInfoVO;
import ncc.vo.esb.WyResultEsbVO;
import ncc.vo.esb.result.WyResultVO;
import nccloud.commons.lang.StringUtils;
import uap.json.JSONObject;
/**   
 * @ClassName:  MdgTmReceiveAsslinenumBS   
 * @Description:MDG传NCC人行联行号  新增/修改/删除  
 * 记录日志后台表：bd_asslinenum_log 对应VO：AssLineNumLogVO
 * @author: 周蓝萍
 * @date:  20201203
 *   
 */
public class MdgToNccAsslinenumServelet extends NccEsbJsonServletUtil{

	public void execFunction(HttpServletRequest request,
			HttpServletResponse response) {
		
		
		JSONObject jsonobj = null;
		
		try{
			jsonobj=findPostJsonValue(request);//获取Post请求的值
			if(jsonobj==null || "".equals(jsonobj)){//无Post提交值
				WyResultVO result=new WyResultVO();
				result.setCode(WyReturnStatus.FAILING);//失败
				result.setMessage("Post所提交请求Json格式错误或者无值!");
				WyResultEsbVO<WyResultVO> esb=new WyResultEsbVO<WyResultVO>();
				createResultEsbVO(esb);
				esb.getEsbInfo().setReturnStatus(WyReturnStatus.ESB_FAILING);
				esb.getEsbInfo().setReturnMsg("失败");
				esb.setResultInfo(result);
				sendResponse(response,esb);
			}else{
				/** begin 构建系统参数（BGY） **/
				try{
					initInvocationInfo();
				}catch(Exception e){
					throw e;
				}
				/** end 构建系统参数（BGY） **/
			}
		}catch(Exception e){
			WyResultVO result=new WyResultVO();
			result.setCode(WyReturnStatus.ERROR);//异常
			result.setError(getExceptionDetail(e));
			WyResultEsbVO<WyResultVO> esb=new WyResultEsbVO<WyResultVO>();//创建响应对象
			createResultEsbVO(esb);//初始化响应对象
			esb.getEsbInfo().setReturnStatus(WyReturnStatus.ESB_ERROR);
			esb.getEsbInfo().setReturnMsg("异常");
			esb.setResultInfo(result);//设置响应内容
			sendResponse(response,esb);
		}
		

		WyResultEsbVO<WyResultVO> esb = new WyResultEsbVO<WyResultVO>();//创建响应对象
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		Calendar cal = Calendar.getInstance();
		String begindate = df.format(cal.getTime());
		String pcombinenum="";
		AssLineNumLogVO logVO = new AssLineNumLogVO();//同步日志VO
		UFDateTime time = AppContext.getInstance().getServerTime();
		
		BaseDAO dao = new BaseDAO();
		
		try{
			
			JSONObject obj = jsonobj.getJSONObject("requestInfo");
			JSONObject header = obj.getJSONObject("Header");
			logVO = jsonToVO(header,logVO);
			
			pcombinenum = logVO.getPcombinenum();
			if(pcombinenum==null || pcombinenum.length()==0){
				throw new Exception("人行联行信息编码不能为空");
			}else if(pcombinenum.length()>12){
				throw new Exception("人行联行信息编码超过12位，NCC不接收");
			}
			String pcombinename = logVO.getPcombinename();
			if(pcombinename==null || pcombinename.length()==0){
				throw new Exception("人行联行信息名称不能为空");
			}
			String countrycode = logVO.getCountrycode();//国家
			String address = logVO.getAddress(); //详细地址
			String city	 = logVO.getCity();//城市
			String swiftcode = logVO.getSwiftcode();//SWIFT
			String tel_number = logVO.getTel_number();//银行电话
			
			ArrayList<AssLineNumVO> list=null;
			list=(ArrayList<AssLineNumVO>) dao.executeQuery("select * from bd_asslinenum where code ='"+pcombinenum+"'", new BeanListProcessor(AssLineNumVO.class));
			String chkme = logVO.getChkme();
			if(chkme!=null && "X".equals(chkme)){
				if(list!=null && list.size()>0){
					dao.deleteVOArray(list.toArray(new AssLineNumVO[list.size()]));
					logVO.setIssuccess("Y");
					logVO.setMsg("MDG调用NCC接口删除操作成功");
				}else{
					throw new Exception("NCC不存在该联行号编码的相关信息，删除操作失败："+pcombinenum);
				}
			}else{
				
				if(list!=null && list.size()>0){
					AssLineNumVO[] assLineNumVOs = list.toArray(new AssLineNumVO[list.size()]);
					for(AssLineNumVO vo : assLineNumVOs){
						String code = vo.getCode();
						if(pcombinenum.equals(code)){
							vo.setName(pcombinename);
							vo.setCity(city);
							vo.setTelePhone(tel_number);
							vo.setLocation(address);
							vo.setModifiedtime(time);
							vo.setModifier(WyConstants.NCCADMIN_CUSERID);
						}
					}
					int rest = dao.updateVOArray(assLineNumVOs);
					if(rest==1){
						logVO.setIssuccess("Y");
						logVO.setMsg("MDG调用NC接口更新操作成功");
					}
				}else{
					AssLineNumVO numVO = new AssLineNumVO();
					numVO.setCode(pcombinenum);
					numVO.setName(pcombinename);
					numVO.setCity(city);
					numVO.setTelePhone(tel_number);
					numVO.setLocation(address);
					numVO.setCreationtime(time);
					numVO.setCreator(WyConstants.NCCADMIN_CUSERID);
					numVO.setPk_group(WyConstants.GROUPID);
					numVO.setPk_org("");
					
					String rest = dao.insertVO(numVO);
					logVO.setIssuccess("Y");
					logVO.setMsg("MDG调用NCC接口保存操作成功"+rest);
				}
			}

			InvocationInfoProxy.getInstance().setGroupId(WyConstants.GROUPID);
			InvocationInfoProxy.getInstance().setUserId(
					WyConstants.NCCADMIN_CUSERID);
			//组装日志信息
			logVO.setSend_data_sn(jsonobj.toString());
			logVO.setCreationtime(time);
			logVO.setCreator(WyConstants.NCCADMIN_CUSERID);
			
			//组装返回信息
			WyResultVO result=new WyResultVO();
			result.setCode(WyReturnStatus.SUCCEED);//成功
			result.setMessage("执行操作成功");
			Calendar call = Calendar.getInstance();
			String enddate = df.format(call.getTime());
			createResultEsbVO(esb,jsonobj.getJSONObject("esbInfo").getString("instId"),begindate,enddate);//初始化响应对象
			esb.getEsbInfo().setReturnStatus(WyReturnStatus.ESB_SUCCEED);
			esb.setResultInfo(result);
			sendResponse(response, esb);// 发送响应对象
			
		}catch(Exception e){
			Logger.error("====人行联行号写入异常===" + e.getMessage());
			Logger.error("====人行联行号写入报文===" + jsonobj);
			
			//组装日志信息
			logVO.setIssuccess("N");
			logVO.setMsg(e.getMessage());
			logVO.setSend_data_sn(jsonobj.toString());
			logVO.setCreationtime(time);
			
			//组装返回信息
			WyResultVO result=new WyResultVO();
			result.setCode(WyReturnStatus.FAILING);//失败
			result.setMessage("执行操作失败");
			result.setError(e.getMessage());
			Calendar call = Calendar.getInstance();
			String enddate = df.format(call.getTime());
			createResultEsbVO(esb,jsonobj.getJSONObject("esbInfo").getString("instId"),begindate,enddate);//初始化响应对象
			esb.getEsbInfo().setReturnMsg("失败");
			esb.getEsbInfo().setReturnCode(WyReturnStatus.ESB_FAILING_CODE);
			esb.getEsbInfo().setReturnStatus(WyReturnStatus.ESB_ERROR);
			esb.setResultInfo(result);//设置响应内容
			sendResponse(response, esb);// 发送响应对象
			
		}finally{
			try {
				//插入日志
				logVO.setResult_data_sn(com.alibaba.fastjson.JSONObject.toJSONString(esb).toString());
				dao.insertVO(logVO);
			} catch (Exception e) {
				Logger.debug("人行联行号保存日志插入失败" + e.getMessage());
			}
		}
		
	}
	
	/**
	 * json转换VO
	 * @time 2020-12-03
	 * @param header,logVO
	 */
	public AssLineNumLogVO jsonToVO(JSONObject header,AssLineNumLogVO logVO){
		Iterator<String> it;
		String attributeName;
		Object value;
		it = (Iterator<String>) header.keys();
		while (it.hasNext()) {
			attributeName = it.next();
			if (StringUtils.isEmpty(attributeName)) {
				continue;
			}
			value = header.get(attributeName);
			if (value == null || StringUtils.isEmpty(value.toString()) || header.isNull(attributeName)) {
				continue;
			}
			logVO.setAttributeValue(attributeName, value);
		}
		return logVO;
	}
	
	/**
	 * 生成ESB响应对象
	 * @param esb
	 * @param instId 来源数据ID
	 * @param begindate 请求开始时间
	 * @param enddate 请求结束时间
	 */
	public void createResultEsbVO(final WyResultEsbVO esb,String instId,String begindate,String enddate){
		WyEsbInfoVO esbInfo=new WyEsbInfoVO();
		WyQueryInfoVO queryInfo=new WyQueryInfoVO();

		if(instId!=null && !"".equals(instId)){
			esbInfo.setInstId(instId);
		}else{
			esbInfo.setInstId(getStringUUID());//使用UUID作为流水号
		}
		esbInfo.setRequestTime(begindate);//设置请求开始时间
		esbInfo.setResponseTime(enddate);//设置响应时间
		esbInfo.setReturnStatus(WyReturnStatus.ESB_SUCCEED);//默认响应成功
		esbInfo.setReturnCode(WyReturnStatus.ESB_SUCCEED_CODE);//默认成功code
		esbInfo.setReturnMsg("成功");//默认响应成功提示
		esb.setEsbInfo(esbInfo);
		esb.setQueryInfo(queryInfo);
	}
	
	/**
	 * 获得UUID值
	 */
	public static String getStringUUID(){
		return UUID.randomUUID().toString();
	}
	
	/**
	 * 发送响应信息
	 * @param response
	 * @param esb
	 */
	public void sendResponse(final HttpServletResponse response,WyResultEsbVO esb){
		String jsondata=com.alibaba.fastjson.JSONObject.toJSONString(esb).toString();
		PrintWriter out=null;
		try {
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8"));
	        out.write(jsondata);
	        out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
			}
		}
	}
	
	/**
	 * 加载Post提交上来的Json参数
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	private JSONObject findPostJsonValue(final HttpServletRequest request) throws Exception{
		BufferedReader br=null;
		try {
			br= new BufferedReader(new InputStreamReader(
					(ServletInputStream) request.getInputStream(), "utf-8"));
			StringBuffer sb = new StringBuffer();
			String temp=null;
			while ((temp = br.readLine())!= null) {
				sb.append(temp);
			}
			return new JSONObject(sb.toString());
		} catch (Exception e) {
			throw e;
		}finally{
			try {
				if(br!=null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
