package com.palmnest.service.ws;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.palmnest.application.Constants;
import com.palmnest.application.core.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 蜂助手平台接口实现
 * 关于影视会员充值、加油卡充值业务
 *
 * @author xiemin
 * @modify yubing
 * @modifyTime 2017-07-13
 * <p>
 * 原来的地址
 * http://test.orderapi.phone580.com:8000/ps3
 * <p>
 * 12.6号蜂助手加油卡充值接口变更新接口地址：
 * 测试：http://test.orderapi.phone580.com:8000/fzs-open-api/api
 * 生产：https://orderapi.phone580.com/fzs-open-api/api
 */
@Slf4j
public class PhoneClient {


	/**
	 * 蜂助手版本号 VERSION_PHONE
	 */
	public static String VERSION_PHONE = "";

	/**
	 * 辅助手请求地址 PHONEURL
	 */
	public static String PHONEURL       = "";
	/**
	 * 影视会员应用ID
	 */
	public static String filmVipAppId   = "";
	/**
	 * 影视会员应用秘钥
	 */
	public static String filmVipAppKey  = "";
	/**
	 * 加油卡应用ID
	 */
	public static String fuelCardAppId  = "";
	/**
	 * 加油卡应用秘钥
	 */
	public static String fuelCardAppKey = "";

	static {
		try {
			VERSION_PHONE = PropertiesKit.readPropertiesValue("version_phone", "phone_config.properties");
			PHONEURL = PropertiesKit.readPropertiesValue("phoneurl", "phone_config.properties");
			filmVipAppId = PropertiesKit.readPropertiesValue("filmVipAppId", "phone_config.properties");
			filmVipAppKey = PropertiesKit.readPropertiesValue("filmVipAppKey", "phone_config.properties");
			fuelCardAppId = PropertiesKit.readPropertiesValue("fuelCardAppId", "phone_config.properties");
			fuelCardAppKey = PropertiesKit.readPropertiesValue("fuelCardAppKey", "phone_config.properties");

			log.info("--PhoneClient init config message--");
			log.info("PHONEURL:" + PHONEURL);
			log.info("VERSION_PHONE:" + VERSION_PHONE);
			log.info("filmVipAppId:" + filmVipAppId);
			log.info("filmVipAppKey:" + filmVipAppKey);
			log.info("fuelCardAppId:" + fuelCardAppId);
			log.info("fuelCardAppKey:" + fuelCardAppKey);
		} catch (Exception e) {
			log.error("PhoneClient init config message occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	/**
	 * 初始化请求的公共参数
	 *
	 * @param code 业务编码
	 * @param desc 业务描述
	 * @return
	 */
	private static Map<String, String> initCommonParams(String appId, String code, String desc) {
		Map<String, String> commonParams = new HashMap<String, String>();
		String              reqid        = StringUtil.getOrderId("CG");
		commonParams.put("reqid", reqid);
		commonParams.put("appid", appId);
		commonParams.put("code", code);
		commonParams.put("version", VERSION_PHONE);
		commonParams.put("desc", desc);
		commonParams.put("time", DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		return commonParams;
	}

	/**
	 * 返回结果封装重用
	 *
	 * @param responseStr 接口返回结果值
	 * @return Map<String, String>
	 * result SUCCESS/ERROR
	 * result_desc 结果描述
	 * status 查询订单的时候返回的状态（RECHARGING:充值中 RECHAGE_OK:充值成功 RECHAGE_ERR:充值失败 CLOSED:订单关闭）
	 */
	private static Map<String, String> dealResult(String responseStr) {
		Map<String, String> retMap = new HashMap<String, String>();
		if (StringUtils.isNotBlank(responseStr) && !"{}".equals(responseStr)) {
			JSONObject json = JSONObject.parseObject(responseStr);
			//接口处理结果
			if ("SUCCESS".equals(json.get("result").toString())) {
				JSONObject outparam = json.getJSONObject("outparam");
				//业务处理结果
				if ("SUCCESS".equals(outparam.get("BUSI_RESULT").toString())) {
					retMap.put("result", "SUCCESS");
					if (outparam.get("ORDER_STATUS") != null) {
						retMap.put("status", outparam.get("ORDER_STATUS").toString());
						retMap.put("result_desc", outparam.get("ORDER_STATUS_DESC").toString());
					} else {
						retMap.put("result_desc", "SUCCESS");
					}
				} else {
					retMap.put("result", "ERROR");
					retMap.put("result_desc", outparam.get("BUSI_RESULT_DESC").toString());
				}
			} else {
				retMap.put("result", "ERROR");
				retMap.put("result_desc", json.get("result_desc").toString());
			}
		} else {
			retMap.put("result", "ERROR");
			retMap.put("result_desc", "req timeout or the response not standard.");
		}
		//System.out.println(JSONObject.toJSONString(retMap));
		return retMap;
	}

	/**
	 * 加油卡接口（充值接口）
	 * --充值参数--
	 * paramMap 里参数 ORDER_NO 订单号（32）
	 * paramMap 里参数 CARD_TYPE 卡类型（CNPC：中石油，暂不支持。SINOPEC：中石化）
	 * paramMap 里参数 CARD_TYPE_NAME 卡类型名称：中石油加油卡、中石化加油卡
	 * paramMap 里参数 CARD_CODE 卡号
	 * paramMap 里参数  PHONE_NO 手机号
	 * paramMap 里参数  RECHARGE_AMOUNT 充值金额（仅限：50、100、200、500、1000）
	 * paramMap 里参数  RET_URL 充值结果回调
	 *
	 * @param paramMap
	 * @return
	 */
	public static Map<String, String> rechargeFuelCard(Map<String, String> paramMap) {
		log.info("-rechargeFuelCard request begin-");
		//公共参数
		Map<String, String> commonParams = initCommonParams(fuelCardAppId, "300100", "加油卡充值");
		//业务参数
		Map<String, String> busiParams = new HashMap<String, String>();
		if (null != paramMap.get("ORDER_NO") && !paramMap.get("ORDER_NO").equals("")) {
			busiParams.put("ORDER_NO", paramMap.get("ORDER_NO"));
		}
		if (null != paramMap.get("CARD_TYPE") && !paramMap.get("CARD_TYPE").equals("")) {
			busiParams.put("CARD_TYPE", paramMap.get("CARD_TYPE"));
		}
		if (null != paramMap.get("CARD_TYPE_NAME") && !paramMap.get("CARD_TYPE_NAME").equals("")) {
			busiParams.put("CARD_TYPE_NAME", paramMap.get("CARD_TYPE_NAME"));
		}
		if (null != paramMap.get("CARD_CODE") && !paramMap.get("CARD_CODE").equals("")) {
			busiParams.put("CARD_CODE", paramMap.get("CARD_CODE"));
		}
		if (null != paramMap.get("PHONE_NO") && !paramMap.get("PHONE_NO").equals("")) {
			busiParams.put("PHONE_NO", paramMap.get("PHONE_NO"));
		}
		if (null != paramMap.get("RECHARGE_AMOUNT") && !paramMap.get("RECHARGE_AMOUNT").equals("")) {
			busiParams.put("RECHARGE_AMOUNT", paramMap.get("RECHARGE_AMOUNT"));
		}
		if (null != paramMap.get("RET_URL") && !paramMap.get("RET_URL").equals("")) {
			busiParams.put("RET_URL", paramMap.get("RET_URL"));
		}
		busiParams.put("QUANTITY", paramMap.get("QUANTITY"));
		//业务参数MD5加密
		String busiParamsMd5Str = StringUtil.sign(busiParams, "");
		commonParams.put("params", busiParamsMd5Str);
		//请求数据签名
		String sign = StringUtil.sign(commonParams, fuelCardAppKey);

		Map<String, Object> reqParams = new HashMap<String, Object>();
		reqParams.putAll(commonParams);
		reqParams.put("params", busiParams);
		reqParams.put("sign", sign);

		String jsonStr = "";
		try {
			String reqParamsStr = JSONObject.toJSONString(reqParams, SerializerFeature.WriteMapNullValue);
			log.info("reqParamsStr:" + reqParamsStr);
			jsonStr = HttpKit.httpJson(PHONEURL, reqParamsStr, Constants.POST);
			System.out.println("jsonStr" + jsonStr);
			log.info("jsonStr:" + jsonStr);
		} catch (Exception e) {
			log.error("rechargeFuelCard occur error.{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
		return dealResult(jsonStr);
	}

	/**
	 * 加油卡接口（充值订单查询）
	 * --根据订单号查询参数--
	 * orderNo 里参数 ORDER_NO 充值原始订单号（32）
	 *
	 * @return
	 */
	public static Map<String, String> queryFuelCard(String orderNo) {
		log.info("-queryFuelCard request begin-");
		//公共参数
		Map<String, String> commonParams = initCommonParams(fuelCardAppId, "300110", "加油卡充值订单查询");
		//业务参数
		Map<String, String> busiParams = new HashMap<String, String>();
		busiParams.put("ORDER_NO", orderNo);

		//业务参数MD5加密
		String busiParamsMd5Str = StringUtil.sign(busiParams, "");
		commonParams.put("params", busiParamsMd5Str);
		//请求数据签名
		String sign = StringUtil.sign(commonParams, fuelCardAppKey);

		Map<String, Object> reqParams = new HashMap<String, Object>();
		reqParams.putAll(commonParams);            //公共参数
		reqParams.put("params", busiParams);    //业务参数
		reqParams.put("sign", sign);            //签名
		String jsonStr = "";
		try {
			String reqParamsStr = JSONObject.toJSONString(reqParams, SerializerFeature.WriteMapNullValue);
			log.info("reqParamsStr:" + reqParamsStr);
			jsonStr = HttpKit.httpJson(PHONEURL, reqParamsStr, Constants.POST);
			log.info("jsonStr:" + jsonStr);
		} catch (Exception e) {
			log.error("queryFuelCard occur error.{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
		return dealResult(jsonStr);
	}

	/**
	 * 影视会员接口（充值接口）
	 * --充值参数--
	 * paramMap 里参数 ORDER_NO 订单号（32）
	 * paramMap 里参数 BUSS_TYPE 业务类型：(MGTV/IQIYI/TENCENT/…)MGTV=芒果TV(目前只支持芒果TV)
	 * paramMap 里参数 BUSS_TYPE_NAME 业务名称：芒果TV、爱奇艺、腾讯视频
	 * paramMap 里参数  ACCOUNT 账号（现阶段只支持手机号码）
	 * paramMap 里参数  PHONE_NO 手机号
	 * paramMap 里参数  PRODUCT_CODE 产品编码
	 * paramMap 里参数  PRODUCT_NAME 产品名称
	 * paramMap 里参数  PRODUCT_AMOUNT 充值金额
	 * paramMap 里参数  RET_URL 充值结果回调
	 *
	 * @param paramMap
	 * @return
	 */
	public static Map<String, String> rechargeFilmTelevision(Map<String, String> paramMap) {
		log.info("-rechargeFilmTelevision request begin-");
		//公共参数
		Map<String, String> commonParams = initCommonParams(filmVipAppId, "300200", "影视会员充值");
		//业务参数
		Map<String, String> busiParams = new HashMap<String, String>();
		if (null != paramMap.get("ORDER_NO") && !paramMap.get("ORDER_NO").equals("")) {
			busiParams.put("ORDER_NO", paramMap.get("ORDER_NO"));
		}
		if (null != paramMap.get("BUSS_TYPE") && !paramMap.get("BUSS_TYPE").equals("")) {
			busiParams.put("BUSS_TYPE", paramMap.get("BUSS_TYPE"));
		}
		if (null != paramMap.get("BUSS_TYPE_NAME") && !paramMap.get("BUSS_TYPE_NAME").equals("")) {
			busiParams.put("BUSS_TYPE_NAME", paramMap.get("BUSS_TYPE_NAME"));
		}
		if (null != paramMap.get("ACCOUNT") && !paramMap.get("ACCOUNT").equals("")) {
			busiParams.put("ACCOUNT", paramMap.get("ACCOUNT"));
		}
		if (null != paramMap.get("PHONE_NO") && !paramMap.get("PHONE_NO").equals("")) {
			busiParams.put("PHONE_NO", paramMap.get("PHONE_NO"));
		}
		if (null != paramMap.get("PRODUCT_CODE") && !paramMap.get("PRODUCT_CODE").equals("")) {
			busiParams.put("PRODUCT_CODE", paramMap.get("PRODUCT_CODE"));
		}
		if (null != paramMap.get("PRODUCT_NAME") && !paramMap.get("PRODUCT_NAME").equals("")) {
			busiParams.put("PRODUCT_NAME", paramMap.get("PRODUCT_NAME"));
		}
		if (null != paramMap.get("PRODUCT_AMOUNT") && !paramMap.get("PRODUCT_AMOUNT").equals("")) {
			busiParams.put("PRODUCT_AMOUNT", paramMap.get("PRODUCT_AMOUNT"));
		}
		if (null != paramMap.get("RET_URL") && !paramMap.get("RET_URL").equals("")) {
			busiParams.put("RET_URL", paramMap.get("RET_URL"));
		}

		//业务参数MD5加密
		String busiParamsMd5Str = StringUtil.sign(busiParams, "");
		commonParams.put("params", busiParamsMd5Str);
		//请求数据签名
		String sign = StringUtil.sign(commonParams, filmVipAppKey);

		Map<String, Object> reqParams = new HashMap<String, Object>();
		reqParams.putAll(commonParams);            //公共参数
		reqParams.put("params", busiParams);    //业务参数
		reqParams.put("sign", sign);            //签名
		busiParams.put("QUANTITY", paramMap.get("QUANTITY"));    //数量，新版本加入，不参与签名
		String jsonStr = "";
		try {
			String reqParamsStr = JSONObject.toJSONString(reqParams, SerializerFeature.WriteMapNullValue);
			log.info("reqParamsStr:" + reqParamsStr);
			jsonStr = HttpKit.httpJson(PHONEURL, reqParamsStr, Constants.POST);
			log.info("jsonStr:" + jsonStr);
		} catch (Exception e) {
			log.error("rechargeFilmTelevision occur error.{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
		return dealResult(jsonStr);
	}

	/**
	 * 影视会员接口
	 * --影视会员充值订单明细查询参数--
	 * orderNo 里参数 ORDER_NO 充值原始订单号（32）
	 *
	 * @return
	 */
	public static Map<String, String> queryFilmTelevision(String orderNo) {
		log.info("-queryFilmTelevision request begin-");
		//公共参数
		Map<String, String> commonParams = initCommonParams(filmVipAppId, "300220", "影视会员充值订单明细查询");
		//业务参数
		Map<String, String> busiParams = new HashMap<String, String>();
		busiParams.put("ORDER_NO", orderNo);
		//业务参数MD5加密
		String busiParamsMd5Str = StringUtil.sign(busiParams, "");
		commonParams.put("params", busiParamsMd5Str);
		//请求数据签名
		String sign = StringUtil.sign(commonParams, filmVipAppKey);

		Map<String, Object> reqParams = new HashMap<String, Object>();
		reqParams.putAll(commonParams);            //公共参数
		reqParams.put("params", busiParams);    //业务参数
		reqParams.put("sign", sign);            //签名
		String jsonStr = "";
		try {
			String reqParamsStr = JSONObject.toJSONString(reqParams, SerializerFeature.WriteMapNullValue);
			log.info("reqParamsStr:" + reqParamsStr);
			jsonStr = HttpKit.httpJson(PHONEURL, reqParamsStr, Constants.POST);
			log.info("jsonStr:" + jsonStr);
		} catch (Exception e) {
			log.error("queryFilmTelevision occur error.{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
		return dealResult(jsonStr);
	}

	/**
	 * 预存余额查询（查询间隔必须大于2分钟）
	 *
	 * @param busiType 业务类型（JYKCG-加油卡\FILMCG-影视会员）
	 * @param queryNo  查询流水号（32）
	 * @return
	 */
	public static Map<String, String> queryBalanceFuelCard(String busiType, String queryNo) {
		log.info("-queryBalanceFuelCard request begin-");
		//公共参数
		Map<String, String> commonParams;
		if ("JYK".equals(busiType)) {
			commonParams = initCommonParams(fuelCardAppId, "300130", "预存余额查询");
		} else if ("YSHY".equals(busiType)) {
			commonParams = initCommonParams(filmVipAppId, "300130", "预存余额查询");
		} else {
			commonParams = new HashMap<String, String>();
		}
		//业务参数
		Map<String, String> busiParams = new HashMap<String, String>();
		//返回的结果
		Map<String, String> retMap = new HashMap<String, String>();
		busiParams.put("QUERY_NO", queryNo);

		//业务参数MD5加密
		String busiParamsMd5Str = StringUtil.sign(busiParams, "");
		commonParams.put("params", busiParamsMd5Str);
		//请求数据签名
		String sign = "";
		if ("JYK".equals(busiType)) {
			sign = StringUtil.sign(commonParams, fuelCardAppKey);
		} else if ("YSHY".equals(busiType)) {
			sign = StringUtil.sign(commonParams, filmVipAppKey);
		}

		Map<String, Object> reqParams = new HashMap<String, Object>();
		reqParams.putAll(commonParams);            //公共参数
		reqParams.put("params", busiParams);    //业务参数
		reqParams.put("sign", sign);            //签名
		String jsonStr = "";
		try {
			String reqParamsStr = JSONObject.toJSONString(reqParams, SerializerFeature.WriteMapNullValue);
			log.info("reqParamsStr:" + reqParamsStr);
			jsonStr = HttpKit.httpJson(PHONEURL, reqParamsStr, Constants.POST);
			log.info("jsonStr:" + jsonStr);
		} catch (Exception e) {
			log.error("queryBalanceFuelCard occur error.{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
		if (StringUtils.isNotBlank(jsonStr)) {
			JSONObject json = JSONObject.parseObject(jsonStr);
			//接口处理结果
			if ("SUCCESS".equals(json.get("result").toString())) {
				JSONObject outparam = json.getJSONObject("outparam");
				//业务处理结果
				if ("SUCCESS".equals(outparam.get("BUSI_RESULT").toString())) {
					retMap.put("result", "SUCCESS");
					retMap.put("amount", outparam.get("AVAI_AMOUNT").toString());
				} else {
					retMap.put("result", "ERROR");
					retMap.put("result_desc", outparam.get("BUSI_RESULT_DESC").toString());
				}
			} else {
				retMap.put("result", "ERROR");
				retMap.put("result_desc", json.get("result_desc").toString());
			}
		} else {
			retMap.put("result", "ERROR");
			retMap.put("result_desc", "req timeout or the response not standard.");
		}
		return retMap;
	}

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("CARD_TYPE", "SINOPEC");
		map.put("CARD_TYPE_NAME", "中国石化加油卡");
		map.put("CARD_CODE", "1000113200021894219");
		map.put("PHONE_NO", "15019433985");
		map.put("RET_URL", "http://wx.palmnest.com/super_reception/login");
		map.put("RECHARGE_AMOUNT", "50");
		map.put("QUANTITY", "1");
		map.put("ORDER_NO", StringUtil.getOrderId("CG"));
		rechargeFuelCard(map);
//		System.out.println(map.get("ORDER_NO"));

		//queryFuelCard("20170720162408");
		
		/*Map<String,String> map = new HashMap<String, String>();
		map.put("ORDER_NO", "20170713125714");
		queryFilmTelevision(map);*/
		//queryFilmTelevision("20170720162258");
		
		/*Map<String,String> map = new HashMap<String, String>();
		map.put("ORDER_NO", "20170713125714");
		queryFilmTelevision(map);*/

//		Map<String,String> map = new HashMap<String, String>();
//		map.put("ORDER_NO", StringUtil.getOrderId(new Date().getTime()+""));
//		map.put("BUSS_TYPE", "MGTV");
//		map.put("BUSS_TYPE_NAME", "芒果tv");
//		map.put("ACCOUNT", "15019433985");
//		map.put("PHONE_NO", "15019433985");
//		map.put("PRODUCT_CODE", "MGTV11");
//		map.put("PRODUCT_NAME", "黄金月卡");
//		map.put("PRODUCT_AMOUNT", "19.8");
//		map.put("RET_URL", "http://wx.palmnest.com/super_reception/wechat/recharge/callbackVideoUrl");
//		map.put("QUANTITY", "1");
//		rechargeFilmTelevision(map);
	}
}
