package com.iamberry.wechat.service.pay;

import java.net.InetAddress;
import java.util.regex.Pattern;

import com.iamberry.wechat.tools.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.face.pay.PayService;

/**
 * @author 何秀刚 Class Description: 微信支付service实现 Create Date:2016年4月19日 Update
 *         Date:2016年4月19日
 */
@Service
public class PayServiceImpl implements PayService {

	@Autowired
	private WxPayUtil wxPayUtil;

	public void setWxPayUtil(WxPayUtil wxPayUtil) {
		this.wxPayUtil = wxPayUtil;
	}

	private static String ip = null;

	static {
		ip = getLocalIP();
	}

	public static String getLocalIP() {
		try {
			String localIP = "";
			InetAddress addr = (InetAddress) InetAddress.getLocalHost();
			// 获取本机IP
			localIP = addr.getHostAddress().toString();
			return localIP;
		} catch (Exception e) {
			return "120.76.152.52";
		}
	}

	private final Pattern pattern = Pattern
			.compile("(http[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?");

	@Override
	public PayResult requestPay(String openid, String orderId, Integer money,
			String reqPayGoodsName, String backUrl) {
		// TODO Auto-generated method stub
		PayResult payResult = new PayResult();
		/*if (!pattern.matcher(backUrl).find()) {
			payResult.setPayData("回调URL不正确!");
			return payResult;
		}*/
		Object object = wxPayUtil.getPackage(openid, orderId, money,
				ip, reqPayGoodsName, NameUtils.getConfig("appId"), backUrl);
		if (object.getClass() == String.class) {
			payResult.setPaySuccess(true);
			payResult.setPayData(object.toString());
		} else {
			WxPrepayIdErrorResult errorResult = (WxPrepayIdErrorResult) object;
			payResult.setPayData(errorResult.getErr_code_des());
			payResult.setPaySuccess(false);
		}
		return payResult;
	}
}
