package com.payment_system.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import com.alipay.api.response.AlipayFundAuthOrderUnfreezeResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.payment_system.entity.AliFreeze;
import com.payment_system.entity.TradeOrder;
import com.payment_system.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class OrderController {
    @Autowired
    private OrderService orderService;

    private final String alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvouqsCn75/KGaf7ZSXR+RCxF6J+FSnMggd7JSyH32/xsdvHsa1GdmQcq9r4YFCy//UhYvxS/Gu0CXNdKFl16Kjqq63dlE6BgiOR2aNxwt5DZfKuF0Vyj9Lw8VC6CFA7F5TsA7bznEQP7M+V2MGO9KxuEpx10jrvtrCOaqU/s4cBmjCpVX6dvGq+aI9nYw3Rs65BwrvYwMXidkPA35AGczwXT2VgTGNuoTQqtAYh0C27eQz1R1wdg8owbPwh+tc/jJeh+fj/Zn9ztOHn48a0V5kic9B9qxPDpjfkiEJBseYfaEbWeoLwN3JGc6raxJh47MooLmYKMX8bJRMT8SNJABwIDAQAB";
    private final String charset="UTF-8";
    private final String signType="RSA2";

    //冻结资金请求
    @PostMapping("/freeze")
    public String freeze(@RequestBody AliFreeze aliFreeze) throws AlipayApiException{
        String orderStr= orderService.freeze(aliFreeze);
        return orderStr;
    }
    //冻结资金转支付请求
    @PostMapping("/pay")
    public AlipayTradePayResponse pay(@RequestBody AliFreeze aliPay) throws AlipayApiException{
        AlipayTradePayResponse response = orderService.pay(aliPay);
        return response;
    }
    //冻结资金查询请求
    @GetMapping("/query/{userId}")
    public String query(@PathVariable long userId) throws AlipayApiException{
        AlipayFundAuthOperationDetailQueryResponse response = orderService.query(userId);
        String amount = response.getRestAmount();
        return amount; //返回冻结资金余额
    }

    //资金解冻请求
    @PostMapping("/unfreeze")
    public String unfeeze(@RequestBody AliFreeze aliUnfreeze) throws AlipayApiException{
        AlipayFundAuthOrderUnfreezeResponse response = orderService.unfreeze(aliUnfreeze);
        String amount = response.getAmount(); //获取解冻金额
        return amount; //返回解冻金额，app端显示解冻成功，已解冻amount元
    }

    //查询冻结情况
    @GetMapping("/{userId}")
    public boolean judge(@PathVariable long userId){
        boolean result = orderService.judge(userId);
        return result;
    }

    //资金冻结接口异步请求
    @PostMapping("/freezeNotify")
    public String feezeNotify(HttpServletRequest request) throws Exception{
        // 将请求参数存储到map集合中
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()){
            params.put(name, request.getParameter(name));
        }

        String authNumber = params.get("auth_no"); //支付宝订单号
        String operationNumber = params.get("operation_id"); //支付宝的资金操作流水号
        String tradeNumber = params.get("out_order_no"); //商家订单号
        String status = params.get("status"); //授权状态
        // 验签
//        String sign = params.get("sign");
//        String content = AlipaySignature.getSignCheckContentV1(params);
//        boolean checkSignature = AlipaySignature.rsa256CheckContent(content,sign,aliConfig.getAlipayPublicKey(),aliConfig.getCharset());
        boolean checkSignature = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
        if(checkSignature && status.equals("SUCCESS")){
                orderService.updateFreezeOrder((short)1,authNumber,operationNumber,tradeNumber); //更改授权订单信息
        }
        return "success";
    }
    //支付接口异步请求
    @PostMapping("/payNotify")
    public String payNotify(HttpServletRequest request) throws Exception{
        // 将请求参数存储到map集合中
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()){
            params.put(name, request.getParameter(name));
        }

        String tradeNumber = params.get("out_trade_no"); //商户订单号
        String status = params.get("trade_status"); //交易状态
        //验签
        boolean checkSignature = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
        if(checkSignature && status.equals("TRADE_SUCCESS")){
                orderService.updateTradeOrder((short)1,tradeNumber); //根据商户订单号来修改支付状态
        }
        return "success";
    }

    //不使用支付宝接口的模拟支付
    @PostMapping("/payMoney")
    public void payMoney(@RequestBody AliFreeze alipay){
        orderService.payMoney(alipay);
    }
    //解冻同上
    @PostMapping("/unfreezeMoney")
    public void unfreezeMoney(@RequestBody AliFreeze aliUnfreeze){
        orderService.unfreezeMoney(aliUnfreeze);
    }
    //查询冻结资金余额
    @GetMapping("/get/{userId}")
    public BigDecimal queryBalance(@PathVariable long userId){
        BigDecimal balance = orderService.queryBalance(userId);
        return balance;
    }
    //查询订单信息
    @GetMapping("/search/{userId}")
    public List<TradeOrder> getTrade(@PathVariable long userId){
        List<TradeOrder> tradeOrderList = orderService.getTrade(userId);

        return tradeOrderList; // 状态码200，响应体为trade对象
    }
}

