package com.community.huiju.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.common.wxpay.WXPayConstants;
import com.community.huiju.common.wxpay.WXPayUtil;
import com.community.huiju.service.AliPayServiceI;
import com.community.huiju.service.WxPayServiceI;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET_UTF8;

/**
 * @author FXF
 * @date 2019-03-12
 */
@RestController
@RefreshScope
@RequestMapping("/")
@Api(value = "支付宝支付 API", description = "支付宝支付 API")
@Slf4j
public class AliPayController {
	
	private Logger log = LoggerFactory.getLogger(AliPayController.class);
	
	@Autowired
	private AliPayServiceI aliPayService;
	
	@Autowired
	private WxPayServiceI wxPayService;
	
	@Value("${alipay.ALIPAY_PUBLIC_KEY}")
	private String ALIPAY_PUBLIC_KEY;
	
	@ApiOperation(value = "统一下单", notes = "统一下单")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", dataType = "String", name = "outTradeNo", value = "订单号"),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "type", value = "订单类型：type: 类型(car 车缴费, bill 物业缴费)"),
			@ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token") })
	@RequestMapping(value = "/aliPayOrder/{outTradeNo}",method = RequestMethod.GET)
	public ResponseBean wxUnifiedOrder(@PathVariable("outTradeNo") String outTradeNo, @RequestParam("type") String type, HttpSession session){
		ResponseBean responseBean = new ResponseBean();
		UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
		String resp = "";
		try {
			resp = aliPayService.AliPayOrder(outTradeNo, type,userElement);
		} catch (Exception e) {
			e.printStackTrace();
			responseBean.addError(e.getMessage());
			return responseBean;
		}
		responseBean.addSuccess(resp);
		return responseBean;
	}
	
	@ApiOperation(value = "支付宝手机订单支付完成后回调 物业缴费", notes = "支付宝手机订单支付完成后回调")
	@RequestMapping(value = "/aliPayBillNotify",method = RequestMethod.POST)
	public void aliPayBillNotify(HttpServletRequest request, HttpServletResponse response){
		log.info("支付宝手机订单支付完成后回调 物业缴费");
		wxNotify(request, Constant.PAY_TYPE_BILL);
	}

	@ApiOperation(value = "支付宝手机订单支付完成后回调 车缴费", notes = "支付宝手机订单支付完成后回调 车缴费")
	@RequestMapping(value = "/aliPayCarNotify",method = RequestMethod.POST)
	public void aliPayCarNotify(HttpServletRequest request, HttpServletResponse response){
		log.info("支付宝手机订单支付完成后回调 车缴费");
		wxNotify(request, Constant.PAY_TYPE_CAR);
	}

	/**
	 * 支付回调
	 * @param request
	 * @param type
	 */
	private void wxNotify(HttpServletRequest request, String type) {
		log.info("支付宝 alipay result  start =======");
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		try {
			boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET_UTF8,"RSA2");
			if (flag){
				params.put("pay_type","2");
				if (Constant.PAY_TYPE_BILL.equals(type)) {
					wxPayService.wxBillNotify(params);
				} else if (Constant.PAY_TYPE_CAR.equals(type)){
					wxPayService.wxCarNotify(params);
				}

			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
