package com.backfire.doudizhu;

import java.util.HashMap;
import java.util.TreeMap;

import net.yeeyo.doudizhu.feiyu.R;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Handler;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;

/*import cn.wimipay.sdk.WimiPaySdk;
import cn.wimipay.sdk.WimiPaymentCallback;*/

import com.backfire.doudizhu.common.APNUtil;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.LoadingProgressDialog;
import com.backfire.doudizhu.common.Md5;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.lobby.AddStatistics;
import com.backfire.doudizhu.userinfo.UserInfo;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.php.PHPCallbackInterface;
import com.backfire.php.PHPConnect;
import com.backfire.php.PHPMethodName;
import com.backfire.php.PHPRequestPool;
import com.backfire.php.PHPResult;
import com.backfire.php.PHPResult.ErrorCode;
import com.backfire.php.URLUtil;
import com.backfire.popupwindow.BuyFailPopupWindow;
import com.backfire.popupwindow.BuyTipPopupWindow;
import com.backfire.utils.Log;
import com.backfire.utils.MyAsyncTask;
import com.backfire.utils.MyTaskWrap;
import com.easou.epay_all.EpayU.Pay;
import com.easou.epay_all.activity.EasouPayActivity;
import com.easou.epay_all.util.EasouConstant;
/*import com.qnn.SDKCallback;
import com.qnn.SDKFace;*/
import com.umeng.analytics.MobclickAgent;

/**
 * @Title: ActivityThirdPlatform.java
 * @Package com.backfire.doudizhu
 * @Description: 第三方平台相关东西接入。（支付）
 * @author Potter
 * @date 2014-1-17 上午11:24:53
 * @version V2.0
 */
public abstract class ActivityThirdPlatform extends ActivityBase{
	public abstract void updateUserMsgSuccess();

	public abstract String getTipBuy(final long needMoney);

	public abstract void rechargeSuccess(String msg);

	public abstract void showMessage(String msg);

	protected abstract void orderFailed(final long needMoney);

	public void userMessageRequest() {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new UserMessageCallback(),
				PHPMethodName.CLI_USERINFO_REQ, json);
	}

	private class UserMessageCallback implements PHPCallbackInterface {

		public void onFinish(PHPResult result) {
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();

						JSONObject money = JSONUtil.getJSONObject(res,
								"moneyBean");

						self.setMoney(JSONUtil.getLong(money, "money", 0));
						self.setVip(JSONUtil.getInt(money, "vip", 0));
						self.setVipTime(JSONUtil.getInt(money, "vipTime", 0));
						self.setLottery(JSONUtil.getLong(money, "lottery", 0));
						self.setExchangeCard(JSONUtil.getLong(money,
								"exchange", 0));

						self.setNeedLottery(JSONUtil.getInt(res, "needLottery",
								0));

						try {
							((ActivityThirdPlatform) ActivityContainer
									.getInstance().getCurrentActivity())
									.updateUserMsgSuccess();
						} catch (Exception e) {
							Log.e(this, e);
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	public void getServerOrder(final String paycode, final long uid,
			final int goodId, final int price, final String desc,
			final long needMoney) {
		Log.i(this, "isGoodBuying="
				+ UserMessageCenter.getInstance().isGoodBuying);
		if (UserMessageCenter.getInstance().isGoodBuying) {
			return;
		}
		UserMessageCenter.getInstance().isGoodBuying = true;
		startLoading("加载信息中，请稍候...");
		new MyAsyncTask(new MyTaskWrap() {
			String result = "";

			@Override
			public void onTaskStart() {
				StringBuffer sb2 = new StringBuffer(128);
				sb2.append("Theoneisontheway2012-12-12")
						.append("|")
						.append(uid)
						.append("|")
						.append(UserMessageCenter.getInstance().getUserInfo()
								.getSession()).append("|")
						.append(UserMessageCenter.getInstance().appId);
				sb2.append("||||")
						.append(UserMessageCenter.getInstance().thirdAPPId)
						.append("|").append(goodId).append("|")
						.append(price * 100).append("|").append(1);
				String md5sign = Md5.hash(sb2.toString()).toLowerCase();

				String postdata = "appId="
						+ UserMessageCenter.getInstance().appId
						+ "&uid="
						+ uid
						+ "&goodId="
						+ goodId
						+ "&price="
						+ price
						* 100
						+ "&num=1"
						+ "&partnerId="
						+ UserMessageCenter.getInstance().thirdAPPId
						+ "&session="
						+ UserMessageCenter.getInstance().getUserInfo()
								.getSession() + "&sign=" + md5sign
						+ "&paytype=" + UserMessageCenter.payType;

				Log.v("getServerOrder", "postdata:" + postdata);
				result = URLUtil
						.getPostRequestStr(PHPConnect.pay_url, postdata);
				Log.v("getServerOrder", "result:" + result);
			}

			@Override
			public void onTaskFinish() {
				if (result == null || result.trim().length() == 0) {
					Log.v("shop", "MM下单失败......");
					orderFailed(needMoney);
					AddStatistics.addCanNotPayStatistics(
							ActivityThirdPlatform.this, "下单失败：网络异常");
				} else {
					JSONObject retjson = JSONUtil.parse(result);
					if (retjson != null) {
						int ret = JSONUtil.getInt(retjson, "ret", 0);
						if (ret == 1) {
							// 下单成功
							String orderid = JSONUtil.getString(retjson,
									"orderId", "");
							if (orderid.trim().length() > 0) {
								thirdpay(paycode, orderid, desc, needMoney,
										price);
							} else {
								orderFailed(needMoney);
								int retCode = JSONUtil.getInt(retjson,
										"retCode", 0);
								String msg = JSONUtil.getString(retjson,
										"retMsg", "");
								AddStatistics.addCanNotPayStatistics(
										ActivityThirdPlatform.this, "下单失败："
												+ msg + "(" + retCode + ")");
							}
						} else {
							orderFailed(needMoney);
							AddStatistics.addCanNotPayStatistics(
									ActivityThirdPlatform.this, "下单失败：数据解析异常");
						}
					} else {
						orderFailed(needMoney);
						AddStatistics.addCanNotPayStatistics(
								ActivityThirdPlatform.this, "下单失败：数据解析异常");
					}
				}
			}

		}).execute();
	}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("requestCode is " + requestCode + " , " + resultCode + " order ID " +data.getStringExtra(Pay.EPAY_CP_ORDER_ID) );
		if (requestCode == Pay.REQUESTCODE) {// 是epay返回数据
			switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
			case EasouConstant.SUCC:// 支付成功
				
				checkGoodsRequest("", data.getStringExtra(Pay.EPAY_CP_ORDER_ID), "");	
//				checkGoodsRequest("", orderID, "");	
				break;
			case EasouConstant.ERROR_CHANNEL_RESPONSE_UNKONW:// 支付失败
			case EasouConstant.ERROR_CONNECTION:// 支付失败
			case EasouConstant.ERROR_EXCEPTION:// 支付失败
			case EasouConstant.ERROR_PARAM:// 支付失败
			case EasouConstant.ERROR_SERVER:// 支付失败
			case EasouConstant.FAILED:// 支付失败
				
				break;
			default:// 支付失败
				break;
			}
		}
	}
	
	private void thirdpay(final String paycode, final String orderID,
			final String desc, final long needMoney, final int price) {
		UserMessageCenter.getInstance().isGoodBuying = false;
		stopLoading();
//		startLoading("正在加载数据中...");
	String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMsCNDhcp9N5gNHig+ScU1idB8LA9unTUmW0xvrmiQEDp1p78dHGGS32hq48w0GQJ2sL3HWYFoUrqZthNhkSSsHUlOtUBl/huNngAQ8VrwbAjnNddE9HwAfZ/MxBKz0JdcjDdlZ0VskcEe466JZnrQXy8zyHQn2Nih33mN8S9AH5AgMBAAECgYAj6FfkQD9PIIawmShLH3t+iQf+YrNJ2J8Sbk9jwbMqAsNvNc0oFaoOfzSDTSwcRKs0O/zar/QLyhVN7nvrI1klbwEC+lhXtBp8lyUdiIr7LDl6y8feD12Y4BZqjEIYs5SfIlVig7tw0YRdKDBF2kvLdN2sgKJ/2109b2OlPOHCIQJBAO6+DQOzONg5Ul2yu2CCxcyXpaWtHmmKtUaOTAvolK2U6y54W+UX9M+Zyny0XB/Rb30pgqSZ+fVaKPymd/dTfTMCQQDZruV7tpMQKdPLw7YqpkDLOfYPWW+ao2KHFIQJKoVAjZekcIhnXMNnvT+OjxTE6AEoBtMv4vttJKHXaWDppowjAkBs+8r7HmxboEcuSLHqy6e5zpwqdk3ExjIcREcIxKJiXvHBI+ZnPTlfL4hUxwyq5bNsQm/F7hhB3WeKdf+borwrAkBVGCSHNvjIQcGUjv4gL/t2NkM0/t480g/LBD8VIjUS5gbYdlEsLrwISpeUz+PrkVIaZoiZ2J42rTJC9eO3kq6HAkAYXrY6H/VdDCb2mglTXec6a7cYNwRdjyOqnUESWOXv7yLy3OGNKJbV2LwOVVNf1IKLJG/Q9+eX+/2I2NcLi3iG";
		
		Intent intent = new Intent(this, EasouPayActivity.class);
		intent.putExtra(Pay.EPAY_FEE, price*100);// 计费金额以分为单位
		intent.putExtra(Pay.EPAY_CPID, 996);// CpID，在我司后台申请
		intent.putExtra(Pay.EPAY_APPFEE_ID, Integer.valueOf(paycode));//计费ID，在我司后台申请
		intent.putExtra(Pay.EPAY_CP_PRIVATE_KEY, privateKey);// 用户私钥
		intent.putExtra(Pay.EPAY_CP_ORDER_ID, orderID);// 用户定单ID
		intent.putExtra(Pay.EPAY_APPNAME, desc);// 商品名称
		this.startActivityForResult(intent, Pay.REQUESTCODE);
	
		
		/* WimiPaySdk.buy(ActivityThirdPlatform.this, paycode, desc, orderID, new WimiPaymentCallback() {
				@Override
				public void onBuyProductOK(String arg0, String arg1) {
					// TODO Auto-generated method stub
					
					DdzApplication.getApplication().showToast("商品购买成功 ！");
					(new Handler()).postDelayed(new Runnable() {
						@Override
						public void run() {
							checkGoodsRequest("", orderID, "");						
						}

					}, 3000);
					
				}
				
				@Override
				public void onBuyProductFailed(String arg0, String arg1) {
					// TODO Auto-generated method stub
					DdzApplication.getApplication().showToast("商品购买取消 ！");
				}
			});
			*/
		
		//-------------------------
		/* SDKFace.btext(paycode,orderID,desc,new SDKCallback(ActivityThirdPlatform.this,45000){

				@Override
				public void onFail(int errorNo,int paycode, String orderID, String text) {
					Log.i(this, text);
					stopLoading();
					String msg = ActivityThirdPlatform.this
							.getTipBuy(needMoney);
					if (null == msg) {
						msg = text;
					}
					AddStatistics.addCanNotPayStatistics(
							ActivityThirdPlatform.this, text);
					BuyFailPopupWindow alert = new BuyFailPopupWindow(
							ActivityThirdPlatform.this, msg, true);
					alert.setListens(null);
					alert.ShowWindowInCenter();
				}

				@Override
				public void onSuccess(final int paycode, final String orderID,String msg) {
					
					Log.i(this, msg);
					stopLoading();
					BuyTipPopupWindow select = new BuyTipPopupWindow(ActivityThirdPlatform.this,msg);
					select.setListens(new OnClickListener(){
						@Override
						public void onClick(View arg0) {
							startLoading("正在充值中，请稍候...");
							Log.i("orderSuccess", "orderID:"+orderID);
							SDKFace.bwork(paycode,orderID, new SDKCallback(ActivityThirdPlatform.this, 45000){

								public void onFail(int errorNo,int pointId, String orderNo, String msg) {
									LoadingProgressDialog.dissmissDlg();
									showInfo(DdzApplication.getApplication().getPayTip(
											DdzApplication.PAY_TIP_CHARGE_FAIL));// 充值不成功，请重试！
									doMsg(0, "支付失败" + msg);
									HashMap<String, String> purchase = new HashMap<String, String>();
									purchase.put("version", UserMessageCenter.getInstance().version);
									purchase.put("uid", UserMessageCenter.getInstance().getUserInfo()
											.getUid()
											+ "");
									purchase.put("apn", APNUtil.getApnName(ActivityThirdPlatform.this));
									purchase.put("msg", "渠道支付失败：" + msg);
									MobclickAgent.onEvent(ActivityThirdPlatform.this, "Can_Not_Pay", purchase);
								}

								@Override
								public void onSuccess(int pointId, final String orderNo,String msg) {
									
									doMsg(0, "支付成功" + msg);
									Log.e("talkingData", "orderNo=" + orderNo);
									// TDGAVirtualCurrency.onChargeSuccess(orderNo);
									(new Handler()).postDelayed(new Runnable() {

										@Override
										public void run() {
											checkGoodsRequest("", orderNo, "");
										}

									}, 3000);
								}

								@Override
								public void onTimeout() {
									// TODO Auto-generated method stub
									
								}});
							
						}
						
					}, null);
					select.ShowWindowInCenter();
					
					
				}

				@Override
				public void onTimeout() {
					String ms= "网络超时，请稍候再试";
					stopLoading();
					String msg = ActivityThirdPlatform.this
							.getTipBuy(needMoney);
					if (null == msg) {
						msg = ms;
					}
					AddStatistics.addCanNotPayStatistics(
							ActivityThirdPlatform.this,ms);
					BuyFailPopupWindow alert = new BuyFailPopupWindow(
							ActivityThirdPlatform.this, msg, true);
					alert.setListens(null);
					alert.ShowWindowInCenter();
				}
				 
			 });*/

	}

	// 查看购买信息
	private void checkGoodsRequest(String tradeId, String orderId, String amount) {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("orderid", orderId);
		param.put("tradeId", tradeId);
		param.put("amount", amount);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new CheckGoodsCallback(tradeId, orderId, amount, 1),
				PHPMethodName.CLI_CHECK_GOODS_REQ, json);
	}

	private void reCheckGoodsRequest(final String tradeId,
			final String orderId, final String amount, final int times) {
		(new Handler()).postDelayed(new Runnable() {

			@Override
			public void run() {
				UserInfo self = UserMessageCenter.getInstance().getUserInfo();
				TreeMap<String, Object> param = new TreeMap<String, Object>();
				param.put("uid", self.getUid());
				param.put("session", self.getSession());
				param.put("orderid", orderId);
				param.put("tradeId", tradeId);
				param.put("amount", amount);

				String json = new MyJson(param).toString();
				PHPRequestPool.getInstance()
						.AddRequest(
								new CheckGoodsCallback(tradeId, orderId,
										amount, times),
								PHPMethodName.CLI_CHECK_GOODS_REQ, json);
			}

		}, getTime(times));
	}

	private class CheckGoodsCallback implements PHPCallbackInterface {
		private int times = 0;
		private String orderId = "";
		private String tradeId = "";
		private String amount = "";

		public CheckGoodsCallback(String tradeId, String orderId,
				String amount, int times) {
			this.times = times;
			this.orderId = orderId;
			this.tradeId = tradeId;
			this.amount = amount;
		}

		public void onFinish(PHPResult result) {
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						UserInfo self = UserMessageCenter.getInstance()
								.getUserInfo();

						JSONObject money = JSONUtil.getJSONObject(res,
								"moneyBean");

						self.setMoney(JSONUtil.getLong(money, "money", 0));
						self.setVip(JSONUtil.getInt(money, "vip", 0));
						self.setVipTime(JSONUtil.getInt(money, "vipTime", 0));

						long lottery = JSONUtil.getLong(money, "lottery", 0);
						long exchange = JSONUtil.getLong(money, "exchange", 0);
						if (exchange > 0) {
							self.setExchangeCard(exchange);
						}
						if (lottery > 0) {
							self.setLottery(lottery);
						}

						LoadingProgressDialog.dissmissDlg();
						String msg = "恭喜您，购买商品成功！您目前持有<font color=red>金币"
								+ self.getMoney() + "  </font>";
						if (self.getLottery() > 0) {
							msg += "<font color=red>,彩券 " + self.getLottery()
									+ " 张</font>";
						}
						if (self.getExchangeCard() > 0) {
							msg += "<font color=red>,无敌卡 "
									+ self.getExchangeCard() + " 张</font>";
						}
						AddStatistics.addPaySuccessStatistics(
								ActivityThirdPlatform.this, times);
						try {
							((ActivityThirdPlatform) ActivityContainer
									.getInstance().getCurrentActivity())
									.rechargeSuccess(msg);
						} catch (Exception e) {
							Log.e(this, e);
							e.printStackTrace();
						}
					} else {
						isReCheckGoods(tradeId, orderId, amount, times);
					}
				} else {
					isReCheckGoods(tradeId, orderId, amount, times);
				}
			} else {
				isReCheckGoods(tradeId, orderId, amount, times);
			}
		}
	}

	public void isReCheckGoods(String tradeId, String orderId, String amount,
			int times) {
		times++;
		if (times == 3) {
			LoadingProgressDialog.dissmissDlg();
			showInfo(DdzApplication.getApplication().getPayTip(
					DdzApplication.PAY_TIP_CHARGE_WAIT_DELIVERY));// 订单已创建，发货有时会有延时，请稍后重新登录更新您的信息!
			reCheckGoodsRequest(tradeId, orderId, amount, times);
		} else if (times > 8) {
			// 8次以上，不再验证
			confirmOrderFailed(orderId);
		} else {
			reCheckGoodsRequest(tradeId, orderId, amount, times);
		}
	}

	private void confirmOrderFailed(String orderId) {
		UserInfo self = UserMessageCenter.getInstance().getUserInfo();
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session", self.getSession());
		param.put("orderid", orderId);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new ConfirmOrderFailedCallback(),
				PHPMethodName.CLI_CONFIRM_GOODS_FAILED_REQ, json);
	}
	
	


	protected class RechargeGoodsCallback implements PHPCallbackInterface {
		private long needMoney;

		public RechargeGoodsCallback(long money) {
			needMoney = money;
		}

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						JSONObject p = JSONUtil.getJSONObject(res, "products");
						final int pid = JSONUtil.getInt(p, "productID", 0);
						final int price = JSONUtil.getInt(p, "price", 0);
						String desc = JSONUtil.getString(p, "desc", "");
						final String payCode = JSONUtil
								.getString(p, "paycode", "");

						String giftinfo = JSONUtil.getString(p, "giftinfo", "");
						if (giftinfo.trim().length() > 0) {
							desc = desc + "," + Html.fromHtml(giftinfo);
						}

						getServerOrder(payCode, UserMessageCenter.getInstance()
								.getUserInfo().getUid(), pid, price, desc,
								needMoney);
					} else {
						// 登录失败
						int retCode = JSONUtil.getInt(res, "retCode", 0);
						String msg = JSONUtil.getString(res, "retMsg", "");
						showMessage(msg + "(" + retCode + ")");

						AddStatistics.addCanNotPayStatistics(
								ActivityThirdPlatform.this, "获取商品失败：" + msg
										+ "(" + retCode + ")");
					}
				} else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
					AddStatistics.addCanNotPayStatistics(
							ActivityThirdPlatform.this, "获取商品失败：数据包解析异常");
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
				AddStatistics.addCanNotPayStatistics(
						ActivityThirdPlatform.this, "获取商品失败：网络异常异常");
			}
		}
	}

	private class ConfirmOrderFailedCallback implements PHPCallbackInterface {
		public void onFinish(PHPResult result) {
			LoadingProgressDialog.dissmissDlg();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if (res != null) {
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if (ret == 1) {
						Log.i(this, "提交验单失败命令成功");
					} else {
						Log.i(this, "提交验单失败命令失败");
					}
				} else {
					Log.i(this, "提交验单失败命令失败");
				}
			} else {
				Log.i(this, "提交验单失败命令失败");
			}
		}
	}

	protected void doMsg(int eventTypeNum, Object obj) {
		Log.v("支付：-------", "支付：-------》eventTypeNum:" + eventTypeNum
				+ "---->msg:" + (String) obj);
	}

	

}
