package com.chinacreator.video.restful.controller;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;

import com.chinacreator.video.exception.BusinessException;
import com.chinacreator.video.restful.util.HttpInvoke;
import com.chinacreator.video.restful.util.JsonUtil;

import net.sf.json.JSONArray;
import org.jboss.logging.Logger;
import org.omg.PortableInterceptor.ObjectReferenceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.mapper.CpSpDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.mapper.ShangHaiOrderDao;
import com.chinacreator.video.restful.bean.ShangHaiObject;
import com.chinacreator.video.restful.service.ShangHaiOrderService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;


/**
 * 2元能力产品针对上海权益
 * 底层处理逻辑与腾讯2元相同
 * 办理广东2元，畅视2元
 * 广东2元有三个操作，分别为订购、退订、预订购。畅视2元只有订购和退订两个操作
 * 接口转接到广东腾讯2元的接口tcpreOrder.do
 * @author zhou.xu
 * @date 20190725
 */
@RestController
@RequestMapping(value = "/sh")
public class ShangHaiController {
	
	private static Logger logger = Logger.getLogger(ShangHaiController.class);
	
	private static Logger log = Logger.getLogger("shanghai");
	
	@Autowired
	private ShangHaiOrderService service;
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private CpSpDao CpSpDao;
	
	@Autowired
	private ShangHaiOrderDao shangHaiOrderDao;
	
	@Autowired
	private CommConfDao commConfDao;
	
	/**
	 * POST方式办理业务
	 * @param inputObj
	 * @param request
	 * @return
	 * @throws Exception 
	 */
    @RequestMapping(value = "/activeCouponNo", method = RequestMethod.POST, produces = "application/json")
    public String order(@RequestBody String params, HttpServletRequest request) throws Exception {
    	ShangHaiObject inputObj = new ShangHaiObject();
    	ShangHaiObject outputObj = new ShangHaiObject();
    	Map<String,Object> logmap = new HashMap<String,Object>();
    	logmap.put("forward", "activeCouponNo");
   
    	String inputParams = "";
    	String outputParams = "";
    	String transid = "";
    	String tradeid = "";
    	String accountid = "";
    	String respcode = "";
    	String respdesc = "";
    	String logid = ""; //日志表ID
     	logmap.put("transid",transid);
        OrderInfo orderInfo = new OrderInfo();
    	try {
        	inputParams = params; //JSON.toJSONString(params); //输入参数
        	logmap.put("inputParams",inputParams);
        	//System.out.println("++++++++++++==inputParams:"+inputParams);
        	//JSONObject jsonObject = JSON.parseObject(params);
        	inputObj = new JSONObject().parseObject(params, ShangHaiObject.class);
        	
        	try {
        		transid = inputObj.getUni_bss_head().get("TRANS_ID").toString();	//流水号
        		accountid = inputObj.getUni_bss_body().getJSONObject("ACTIVE_COUPON_NO_REQ").get("ID").toString(); //ID，用于对账
        		tradeid = inputObj.getUni_bss_body().getJSONObject("ACTIVE_COUPON_NO_REQ").get("TRADE_ID").toString();  //订单ID    		
			} catch (Exception e) {
				e.printStackTrace();
			} 
        	logid = commConfDao.generateId();
//        	Map recBean = shangHaiOrderDao.getShInPaInfoByTransid(transid);
//        	if(recBean != null && transid.equals(recBean.get("TRANS_ID"))){
//        		throw new BussinessException("8003", "参数不合法，重复TRANS_ID");
//        	}
        	//添加到输入输出参数日志表，tcpreOrder接口受理后会把流水号更新到这个表
        	shangHaiOrderDao.addShInPaInfo(logid,tradeid,transid,accountid,inputParams); 

/*        	System.out.println(inputObj.getUni_bss_head().toJSONString());
        	System.out.println(inputObj.getUni_bss_body().toJSONString());
        	System.out.println(inputObj.getUni_bss_attached().toJSONString());
        	System.out.println(JSON.toJSONString(inputObj));
        	//inputObj.setUniBssHead(jsonObject.getJSONObject("UNI_BSS_HEAD"));
        	JSONArray jsonArray = inputObj.getUni_bss_body().getJSONObject("ACTIVE_COUPON_NO_REQ").getJSONArray("ACCOUNT_PARAM");
        	System.out.println(jsonArray.toJSONString());*/

        	orderInfo.setReorderid(logid);
        	logmap.put("orderInfo",orderInfo);
        	service.checkBusi(inputObj, orderInfo);
			String numberlimit = dictionaryDao.getValue("Numberlimit");
			if (numberlimit != null && numberlimit.indexOf(orderInfo.getUserid().substring(0, 7)) != -1) {
				throw new BussinessException("9010", "用户为黑名单用户");
			}
        	String url = order(orderInfo);
        	logmap.put("url",url);
        	String result = this.doHandle(url);
        	//System.out.println("=====result:"+result);
        	respcode = JSON.parseObject(result).get("resultcode").toString();
        	respdesc = JSON.parseObject(result).get("errorinfo").toString();
        	//办理成功，指定产品记录办理次数
        	if("0".equals(respcode)){
        		service.addordercnt(orderInfo);
        	}
			//if(!JSON.parseObject(result).get("resultcode").equals("0")) {
				//throw new BussinessException(JSON.parseObject(result).get("resultcode").toString(),JSON.parseObject(result).get("errorinfo").toString());
			//}
        	//System.out.println(JSON.toJSONString(transToLowerObject(JSON.parseObject(JSON.toJSONString(inputObj)))));
        	//outputParams = JSON.toJSONString(service.transToLowerObject(JSON.parseObject(JSON.toJSONString(outputObj))));
            //return JSON.toJSONString(outputObj);
		} catch (Exception e) {
			e.printStackTrace();
			if(e instanceof BussinessException) {
				respcode = ((BussinessException) e).getCode();
				respdesc = ((BussinessException) e).getMessage();
				if("9001".equals(respcode)){
					respcode = "9110";
					respdesc = "重复订单，不处理";
				}else if("9003".equals(respcode)){
					respcode = "9117";
					respdesc = "已办理互斥业务";
				}
			}else {
				respcode = "8003";
				respdesc = "出现异常，"+e.getMessage();
				
//				ByteArrayOutputStream buf=new ByteArrayOutputStream();
//    			e.printStackTrace(new PrintWriter(buf,true));
//    			String expMessage=buf.toString();
//    			if(expMessage.indexOf("ORA-00001")!=-1){  //超时异常}
//    				//System.out.println("=============+++++++++++++++====违反唯一约束");
//    				respdesc = "出现异常，重复TRANS_ID";
//    			}
			}
			log.info(transid+"=>异常信息：respcode=>"+respcode+", respdesc=>"+respdesc);
		} finally {
			try {
				outputParams = getOutputObj(logid, transid, respcode, respdesc);
			} catch (Exception e) {
				e.printStackTrace();
				log.info(transid+"=>getOutputObj出现异常，"+e);
				respcode = "8003";
				respdesc = "出现异常，"+e.getMessage();
				outputParams = this.getErrorInfo(transid, respcode, respdesc);
			}
			
			try {
				shangHaiOrderDao.updShInPaInfo(logid,outputParams);
			} catch (Exception e) {
				e.printStackTrace();
				log.info(transid+"=>updShInPaInfo出现异常，"+e);
			} 
			
			logmap.put("respcode",respcode);
			logmap.put("respdesc",respdesc);
			logmap.put("outputParams",outputParams);
			
			log.info(JSON.toJSONString(logmap));
			//log.info(transid+"=>inputParams=>"+inputParams);
			//log.info(transid+"=>outputParams=>"+outputParams);
            //订购关系同步给华盛
			/****
            if ("0".equals(respcode)){
                try {
                    Map conf = shangHaiOrderDao.getCsMakeupConf(orderInfo.getSpid());
                    if (conf!=null&&conf.size()>0){
                        conf.put("SENO",orderInfo.getOrderid());
                        String result = invokeTwvip(orderInfo, conf);
                        log.info("2元产品同步结果===useri=="+orderInfo.getUserid()+"===SPID=="+ orderInfo.getSpid()+"====接口返回结果=="+result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("2元产品同步失败===="+e.getMessage());
                }
            }
            ****/
			//发送短信
			inserSmstMq(orderInfo, respcode);
		}
        return outputParams;
    }


    /**
     * 调拓维会员接口
     * @param orderBean
     * @param conf
     * @return
     * @throws Exception
     */
    private String invokeTwvip(OrderInfo orderBean, Map conf) throws Exception{
        String result = ""; //调拓维会员接口返回结果
        String vipurl = "";
        String jsonParams = "";
        if ("0".equals(orderBean.getType())){
            vipurl = dictionaryDao.getValue("csmakeupviporderurl");
            jsonParams = this.fullOrderParams(orderBean.getUserid(),conf);
        }else {
            throw new  BussinessException("9001","退订不需要同步");
        }

        logger.info("vipurl=>"+vipurl+", jsonParams=>"+jsonParams);
		/*
		if("1".equals(orderBean.getUpdatetype())){//订购
			result = com.chinacreator.process.util.URLUtil.postJson(vipurl, jsonParams);
			result = HttpInvoke.sendHttpByPost("POST", vipurl, jsonParams, getProperty(orderBean.getUpdatetype()));
		}else{//退订
			result = com.chinacreator.process.util.URLUtil.postForm(vipurl, jsonParams);
			result = HttpInvoke.sendHttpByPost("POST", vipurl, jsonParams, getProperty(orderBean.getUpdatetype()));
		}*/
            result = HttpInvoke.sendhttpsReq("POST", vipurl, jsonParams, getProperty("1"));
        logger.info("调拓维会员接口返回结果："+result);
        //去空格、换行符号
        if(result != null) result = result.replaceAll("\r|\n", "").replaceAll("	", "").replaceAll(" ", "");

        //result = "{\"code\":0,\"message\":\"成功\",\"success\":true}";
        //result = "{\"code\":7007,\"message\":\"签名无效\",\"success\":false}";
        return result;
    }

    /**
     * 填充订购会员参数
     * @param mobile
     * @param conf
     * @return
     * @throws Exception
     */
    private String fullOrderParams(String mobile, Map conf)throws Exception {
        String jsonParams = "";
        String timestamp = System.currentTimeMillis()+"";
        String spid = conf.get("VSPID").toString();
        String cpid = conf.get("VCPID").toString();
        String memberUrl = "";
        String orderNumber = conf.get("SENO").toString();
        String password = conf.get("VPWD").toString();
        mobile = DesUtil.encode(mobile, password); //手机号码加密
        String signature = MD5.MD5Encode(spid + cpid + orderNumber + timestamp + password);

        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(mobile);
        json.put("timestamp", timestamp);
        json.put("signature", signature);
        json.put("spid", spid);
        json.put("cpid", cpid);
        json.put("mobiles", jsonArray);
        json.put("memberUrl", memberUrl);
        json.put("orderNumber", orderNumber);
        jsonParams = json.toJSONString();

        return jsonParams;
    }

    /**
     * 获取请求属性性
     * @return
     */
    private static Map getProperty(String updatetype){
        Map reqProperty = new HashMap();
        if("1".equals(updatetype)){//订购
            reqProperty.put("Content-type", "application/json;charset=utf-8");
        }else{//退订
            reqProperty.put("Content-type", "application/x-www-form-urlencoded");
        }

        return reqProperty;
    }

    private String getErrorInfo(String transid, String respcode, String respdesc){
    	String outputParams = "";
    	ShangHaiObject outputObj = null;
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); 
		String timestamp = fm.format(new Date());
		Map<String, String> reqParams = new HashMap<String, String>();
		JSONObject rspJson = new JSONObject();
		TreeMap<String, Object> headerMap = new TreeMap<String, Object>();
		TreeMap<String, Object> bodyMap = new TreeMap<String, Object>();
		TreeMap<String, Object> acnrMap = new TreeMap<String, Object>();
		TreeMap<String, Object> apMap = new TreeMap<String, Object>();
		List<Map> apList = new ArrayList<Map>();
		TreeMap<String, String> attachedMap = new TreeMap<String, String>();
		String appid = "";
		try {
			appid = dictionaryDao.getValue("shanghaiAppId");
		} catch (Exception e) {
			e.printStackTrace();
		}
		headerMap.put("APP_ID",appid);
		headerMap.put("TIMESTAMP",timestamp);
		headerMap.put("TRANS_ID",transid);
		headerMap.put("RESP_CODE",respcode);
		headerMap.put("RESP_DESC",respdesc);
		headerMap.put("RESERVED","");
		bodyMap.put("ACTIVE_COUPON_NO_RSP", acnrMap);
		
		rspJson.put("UNI_BSS_HEAD", headerMap);
		rspJson.put("UNI_BSS_BODY", bodyMap);
		rspJson.put("UNI_BSS_ATTACHED", attachedMap);
		
		outputParams = rspJson.toString();
		logger.info(outputParams);

		return outputParams;
    }
    
    private String getOutputObj(String logid, String transid, String respcode, String respdesc){
    	String outputParams = "";
    	ShangHaiObject outputObj = null;
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); 
		String timestamp = fm.format(new Date());
		Map<String, String> reqParams = new HashMap<String, String>();
		JSONObject rspJson = new JSONObject();
		TreeMap<String, Object> headerMap = new TreeMap<String, Object>();
		TreeMap<String, Object> bodyMap = new TreeMap<String, Object>();
		TreeMap<String, Object> acnrMap = new TreeMap<String, Object>();
		TreeMap<String, Object> apMap = new TreeMap<String, Object>();
		List<Map> apList = new ArrayList<Map>();
		TreeMap<String, String> attachedMap = new TreeMap<String, String>();
		headerMap.put("APP_ID",dictionaryDao.getValue("shanghaiAppId"));
		headerMap.put("TIMESTAMP",timestamp);
		headerMap.put("TRANS_ID",transid);
		headerMap.put("RESP_CODE","00000");
		headerMap.put("RESP_DESC","Success");
		headerMap.put("RESERVED","");
		if("0".equals(respcode)){
			respcode = "0000";
			respdesc = "成功";
		}else{
			respcode = "9999";
		}
		acnrMap.put("RESP_CODE", respcode);
		acnrMap.put("RESP_DESC", respdesc);
		
		//获取ORDER_NO，重复TRANS_ID异常时不获取，防止取到以前的记录
		if(respdesc != null && respdesc.indexOf("重复TRANS_ID") == -1){
			try {
				Map recBean = shangHaiOrderDao.getShInPaInfoById(logid);
				if(recBean != null && recBean.get("ORDER_NO") != null && !"".equals(recBean.get("ORDER_NO"))){
					acnrMap.put("ORDER_NO", (String)recBean.get("ORDER_NO"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		//acnrMap.put("COUPON_INFO","");
		bodyMap.put("ACTIVE_COUPON_NO_RSP", acnrMap);
		
		rspJson.put("UNI_BSS_HEAD", headerMap);
		rspJson.put("UNI_BSS_BODY", bodyMap);
		rspJson.put("UNI_BSS_ATTACHED", attachedMap);
		
		outputParams = rspJson.toString();
		logger.info(outputParams);

		return outputParams;
    }
    
    /**
     * json小写转大写
     * 
     * @param jSONArray1 jSONArray1
     * @return JSONObject
     */
/*    public static JSONObject transToLowerObject(JSONObject jsonObj) {
        JSONObject reJSONObj = new JSONObject();
        Iterator it = jsonObj.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            Object object = jsonObj.get(key);
            if (object.getClass().toString().endsWith("String")){
            	reJSONObj.put(key.toUpperCase(), object);
            } else if (object.getClass().toString().endsWith("JSONObject")) {
            	reJSONObj.put(key.toUpperCase(), transToLowerObject((JSONObject) object));
            } else if (object.getClass().toString().endsWith("JSONArray")) {
            	reJSONObj.put(key.toUpperCase(), transToArray(jsonObj.getJSONArray(key)));
            }
        }
        return reJSONObj;
    }*/
    
    /**
     * jsonArray转jsonArray
     * 
     * @param jSONArray1 jSONArray1
     * @return JSONArray
     */
/*    public static JSONArray transToArray(JSONArray jsonArray) {
        JSONArray reJSONArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            Object obj = jsonArray.getJSONObject(i);
            if (obj.getClass().toString().endsWith("JSONObject")) {
            	reJSONArray.add(transToLowerObject((JSONObject) obj));
            } else if (obj.getClass().toString().endsWith("JSONArray")) {
            	reJSONArray.add(transToArray((JSONArray) obj));
            }
        }
        return reJSONArray;
    }*/
    
	/**
	 * 获取订购url
	 * @param orderInfo
	 * @return
	 * @throws Exception
	 */
	public String order(OrderInfo orderInfo) throws Exception {
		//测试环境：http://10.199.99.177:86/videoif/
		//String orderUrl = dictionaryDao.getValue("tcpreOrderUrl")+"tcpreOrder.do?";
		String orderUrl = dictionaryDao.getValue("commonOrderUrl")+"backorder.do?";
		orderUrl += this.getParams(orderInfo);
		return orderUrl;
	}
	
	public String doHandle(String url) throws Exception {
		return  URLUtil.get(url);
	}
	
	/**
	 * 拼接转发URL参数
	 * @param orderInfo
	 * @return
	 * @throws BussinessException
	 */
	private String getParams(OrderInfo orderInfo) throws BussinessException{
		String params = "";
		try {
			String cpid = orderInfo.getCpid();
			String spid = orderInfo.getSpid();
			String type = orderInfo.getType();
			String userid = orderInfo.getUserid();
			String timestamp = orderInfo.getTimestamp();
			timestamp = System.currentTimeMillis()/1000+"";
			String orderid = orderInfo.getOrderid();
			String reorderid = orderInfo.getReorderid(); //序列号，用于更新日志报文表的流水号
			String pwd = CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid()).getPwd(); //TB_CP_ACCOUNT_CONFIG表NETPWD字段			
			//params += "reorderid="+reorderid+"&orderid="+orderid+"&type="+type+"&apptype=2&channel="+orderInfo.getChannel()+"&cpid="+cpid+"&spid="+spid+"&timestamp="+URLEncoder.encode(timestamp,"utf-8");	
			params += "reorderid="+reorderid+"&orderid="+orderid+"&type="+type+"&apptype=2&channel="+orderInfo.getChannel()+"&cpid="+cpid+"&spid="+spid+"&timestamp="+URLEncoder.encode(timestamp,"utf-8");
			userid = DesUtil.encode(userid, pwd); //手机号码加密
			//String signature = MD5.MD5Encode(orderid + type + cpid + spid + userid + pwd + timestamp);
			String signature = MD5.MD5Encode(orderid + cpid + spid + userid + timestamp + pwd);
			params += "&userid="+URLEncoder.encode(userid, "utf-8")+"&signature="+signature; //重新编码
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException("80013", "组建调用参数出现异常，"+e.getMessage());
		}
	
		return params;
	}
	
    /**
     * 推送办理成功的短信到队列
     * @param orderInfo
     */
    public void inserSmstMq(OrderInfo orderInfo, String result){
    	/**
		1053	changshi	畅视AI体验馆会员年卡0
		1054	changshi	畅视AI体验馆会员年卡3
		1055	changshi	畅视AI体验馆会员年卡5
    	 */
    	//指定产品办理推送短信
    	String spids = "1053,1054,1055";
    	List<String> spidList =  Arrays.asList(spids.split(","));
    	String userid = "";
        try{
            if("0".equals(orderInfo.getType()) && "0".equals(result) && spidList.contains(orderInfo.getSpid())){ //只发送订购成功短信
            	userid = orderInfo.getUserid();
                Map<String, String> map = new HashMap<String, String>();
                map.put("userid", userid);
                map.put("cpid", orderInfo.getCpid());
                map.put("spid", orderInfo.getSpid());
                map.put("result", "0");
                map.put("channel", orderInfo.getChannel());
                map.put("style","0000");
                map.put("times", "");
                map.put("orderType", "");
                map.put("type", "cssms");
                map.put("busiType", "tran_succ");	//订购成功短信
                //logger.info("++++++map:"+map);
                String  mqReciveUrl = dictionaryDao.getValue("mqReciveUrl");
                URLUtil.post(mqReciveUrl, JSON.toJSONString(map));
            }
        }catch (Exception e){
        	log.error(userid+"推送短信出现异常，"+e.getMessage(),e);
            //e.printStackTrace();
        }
    }
}
