package com.sv.api.controller;

import com.dw.ccm.wechat.base.utils.XMLUtils;
import com.sv.api.context.PlatformContext;
import com.sv.dto.api.wechat.WechatNotifyResponse;
import com.sv.service.api.MemberRefundService;
import com.sv.service.api.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RequestMapping(value = "/weixin/order")
@Controller
public class WXPayNotifyController {

    private static Logger logger = LoggerFactory.getLogger(WXPayNotifyController.class);

    @Resource
    private OrderService orderService;
    @Resource
    private MemberRefundService memberRefundService;

    /**
     * 微信支付后的回调处理
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/Notify", method = RequestMethod.POST)
    public WechatNotifyResponse notify(HttpServletRequest request) {
        try {
            Map<String,String> params = XMLUtils.toMap(request.getInputStream());
            orderService.notifyWx(params);
        } catch (Exception e) {
            logger.error("微信支付回调验证出错", e);
            return new WechatNotifyResponse("FAIL", "ok");
        }
        return new WechatNotifyResponse("SUCCESS", "ok");
    }

    /**
     * 微信退款回调处理
     */
    @ResponseBody
    @RequestMapping(value = "/refund", method = RequestMethod.POST)
    public WechatNotifyResponse refund(HttpServletRequest request) {
        try {
            Map<String,String> params = XMLUtils.toMap(request.getInputStream());
            memberRefundService.notifyRefund(params,PlatformContext.getValue());
        }catch (Exception e){
            logger.error("微信支付回调验证出错", e);
            return new WechatNotifyResponse("FAIL", "ok");
        }
        return new WechatNotifyResponse("SUCCESS", "ok");
    }

}
