package com.bonus.canteen.core.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bonus.canteen.core.pay.util.AlipayConfig;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
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.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Api(tags = "支付同步通知")
@RestController
@RequestMapping("/alipay/return")
public class ReturnCotroller {
    @RequestMapping("getreturn")
    public void getNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        Iterator<String> iter = requestParams.keySet().iterator();
        while(iter.hasNext()) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean singVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        if (singVerified) {
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //商户订单号
            String total_amount = request.getParameter("total_amount");
            //支付宝交易号
            String trade_no = request.getParameter("trade_no");
            //交易状态
            String trade_status = request.getParameter("trade_status");
            out.println("return_values: " + "<br>trade_no:" + trade_no + "<br>out_trade_no:" + out_trade_no +
                    "<br>total_amount:" + total_amount + "<br>trade_status" + trade_status);
        } else {
            out.println("fail");
            //调试用，写文本函数记录程序运行情况是否正常
            //String reason = AlipaySignature.getSignCheckContentV1(params);
            //log.info(reason);
        }
        response.getWriter().flush();
    }
}
