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.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.itf.bd.currinfo.ICurrinfoQueryService;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.bd.currinfo.CurrinfoVO;
import nc.vo.bd.currinfo.CurrrateVO;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pub.lang.UFLiteralDate;
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.rateset.RatesetLogVO;
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;
/**       
 * @Description:MDG传NCC 汇率  
 * @author: 周蓝萍
 * @date:  20201203
 *   
 */
public class MdgToNccRatesetServelet extends NccEsbJsonServletUtil{

	public void execFunction(HttpServletRequest request,
			HttpServletResponse response) {
		
		
		JSONObject jsonobj = null;
		InvocationInfoProxy.getInstance().setUserDataSource("NCCDATA");
		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 ratedate="";
		RatesetLogVO logVO = new RatesetLogVO();//同步日志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);
			
			ratedate = logVO.getRatedate();
			if(ratedate==null || ratedate.length()==0){
				throw new Exception("汇率日期不能为空");
			}
			String pk_currtype = logVO.getPk_currtype();
			if(pk_currtype==null || pk_currtype.length()==0){
				throw new Exception("汇率源币种编码不能为空");
			}
			String oppcurrtype = logVO.getOppcurrtype();
			if(oppcurrtype==null || oppcurrtype.length()==0){
				throw new Exception("汇率目标币种编码不能为空");
			}
			String rate = logVO.getRate();
			if(rate==null || rate.length()==0){
				throw new Exception("汇率不能为空");
			}
			//转换时间
			SimpleDateFormat hldf = new SimpleDateFormat("yyyyMMdd");
			Date date = hldf.parse(ratedate);
			hldf = new SimpleDateFormat("yyyy-MM-dd");
			String hldate = hldf.format(date);
			
			//查询源币种主键
			String ycurrtypeSql = "select pk_currtype from bd_currtype where code='"+pk_currtype+"' and dr=0";
			Map ycurrtypeMap = (Map) dao.executeQuery(ycurrtypeSql, new MapProcessor());
			String ycurrtype = "";
			if(null != ycurrtypeMap && ycurrtypeMap.size()>0) {
				ycurrtype =  (String) ycurrtypeMap.get("pk_currtype");
			}
			//查询目标币种主键
			String tcurrtypeSql = "select pk_currtype from bd_currtype where code='"+oppcurrtype+"' and dr=0";
			Map tcurrtypeMap = (Map) dao.executeQuery(tcurrtypeSql, new MapProcessor());
			String tcurrtype = "";
			if(null != tcurrtypeMap && tcurrtypeMap.size()>0) {
				tcurrtype =  (String) tcurrtypeMap.get("pk_currtype");
			}
			// 获取基准汇率方案的汇率信息
			CurrinfoVO[] currinfoVOs = NCLocator.getInstance().lookup(ICurrinfoQueryService.class)
					.queryCurrinfoVOsByScheme("0001Z010000000000358");
			for (CurrinfoVO currinfoVO : currinfoVOs) {
				String pkCurrtype = currinfoVO.getPk_currtype();// 源币种
				String oppCurrtype = currinfoVO.getOppcurrtype();// 目的币种
				if (ycurrtype.equals(pkCurrtype) && tcurrtype.equals(oppCurrtype)) {
					String pk_currinfo = currinfoVO.getPk_currinfo();
					String wherePart = " isnull(dr, 0) = 0 and pk_currinfo = '" + pk_currinfo + "' and ratedate = '" + ratedate + "'";
					List<CurrrateVO> currrateVOList = (ArrayList<CurrrateVO>) dao.retrieveByClause(CurrrateVO.class, wherePart);
					// 更新日汇率
					CurrrateVO currrateVO = null;
					String pk_currrate = "";
					if (currrateVOList != null && !currrateVOList.isEmpty()) {
						currrateVO = currrateVOList.get(0);
						pk_currrate = currrateVO.getPk_currrate();
						currrateVO.setStatus(VOStatus.UPDATED);
						currrateVO.setRate(new UFDouble(rate));
						dao.updateVO(currrateVO);
					} else {
						currrateVO = new CurrrateVO();
						currrateVO.setPk_currinfo(pk_currinfo);
						currrateVO.setRatedate(new UFLiteralDate(hldate));
						currrateVO.setStatus(VOStatus.NEW);
						currrateVO.setRate(new UFDouble(rate));
						pk_currrate = dao.insertVO(currrateVO);
					}
				}		
			}
			logVO.setIssuccess("Y");
			logVO.setMsg("MDG调用NCC接口保存操作成功");

			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
	 * @author 周蓝萍
	 * @time 2020-12-07
	 * @param header,logVO
	 */
	public RatesetLogVO jsonToVO(JSONObject header,RatesetLogVO 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();
			}
		}
	}
	
}
