package com.cirle.scientific.controller.pay;

import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cirle.scientific.service.PayCallbackService;
import com.cirle.scientific.utils.XmlUtil;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/paycallback")
@Api("支付回调相关接口")
@Slf4j
public class PayCallbackController {

	@Autowired
	private PayCallbackService payCallbackService;
	
	@RequestMapping(value = "/weixin",produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public String weixinpay(HttpServletRequest request) throws ServletException, IOException {
		log.info("进入微信支付消息回调回掉接口-PayCallbackController");
		BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
		CharArrayWriter reqWriter = new CharArrayWriter();
		char[] buf = new char[8192];
		int ret;
		while ((ret = in.read(buf, 0, 8192)) != -1) {
			reqWriter.write(buf, 0, ret);
		}
		String requestBody = reqWriter.toString();
		log.info("微信支付消息回调返回数据:\n " + requestBody + "\n");

		String return_code = XmlUtil.readXMLStr(requestBody ,"return_code");
		//获取自己的订单号
		String out_trade_no = XmlUtil.readXMLStr(requestBody, "out_trade_no");
		
		// 支付成功
		if ("SUCCESS".equals(return_code)) {
	    	//获取微信支付订单号
	    	String transaction_id = XmlUtil.readXMLStr(requestBody, "transaction_id");
	    	//获取支付完成时间
	    	String time_end = XmlUtil.readXMLStr(requestBody, "time_end");
	    	
			payCallbackService.updateStatus(out_trade_no, transaction_id, time_end, 1, 2);
		} else {
			payCallbackService.updateStatus(out_trade_no, null, null, 0, 2);
		}

		return "success";
	}
}
