package com.community.huiju.controller;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.redis.RedisTemplate;
import com.community.commom.session.UserElement;
import com.community.huiju.common.wxpay.HfWxConfig;
import com.community.huiju.common.wxpay.WXPay;
import com.community.huiju.common.wxpay.WXPayConstants;
import com.community.huiju.common.wxpay.WXPayUtil;
import com.community.huiju.service.TaVistorServiceI;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.lang.reflect.Type;
import java.util.*;

/**
 * @author FXF
 * @date 2019-02-19
 */
@RestController
@RefreshScope
@RequestMapping("/")
@Api(value = "微信支付 API", description = "微信支付 API")
public class WxPayController {
	private Logger log = LoggerFactory.getLogger(WxPayController.class);
	
	@Autowired
	private WxPayServiceI wxPayService;
	
	@ApiOperation(value = "统一下单", notes = "统一下单")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", dataType = "Integer", name = "outTradeNo", value = "订单号"),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "type", value = "订单类型： bill 表示订单，car 车缴费"),
			@ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
	})
	@RequestMapping(value = "/wxUnifiedOrder/{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);
		
		Map<String, String> resp = Maps.newHashMap();
		try {
			resp = wxPayService.wxUnifiedOrder(outTradeNo, type,userElement);
		} catch (Exception e) {
			e.printStackTrace();
			responseBean.addError(e.getMessage());
			return responseBean;
		}
		log.info("调用微信支付参数: {}",resp);
		responseBean.addSuccess(resp);
		return responseBean;
	}
	
	@ApiOperation(value = "手机订单支付完成后回调 物业缴费", notes = "手机订单支付完成后回调 物业缴费")
	@RequestMapping(value = "/wxBillNotify",method = RequestMethod.POST)
	public String wxBillNotify(HttpServletRequest request, HttpServletResponse response){
		return wxNotify(request, Constant.PAY_TYPE_BILL);
	}


	@ApiOperation(value = "手机订单支付完成后回调 车缴费", notes = "手机订单支付完成后回调 车缴费")
	@RequestMapping(value = "/wxCarNotify",method = RequestMethod.POST)
	public String wxCarNotify(HttpServletRequest request, HttpServletResponse response){

		return wxNotify(request, Constant.PAY_TYPE_CAR);
	}

	/**
	 * 微信支付回调
	 * @param request
	 * @param type
	 * @return
	 */
	private String wxNotify(HttpServletRequest request, String type) {
		String failResult = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[失败]]></return_msg>" + "</xml> ";
		String successResult = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
		InputStream inStream;
		try {

			inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}

			// 获取微信调用我们notify_url的返回信息
			String result = new String(outSteam.toByteArray(), "utf-8");
			WXPayUtil.getLogger().info("wxnotify:微信支付----result----=" + result);

			// 关闭流
			outSteam.close();
			inStream.close();

			// xml转换为map
			Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
			if (WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
				//处理业务逻辑 修改订单状态等
				resultMap.put("pay_type","0");
				String state = "";
				if (Constant.PAY_TYPE_CAR.equals(type)) {
					state = wxPayService.wxCarNotify(resultMap);
				} else if (Constant.PAY_TYPE_BILL.equals(type)) {
					state = wxPayService.wxBillNotify(resultMap);
				}

				if (state.equals("success")){
					log.info("微信支付成功。。");
					return successResult;
				}
			}else{
				return failResult;
			}

		} catch (Exception e) {
			log.error("手机支付回调通知失败",e);
			return failResult;

		}

		return failResult;
	}

	
	@ApiOperation(value = "订单查询", notes = "订单查询")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "path", dataType = "Integer", name = "outTradeNo", value = "订单号")
	})
	@RequestMapping(value = "/wxOrderQuery/{outTradeNo}",method = RequestMethod.GET)
	public ResponseBean wxOrderQuery(@PathVariable("outTradeNo") String outTradeNo){
		ResponseBean responseBean = new ResponseBean();
		Map<String, String> resp = Maps.newHashMap();
		try {
			resp = wxPayService.wxOrderQuery(outTradeNo);
		} catch (Exception e) {
			e.printStackTrace();
			responseBean.addError("查询失败");
			return responseBean;
		}
		responseBean.addSuccess(resp);
		return responseBean;
	}
	
	@ApiOperation(value = "准备开始支付", notes = "准备开始支付")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "body", dataType = "String", name = "parameter", value = "idArray:账单Id集合, type: 类型(car 车缴费, bill 物业缴费), extensionMonth: 延期月份，也就是延期几个月！只有在 车缴费的时候才有效"),
			@ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
	})
	@RequestMapping(value = "/wxStartPay",method = RequestMethod.POST)
	public ResponseBean wxStartPay(@RequestBody String parameter, HttpSession session){
		ResponseBean responseBean = new ResponseBean();
		try {
			UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
			JSONObject jsonObject = JSONObject.parseObject(parameter);
			Integer[] integers = jsonObject.getJSONArray("idArray").toArray(new Integer[]{});
			String type = jsonObject.getString("type");
			Integer extensionMonth = jsonObject.getInteger("extensionMonth");

			String outTradeNo = wxPayService.wxStartPay(Arrays.asList(integers), type, extensionMonth,userElement);
			Map<String,Object> resultMap = Maps.newHashMap();
			resultMap.put("outTradeNo", outTradeNo);
			responseBean.addSuccess(resultMap);
		} catch (Exception e) {
			e.printStackTrace();
			responseBean.addError(e.getMessage());
			return responseBean;
		}
		return responseBean;
	}
	
	@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 = "/wxCancelPay/{outTradeNo}",method = RequestMethod.GET)
	public ResponseBean wxCancelPay(@PathVariable("outTradeNo") String outTradeNo, @RequestParam("type") String type,HttpSession session){
		ResponseBean responseBean = new ResponseBean();
		try {
			UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
			wxPayService.wxCancelPay(outTradeNo, type,userElement);
		} catch (Exception e) {
			e.printStackTrace();
			responseBean.addError(e.getMessage());
			return responseBean;
		}
		return responseBean;
	}
}
