package com.payment_system.service;

import com.alibaba.fastjson.JSON;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayFundAuthOrderAppFreezeModel;
import com.alipay.api.request.AlipayFundAuthOperationDetailQueryRequest;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.request.AlipayFundAuthOrderUnfreezeRequest;
import com.alipay.api.request.AlipayTradePayRequest;
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.FreezeOrder;
import com.payment_system.entity.TradeOrder;
import com.payment_system.mapper.OrderMapper;
import com.payment_system.utils.OrderNoGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    private final String appId="9021000151640854";
    private final String appPrivateKey="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDPRTNxf1Q22YBk4zX/oJjeoGDohiZn8pKwlr9cNQx2Ip4TJtXjloctaTk3daGSJ0+xj7qGv4ueqBmDzbIdwD30soYza+Ds6QwGZitcpBcAyIUEUd7zl6ztwsw9qXe3w/KHz5eial5/kOqmXcjbxFvMcFvMdlJASY94jT22k2+cHDPKK/2ZxPx9HS6h83bsxqyWGcB/CxxJOuq0sONvKabmViSR7RfYIEDZonH09Y9pXGKz8SCwiwt/2OjW95zakd8J6OGyJQ2tCkqIHHwOOs4ceomOtZltgCLN9EWXXHEWjhCvT/osi+lTaRs7LUz6VUVY2oyQtMJBePveAvQrJemRAgMBAAECggEAPVVL6Lz17Zkk/jWh5/fc5JvusT/pI39LWwfwrldgTaDmx+IJDuSfMZfef4PGgNozIebXGkKaDSPPEQqQN2+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i2jWJfj3UDVy3NUkYDbqwcPaEhMmGSgZ0NuwpYfI4hbWWfmVdIDK8MP+UBz3A==";
    private final String alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvouqsCn75/KGaf7ZSXR+RCxF6J+FSnMggd7JSyH32/xsdvHsa1GdmQcq9r4YFCy//UhYvxS/Gu0CXNdKFl16Kjqq63dlE6BgiOR2aNxwt5DZfKuF0Vyj9Lw8VC6CFA7F5TsA7bznEQP7M+V2MGO9KxuEpx10jrvtrCOaqU/s4cBmjCpVX6dvGq+aI9nYw3Rs65BwrvYwMXidkPA35AGczwXT2VgTGNuoTQqtAYh0C27eQz1R1wdg8owbPwh+tc/jJeh+fj/Zn9ztOHn48a0V5kic9B9qxPDpjfkiEJBseYfaEbWeoLwN3JGc6raxJh47MooLmYKMX8bJRMT8SNJABwIDAQAB";
    private final String gatewayUrl="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String charset="UTF-8";
    private final String signType="RSA2";
    private final String format="json";

    public String freeze(AliFreeze aliFreeze) throws AlipayApiException{
        String orderNo = OrderNoGenerator.generateBase();
        String requestNo = OrderNoGenerator.generateBase();
        // 创建预授权资金冻结订单并赋值
        FreezeOrder freezeOrder = new FreezeOrder();
        freezeOrder.setUserId(aliFreeze.getId());
        freezeOrder.setTradeNumber(orderNo);
        freezeOrder.setAmount(aliFreeze.getAmount());
        freezeOrder.setCreateTime(LocalDateTime.now());
        orderMapper.saveFeezeOrder(freezeOrder);
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,appId,appPrivateKey,format,charset,alipayPublicKey,signType);
        AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
        AlipayFundAuthOrderAppFreezeModel model = new AlipayFundAuthOrderAppFreezeModel();
        request.setNotifyUrl("http://c6ce8ea3.natappfree.cc/alipay/freezeNotify");
        //设置请求参数
        model.setOutOrderNo(orderNo);
        model.setOutRequestNo(requestNo); // 注意确保流水号唯一性
        model.setOrderTitle("资金预授权冻结");
        model.setAmount(String.format("%.2f", aliFreeze.getAmount()));
        model.setProductCode("PRE_AUTH_ONLINE"); // 使用正确的产品码
        model.setPayeeUserId("2088721076638857");

        request.setBizModel(model);

        // 向支付宝发起请求，并获取请求结果
        String result = alipayClient.sdkExecute(request).getBody();
        return result;
    }

    public AlipayTradePayResponse pay(AliFreeze aliPay) throws AlipayApiException{
        String tradeNo = OrderNoGenerator.generateBase();
        String authNo = orderMapper.select1(aliPay.getId()); //获取支付宝授权订单号

        // 创建交易订单并赋值
        TradeOrder tradeOrder = new TradeOrder();
        tradeOrder.setUserId(aliPay.getId());
        tradeOrder.setTradeNumber(tradeNo);
        tradeOrder.setAmount(aliPay.getAmount());
        tradeOrder.setCreateTime(LocalDateTime.now());
        orderMapper.saveTradeOrder(tradeOrder);

        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,appId,appPrivateKey,format,charset,alipayPublicKey,signType);
        // 设置请求参数
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        request.setNotifyUrl("http://c6ce8ea3.natappfree.cc/alipay/payNotify");
        Map map =new HashMap();
        map.put("out_trade_no",tradeNo);
        map.put("total_amount",String.format("%.2f", aliPay.getAmount()));
        map.put("subject",aliPay.getId()+"号用户的订单");
        map.put("product_code","PREAUTH_PAY");
        map.put("auth_no",authNo);
        map.put("auth_confirm_mode","NOT_COMPLETE");
        request.setBizContent(JSON.toJSONString(map));
        // 完成冻结转支付并返回AlipayTradePayResponse对象
        AlipayTradePayResponse response =alipayClient.execute(request);
        return response;
    }

    public AlipayFundAuthOperationDetailQueryResponse query(long userId) throws AlipayApiException{
        String authNo = orderMapper.select1(userId); //获取支付宝授权订单号
        String operationNo = orderMapper.select2(userId); //获取支付宝授权资金操作流水号

        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,appId,appPrivateKey,format,charset,alipayPublicKey,signType);
        // 设置请求参数
        AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
        Map map =new HashMap();
        map.put("auth_no",authNo);
        map.put("operation_id",operationNo);
        map.put("operation_type","FREEZE");
        request.setBizContent(JSON.toJSONString(map));
        AlipayFundAuthOperationDetailQueryResponse response = alipayClient.execute(request);
        return response;
    }

    public AlipayFundAuthOrderUnfreezeResponse unfreeze(AliFreeze aliUnfreeze) throws AlipayApiException{
        String authNo = orderMapper.select1(aliUnfreeze.getId()); //获取支付宝授权订单号
        String outNo = OrderNoGenerator.generate25Digit();
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,appId,appPrivateKey,format,charset,alipayPublicKey,signType);
        // 设置请求参数
        AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
        Map map =new HashMap();
        map.put("auth_no",authNo);
        map.put("out_request_no",outNo);
        map.put("amount",aliUnfreeze.getAmount());
        map.put("remark","解冻"+aliUnfreeze.getAmount()+"元");
        request.setBizContent(JSON.toJSONString(map));
        AlipayFundAuthOrderUnfreezeResponse response = alipayClient.execute(request);
        return response;
    }

    public void updateFreezeOrder(short status,String authNumber,String operationNumber,String tradeNumber){
        orderMapper.updateFeezeOrder(status,authNumber,operationNumber,tradeNumber);
    }

    public void updateTradeOrder(short status,String tradeNumber){
        orderMapper.updateTradeOrder(status,tradeNumber);
    }

    public boolean judge(long userId){
        FreezeOrder f1 = orderMapper.findById(userId);
        if(f1 != null){
            return true;
        }else{
            return false;
        }
    }
    //因为个人账户无法申请预授权支付，所以支付改为计数
    public void payMoney(AliFreeze alipay){
        String tradeNo = OrderNoGenerator.generateBase();//生成订单号
        // 创建交易订单并赋值
        TradeOrder tradeOrder = new TradeOrder();
        tradeOrder.setUserId(alipay.getId());
        tradeOrder.setTradeNumber(tradeNo);
        tradeOrder.setAmount(alipay.getAmount());
        tradeOrder.setCreateTime(LocalDateTime.now());
        tradeOrder.setStatus((short)1);
        //冻结资金扣款
        orderMapper.updateAmount(alipay.getAmount(),alipay.getId());
        //删除金额归0的冻结订单
        orderMapper.delete(alipay.getId());
        //赋值完成订单后的冻结金额
        if(orderMapper.getBalance(alipay.getId()) != null) {
            tradeOrder.setBalance(orderMapper.getBalance(alipay.getId()));
        }else{
            tradeOrder.setBalance(BigDecimal.ZERO);
        }
        orderMapper.saveTradeOrder2(tradeOrder);
    }
    //这里同上
    public void unfreezeMoney(AliFreeze aliUnfreeze){
        orderMapper.updateAmount(aliUnfreeze.getAmount(),aliUnfreeze.getId());
        orderMapper.delete(aliUnfreeze.getId());
    }

    public BigDecimal queryBalance(long userId){
        BigDecimal balance = orderMapper.getBalance(userId);
        return balance;
    }

    public List<TradeOrder> getTrade(long userId){
        List<TradeOrder> tradeOrderList = orderMapper.findTrade(userId);
        return tradeOrderList;
    }
}

