package com.fzm.mall.server.admin.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.admin.pay.service.WxPayService;
import com.fzm.mall.server.admin.util.WxPayUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author wulixian
 * @since 2021/10/18
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WxPayController {

    private final WxPayService wxPayService;
    private final WxPayUtil wxPayUtil;

    @ApiOperation(value = "退款结果通知")
    @PostMapping("/wxpay/refund/return")
    public String wxPayRefundReturn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("微信退款通知回调");
        String notifySign = "%s\n%s\n%s\n";
        Enumeration<String> headerNames = request.getHeaderNames();
        String body = getBodytxt(request);//获取body数据,需要自实现
        log.info(body);
        JSONObject head = new JSONObject();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            head.put(key, value);
        }
        log.info("微信通知头部" + head);
        log.info("微信通知body" + body);
        wxPayUtil.verify(head.getString("wechatpay-serial"), String.format(notifySign, head.getString("wechatpay-timestamp"), head.getString("wechatpay-nonce"), body), head.getString("wechatpay-signature"));
        JSONObject notify = wxPayUtil.refundNotify(JSONObject.parseObject(body));
        log.info("notify:" + notify.toString());
        String outBizNo = notify.getString("transaction_id");
        String eventType = notify.getString("event_type");
        String summary = notify.getString("summary");
        wxPayService.wxPayRefundReturn(outBizNo, eventType, summary);
        JSONObject result = new JSONObject();
        result.put("code", "SUCCESS");
        result.put("message", "成功");
        return result.toString();
    }

    String getBodytxt(HttpServletRequest request) throws IOException {
        BufferedReader br = request.getReader();
        String str, wholeStr = "";
        while ((str = br.readLine()) != null) {
            wholeStr += str;
        }
        return wholeStr;
    }
}
