package com.bonus.core.pay.channel.ali.controller;

import cn.hutool.core.util.ObjectUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.core.pay.channel.ali.extension.AliPayExtension;
import com.bonus.core.pay.common.service.PayTradeService;
import com.bonus.core.pay.common.vo.MobileNotifyVO;
import com.bonus.i18n.I18n;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping({"/api/v2/pay"})
public class AlipayController {
   private static final Logger log = LoggerFactory.getLogger(AlipayController.class);
   @Autowired
   @Lazy
   private PayTradeService payTradeService;
   @Autowired
   @Lazy
   private AliPayExtension aliPayExtension;

   @PostMapping({"/ali/notify"})
   public void aliNotify(HttpServletRequest request, HttpServletResponse response) {
      Map<String, String> params = new HashMap();
      Map<String, String[]> parameterMap = request.getParameterMap();
      Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
      Iterator var6 = entries.iterator();

      while(var6.hasNext()) {
         Map.Entry<String, String[]> entry = (Map.Entry)var6.next();
         String name = (String)entry.getKey();
         String[] values = (String[])entry.getValue();
         String valueStr = String.join(",", values);
         params.put(name, valueStr);
      }

      try {
         MobileNotifyVO mobileNotifyVO = this.aliPayExtension.aliNotifyHandler(params);
         if (ObjectUtil.isNotNull(mobileNotifyVO)) {
            this.payTradeService.payResultHandler(mobileNotifyVO);
            response.getWriter().write("success");
         }

      } catch (Exception var11) {
         log.error("[支付宝app支付]回调处理异常：", var11);
         throw new ServiceException(I18n.getMessage("pay.alipay-callback-exception", new Object[0]));
      }
   }
}
