package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.core.util.Tools;
import com.palmnest.model.estateserve.Recharge;
import com.palmnest.service.wechat.RechargeManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信回调处理
 *
 * @author xiemin
 */
@Slf4j
@Controller
@RequestMapping(value = "/wechat/wxcallback*")
public class WxCallBackController {


	@Autowired
	private RechargeManager rechargeManager;

	/**
	 * 微信支付回调
	 *
	 * @return
	 */
	@RequestMapping(value = "notifyUrl")
	public synchronized String notifyUrl(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/xml");

			ServletInputStream in     = request.getInputStream();
			String             xmlMsg = Tools.inputStream2String(in);

			log.info("####xmlMsg:" + xmlMsg);

			JSONObject json = JSON.parseObject(StringUtil.xmlToJSON(xmlMsg));
			json = json.getJSONObject("xml");
			JSONObject jsonaAtach = JSON.parseObject(json.getString("attach"));

			log.info("#jsonaAtach:" + jsonaAtach);

			Map<String, String> map = new HashMap<String, String>();

			String outPut = "";
			//聚点充值
			if ("SUCCESS".equals(json.getString("return_code")) && "SUCCESS".equals(json.getString("result_code")) && StringUtils.isNotBlank(jsonaAtach.getString("type"))) {
				String out_trade_no  = json.getString("out_trade_no"); // 商户订单号
				String transactionId = json.getString("transaction_id"); // 微信返回id
				String mchId         = json.getString("mch_id"); // 微信商户号
				map.put("outTradeNo", out_trade_no);
				map.put("transactionId", transactionId);
				map.put("type", jsonaAtach.getString("type"));
				map.put("mchId", mchId);
				outPut = rechargeManager.updateRechargeStatus(map);
			} else {
				String outTradeNo = json.getString("out_trade_no"); // 商户订单号
				// 根据订单号查询充值信息
				Recharge re = rechargeManager.findRechargeByOrdId(outTradeNo);
				re.setPayStatus("-1"); // 支付失败
				rechargeManager.updateRecharge(re);
			}
			response.getWriter().write(outPut);
		} catch (Exception e) {
			log.error("callbackUrl error {}", e, e.getMessage());
		}
		return null;
	}

}
