package com.zcloud.modules.goods.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.fasterxml.jackson.core.type.TypeReference;
//import com.wechat.pay.java.core.RSAAutoCertificateConfig;
//import com.wechat.pay.java.core.notification.NotificationConfig;
//import com.wechat.pay.java.core.notification.NotificationParser;
//import com.wechat.pay.java.service.partnerpayments.h5.model.Transaction;
//import com.wechat.pay.java.service.partnerpayments.model.PromotionDetail;
import com.zcloud.common.alipay.AliPayBean;
import com.zcloud.common.alipay.AliPayUtil;
import com.zcloud.common.annotation.SysLog;
import com.zcloud.common.utils.OrderUtils;
import com.zcloud.common.utils.R;
import com.zcloud.common.utils.RequestMap;
import com.zcloud.common.wxpay.WxPayBean;
import com.zcloud.common.wxpay.WxPayUtil;
import com.zcloud.modules.sys.service.ShiroService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fangjiakai
 * @date 2023/12/12 17:16
 */
@Api(tags = "支付")
@RestController
@RequestMapping("pay")
public class PayController {
    @Resource
    private AliPayBean aliPayBean;
    @Resource
    private WxPayBean wxPayBean;
    @Resource
    private AliPayUtil aliPayUtil;
    @Resource
    private WxPayUtil wxPayUtil;
    @Autowired
    private ShiroService shiroService;

    @ApiOperation("支付-支付宝扫码")
    @SysLog("支付-支付宝扫码")
    @RequestMapping("/payFor")
    @ResponseBody
    public void payFor(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> params;
        Map<String, Object> resultData = new HashMap<>();
        params = RequestMap.getParameterMap(request);
        String userId = shiroService.queryByToken(params.get("token")).getUserId();
        //TODO 判断验证码是否过期
        //存储当前时间戳
        if (System.currentTimeMillis() - Integer.parseInt(params.get("expire")) > 60 * 1000) {
            response.sendError(HttpServletResponse.SC_OK, "操作超时");
            return;
        }
        //订单编号
        String orderNumber = OrderUtils.generateOrderNumber(userId);

        String userAgent = request.getHeader("User-Agent").toLowerCase();
        String result;
        if ("zhifubao".equals(params.get("paymentMethod"))) {
            result = aliPayUtil.pay(orderNumber, params.get("totalAmount"), params.get("subject"), userAgent,"/pay/alipay/notify");
        } else if ("weixin".equals(params.get("paymentMethod")))  {
            String bodyAsString = wxPayUtil.pay(System.currentTimeMillis() + "", params.get("totalAmount"), params.get("subject"), userAgent);
            result = bodyAsString;
            Map<String, String> resultMap = new com.fasterxml.jackson.databind.ObjectMapper().readValue(bodyAsString, new TypeReference<Map<String, String>>() {
            });
            resultData.put("wxBean", "wxPayBean");
            resultData.put("prepay_id", resultMap.get("prepay_id"));
            resultData.put("result", bodyAsString);
        } else {
            response.sendError(HttpServletResponse.SC_OK,"请使用微信或支付宝扫码二维码");
            return;
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation("支付-支付宝回调")
    @SysLog("支付-支付宝回调")
    @RequestMapping("/alipay/notify")
    @ResponseBody
    public void aliNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("type=text/html;charset=UTF-8");
        Map<String, String> params;
        try {
            params = RequestMap.getParameterMap(request);
            if (!AlipaySignature.rsaCheckV1(params, aliPayBean.getAlipayPublicKey(), "utf-8", "RSA2")) {
                System.out.println("验签失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if(params!=null) {
//            asyncPayDealTaskService.dealAliPayAsynchronous(params, aliPayProperties.getAli_pid());
//        }
//        if(!Boolean.valueOf(asynchronousResult.get(R.SUCCESS_TAG).toString())) {
        response.getWriter().write("success");
        response.getWriter().close();
//        }else {
//            response.getWriter().write("failure");
//            response.getWriter().close();
//        }
    }

   /* @ApiOperation("微信-微信回调")
    @SysLog("支付-微信回调")
    @RequestMapping("/wxpay/notify")
    @ResponseBody
    public R wxNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //步骤一：验证签名
        String WechatpaySignature = request.getHeader("Wechatpay-Signature");
        String WechatpaySerial = request.getHeader("Wechatpay-Serial");
        String WechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String WechatpayTimestamp = request.getHeader("Wechatpay-Timestamp");
        String WechatpaySignatureType = request.getHeader("Wechatpay-Signature-Type");
        BufferedReader reader = request.getReader();
        StringBuilder builder = new StringBuilder();
        String line = reader.readLine();
        while(line != null){
            builder.append(line);
            line = reader.readLine();
        }
        reader.close();
        String requestBody = builder.toString();

        com.wechat.pay.java.core.notification.RequestParam requestParam = new com.wechat.pay.java.core.notification.RequestParam.Builder()
                .serialNumber(WechatpaySerial)
                .nonce(WechatpayNonce)
                .signature(WechatpaySignature)
                .timestamp(WechatpayTimestamp)
                .signType(WechatpaySignatureType)
                .body(requestBody)
                .build();

        NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId("merchantId")
                .privateKeyFromPath("privateKeyPath")
                .merchantSerialNumber("merchantSerialNumber")
                .apiV3Key("apiV3Key")
                .build();
        //步骤二：参数解密......

        NotificationParser parser = new NotificationParser(config);
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            List<PromotionDetail> promotionDetail = transaction.getPromotionDetail();
            //支付结果处理
            //TODO
            Integer amount = promotionDetail.get(0).getAmount();
        } catch (Exception e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            return R.error(401, String.valueOf(HttpStatus.UNAUTHORIZED)) ;
        }
        if(false){
            return R.error(500, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
        }
        return R.ok().put("code","200");

    }*/
}
