package com.smart.gtstrvl;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.alipay.sdk.app.PayTask;
import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.kind.GameInfo;
import com.example.mountaintravel.kind.PayResult;
import com.example.mountaintravel.util.SignUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class PayActivity extends BaseActivity implements OnClickListener {
	private TextView pay_tvadd;
	private TextView pay_tvnumber;
	private TextView pay_tvreduce;
	private TextView pay_tvnum;
	private TextView pay_tvwushi;
	private TextView pay_iv;
	private int number = 1;
	private int money = 50;
	// 商户PID
	public static final String PARTNER = "2088021830678838";
	// 商户收款账号
	public static final String SELLER = "gaotingshan517@163.com ";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
	private static final int SDK_PAY_FLAG = 1;
	private String orderInfo = "";
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT)
							.show();
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay);
		initTitleBar("确认订单");
		findView();
	}

	private void findView() {
		// TODO Auto-generated method stub
		pay_tvadd = (TextView) findViewById(R.id.pay_tvadd);
		pay_tvnumber = (TextView) findViewById(R.id.pay_tvnumber);
		pay_tvnum = (TextView) findViewById(R.id.pay_tvnum);

		pay_tvwushi = (TextView) findViewById(R.id.pay_tvwushi);
		pay_tvreduce = (TextView) findViewById(R.id.pay_tvreduce);
		pay_iv = (TextView) findViewById(R.id.pay_iv);
		pay_iv.setOnClickListener(this);
		pay_tvadd.setOnClickListener(this);
		pay_tvreduce.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.pay_tvadd:
			number++;
			pay_tvnumber.setText(number + "");
			pay_tvnum.setText(number + "");
			money = number * 50;
			pay_tvwushi.setText(money + ".00");
			break;
		case R.id.pay_tvreduce:
			if (number > 1) {
				number--;
				pay_tvnumber.setText(number + "");
				pay_tvnum.setText(number + "");
				money = number * 50;
				pay_tvwushi.setText(money + ".00");
			}

			break;
		case R.id.pay_iv:
			orderInfo = getOrderInfo("登山卡", "智能登山辅助设备", "5.00");
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					pay(orderInfo);
				}
			}).start();
			break;
		}
	}
	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String sign = (String) msg.obj;
				/**
				 * 完整的符合支付宝参数规范的订单信息
				 */
				final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
						+ getSignType();

				Runnable payRunnable = new Runnable() {

					@Override
					public void run() {
						// 构造PayTask 对象
						PayTask alipay = new PayTask(PayActivity.this);
						// 调用支付接口，获取支付结果
						String result = alipay.pay(payInfo, true);
						Message msg = new Message();
						msg.what = SDK_PAY_FLAG;
						msg.obj = result;
						mHandler.sendMessage(msg);
					}
				};

				// 必须异步调用
				Thread payThread = new Thread(payRunnable);
				payThread.start();
				break;
			}

			super.handleMessage(msg);
		}
	};

	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);
		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	private void pay(String orderInfo) {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address
				+ "/terminal/payment/getAlipaySign";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("orderInfo", orderInfo));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			httpPost.setEntity(entity);
			if (!Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
																// //在浏览器中敲一下回车
			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				InputStream is = response.getEntity().getContent();
				int b = 0;
				StringBuffer sb = new StringBuffer();
				while ((b = is.read()) != -1) {
					sb.append((char) b);
				}

				String result = sb.toString();
				Message message = new Message();
				message.what = 1;
				message.obj = result;
				handler.sendMessage(message);

			} else {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						ToastUtil.show(PayActivity.this, "网络异常");
					}
				});
			}
		} catch (Exception e) {
			runOnUiThread(new Runnable() {
				public void run() {
					ToastUtil.show(PayActivity.this, "网络异常");
				}
			});
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}
}
