package com.fdkankan.platform.order.controller.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.fdkankan.common.controller.BaseController;
import com.fdkankan.pay.alipay.AlipayDefaultConfig;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.user.factory.PayFactory;
import com.fdkankan.platform.user.strategy.OrderStrategyFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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


/**
 * 支付中心-支付宝支付模块
 */
@Log4j2
@RestController
@RequestMapping("/service/platform/order/pay")
public class OrderAlipayController extends BaseController {
    @Autowired
    private AlipayDefaultConfig alipayDefaultConfig;
    @Autowired
    private OrderStrategyFactory orderStrategyFactory;
    @Autowired
    private PayFactory payFactory;

    /**
     * 支付宝付款
     * orderId      订单id
     * orderType    订单类型，0购买相机，1点数重置，2扩容，3商业版，4增值服务，5场景下载
     * spaceId      0表示国内订单，1表示国外订单
     */
    @RequestMapping(value = "/alipay", method = RequestMethod.POST)
    public JSONObject alipay(@RequestBody RequestPlaceOrder order) throws Exception {
        return payFactory.scanPay("alipay", order);
    }

    /**
     * 支付宝H5付款
     * orderId          订单id
     * orderType        订单类型，0购买相机，1点数重置，2扩容，3商业版，4增值服务，5场景下载
     * spaceId          0表示国内订单，1表示国外订单
     * @return
     */
    @RequestMapping(value = "/aliMobilePay", method = RequestMethod.POST)
    public JSONObject aliMobilePay(@RequestBody RequestPlaceOrder order) throws Exception {
        return payFactory.h5Pay("alipay", order, null);
    }

    /**
     * 支付宝异步回调
     */
    @RequestMapping(value = "/alipay/async_notify", method = RequestMethod.POST)
    public String async_notify() {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); 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);
        }
        //调用SDK验证签名
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayDefaultConfig.getAlipayPublicKey(), alipayDefaultConfig.getCharset(), alipayDefaultConfig.getSignType());
            if (signVerified) {
                log.info("支付宝回调签名认证成功");
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                //交易body
                String body = new String(request.getParameter("body").getBytes("ISO-8859-1"), "UTF-8");
                log.info("支付宝回调返回body：" + body);
                //付款金额
//                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
                String openid = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"),"UTF-8");
                String orderSn = out_trade_no.split("_")[0];
                if(body.split("_").length == 2){
                    orderSn += "_" + body.split("_")[1];
                }
                if ("TRADE_FINISHED".equals(trade_status)){
                    log.warn("支付宝——交易结束了！" + out_trade_no);
                }else if ("TRADE_SUCCESS".equals(trade_status)){
                    orderStrategyFactory.doHandler(orderSn, trade_no, openid, out_trade_no.split("_")[1], 1);
                }else {
                    log.error("订单号：" + orderSn + "支付宝回调交易状态异常：" + trade_status);
                }
                return "success";
            }else{
                log.warn("支付宝回调签名认证失败，signVerified=false, paramsJson:{}", JSON.toJSONString(params));
                return "failure";
            }
        } catch (Exception e) {
            log.error("支付宝回调签名认证失败,paramsJson:{},errorMsg:{}", JSON.toJSONString(params), e.getMessage());
            return "failure";
        }
    }

}
