package com.izouma.nineth.web;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.config.HmPayProperties;
import com.izouma.nineth.enums.PayMethod;
import com.izouma.nineth.event.OrderNotifyEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hmpay")
@Slf4j
@AllArgsConstructor
public class HmPayController extends BaseController {
    private final HmPayProperties    hmPayProperties;
    private final RocketMQTemplate   rocketMQTemplate;
    private final GeneralProperties  generalProperties;

    @GetMapping("/notify/{type}/{id}")
    public String orderNotify(@PathVariable String type, @PathVariable Long id, HttpServletRequest req) throws AlipayApiException {
        log.info("回调type={}, orderId={}, 参数={}", type, id, JSON.toJSONString(req.getParameterMap(), true));
        Map<String, String> params = new HashMap<>();
        req.getParameterMap().forEach((k, v) -> {
            if (v != null && v.length > 0 && StringUtils.isNotEmpty(v[0])) {
                params.put(k, v[0]);
            }
        });
        String sign = params.get("sign");
        params.remove("sign");
        String signStr = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
        boolean verify = AlipaySignature.verify(signStr, sign, hmPayProperties.getHmPublicKey(), "UTF-8", "RSA");
        log.info("签名校验: {}", verify);
        if ("SUCCESS".equals(params.get("trade_status"))) {
            String plat_trx_no = params.get("plat_trx_no");
            switch (type) {
                case "order":
                    rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                            new OrderNotifyEvent(id, PayMethod.HMPAY, plat_trx_no, System.currentTimeMillis()));
                    break;
                case "gift":
                    rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                            new OrderNotifyEvent(id, PayMethod.SANDPAY, plat_trx_no,
                                    System.currentTimeMillis(), OrderNotifyEvent.TYPE_GIFT_ORDER));
                    break;
                case "mintOrder":
                    rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                            new OrderNotifyEvent(id, PayMethod.SANDPAY, plat_trx_no,
                                    System.currentTimeMillis(), OrderNotifyEvent.TYPE_MINT_ORDER));
                    break;
                case "recharge":
                    rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                            new OrderNotifyEvent(id, PayMethod.SANDPAY, plat_trx_no,
                                    System.currentTimeMillis(), OrderNotifyEvent.TYPE_RECHARGE));
                    break;
                case "auctionOrder":
                    rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                            new OrderNotifyEvent(id, PayMethod.SANDPAY, plat_trx_no,
                                    System.currentTimeMillis(), OrderNotifyEvent.TYPE_AUCTION_ORDER));
                    break;
            }
        }
        return "SUCCESS";
    }
}
