package com.kym.miniapp.controller;

import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson2.JSONObject;
import com.kym.common.R;
import com.kym.common.annotation.ApiLog;
import com.kym.service.wechat.WxPayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * @author skyline
 * @description
 * @date 2023-07-22 20:36
 */
@Controller
@RequestMapping("/payment")
public class PaymentController {
    private final WxPayService wxPayService;
    private Logger logger = LoggerFactory.getLogger(PaymentController.class);

    public PaymentController(WxPayService wxPayService) {
        this.wxPayService = wxPayService;
    }

    @ApiLog("微信支付")
    @PostMapping("/wxPay")
    @ResponseBody
    R prepay(@RequestBody JSONObject params) {
        return R.success(wxPayService.wxPay(params));
    }

    @ApiLog(value = "微信回调", ignoreParams = true)
    @SneakyThrows
    @PostMapping("/notify")
    String notify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/xml");
        Map<String, String> result = new HashMap<>();
        try {
            wxPayService.wxNotify(request);
            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");
        } catch (Exception e) {
            result.put("return_code", "FAIL");
            result.put("return_msg", e.getMessage());
        }
        String resp = XmlUtil.mapToXmlStr(result);
        logger.info("wxPay notify result>>>:{}", resp);
        return resp;
    }


    @ApiLog("用户申请退款")
    @GetMapping("/wxApplyRefund")
    @ResponseBody
    R wxAppRefund() {
        wxPayService.applyWxRefund();
        return R.success();
    }

    @ApiLog(value = "微信退款回调", ignoreParams = true)
    @PostMapping("/refundNotify")
    String refundNotify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/xml");
        Map<String, String> result = new HashMap<>();
        try {
            wxPayService.wxRefundNotify(request);
            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");
        } catch (Exception e) {
            result.put("return_code", "FAIL");
            result.put("return_msg", e.getMessage());
        }
        String resp = XmlUtil.mapToXmlStr(result);
        logger.info("wxRefund notify result>>>:{}", resp);
        return resp;
    }
}
