package shop.alien.store.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeSettleConfirmModel;
import com.alipay.api.domain.SettleConfirmExtendParams;
import com.alipay.api.domain.SettleDetailInfo;
import com.alipay.api.domain.SettleInfo;
import com.alipay.api.request.AlipayTradeSettleConfirmRequest;
import com.alipay.api.response.AlipayTradeSettleConfirmResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.dto.AlipayTradeSettleConfirmDto;
import shop.alien.store.service.AlipaySettleService;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class AlipaySettleServiceImpl implements AlipaySettleService {

    @Override
    public R<String> tradeSettleConfirm(AlipayTradeSettleConfirmDto request1) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeSettleConfirmRequest request = new AlipayTradeSettleConfirmRequest();
        AlipayTradeSettleConfirmModel model = new AlipayTradeSettleConfirmModel();

        // 设置确认结算请求流水号
        model.setOutRequestNo("3688165032919721921");

        // 设置支付宝交易号
        model.setTradeNo("2026051423001467461454113691");

        // 设置描述结算信息
        SettleInfo settleInfo = new SettleInfo();
        List<SettleDetailInfo> settleDetailInfos = new ArrayList<SettleDetailInfo>();
        SettleDetailInfo settleDetailInfos0 = new SettleDetailInfo();
        settleDetailInfos0.setAmount("0.99");
        settleDetailInfos0.setTransIn("ailien@alienyan.cn");
//        settleDetailInfos0.setSettleEntityType("SecondMerchant");
//        settleDetailInfos0.setSummaryDimension("A0001");
//        settleDetailInfos0.setActualAmount("0.1");
//        settleDetailInfos0.setSettleEntityId("2088xxxxx;ST_0001");
        settleDetailInfos0.setTransInType("email");
        settleDetailInfos.add(settleDetailInfos0);
        settleInfo.setSettleDetailInfos(settleDetailInfos);
        model.setSettleInfo(settleInfo);

        // 设置扩展字段信息
//        SettleConfirmExtendParams extendParams = new SettleConfirmExtendParams();
//        extendParams.setRoyaltyFreeze("true");
//        model.setExtendParams(extendParams);
        // 🔥 核心：直接手动构建 JSON 字符串，amount 是纯数字（无引号）！！！
        String bizContent = "{"
                + "\"out_request_no\":\"3688165032919721921\","
                + "\"trade_no\":\"2026051423001467461454113691\","
                + "\"settle_info\":{"
                + "\"settle_detail_infos\":["
                + "{"
                + "\"trans_in_type\":\"userId\","
                + "\"trans_in\":\"2088480335620690\","
                + "\"settle_dimension_type\":\"USER\","
                + "\"amount\":1.00" // ✅ 纯数字，无引号！！！
                + "}"
                + "]"
                + "}"
                + "}";
        request.setBizContent(bizContent);

//        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradeSettleConfirmResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());

        if (response == null) {
            return R.fail("支付宝返回为空");
        }
        if (response.isSuccess()) {
            return R.data("调用成功", response.getBody());
        }
        return R.fail("调用失败：" + response.getBody());
    }

//    public R<String> tradeSettleConfirm(AlipayTradeSettleConfirmDto request) throws AlipayApiException {
//        if (request == null) {
//            return R.fail("请求体不能为空");
//        }
//        if (StringUtils.isBlank(request.getOutRequestNo())) {
//            return R.fail("out_request_no 不能为空");
//        }
//        if (StringUtils.isBlank(request.getTradeNo())) {
//            return R.fail("trade_no 不能为空");
//        }
//        if (request.getSettleInfo() == null
//                || request.getSettleInfo().getSettleDetailInfos() == null
//                || request.getSettleInfo().getSettleDetailInfos().isEmpty()) {
//            return R.fail("settle_info.settle_detail_infos 不能为空");
//        }
//
//        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
//
//        AlipayTradeSettleConfirmRequest apiRequest = new AlipayTradeSettleConfirmRequest();
//        apiRequest.setBizModel(toModel(request));
//        if (StringUtils.isNotBlank(request.getAppAuthToken())) {
//            apiRequest.putOtherTextParam("app_auth_token", request.getAppAuthToken().trim());
//        }
//
//        log.info("alipay.trade.settle.confirm outRequestNo={}, tradeNo={}",
//                request.getOutRequestNo(), request.getTradeNo());
//        AlipayTradeSettleConfirmResponse response = alipayClient.execute(apiRequest);
//        if (response == null) {
//            return R.fail("支付宝返回为空");
//        }
//        if (response.isSuccess()) {
//            return R.data("调用成功", response.getBody());
//        }
//        return R.fail("调用失败：" + response.getBody());
//    }

//    private static AlipayTradeSettleConfirmModel toModel(AlipayTradeSettleConfirmDto request) {
//        AlipayTradeSettleConfirmModel model = new AlipayTradeSettleConfirmModel();
//        model.setOutRequestNo(request.getOutRequestNo().trim());
//        model.setTradeNo(request.getTradeNo().trim());
//
//        SettleInfo settleInfo = new SettleInfo();
//        List<SettleDetailInfo> details = new ArrayList<>();
//        for (AlipayTradeSettleConfirmDto.SettleDetailInfo src : request.getSettleInfo().getSettleDetailInfos()) {
//            if (src == null) {
//                continue;
//            }
//            SettleDetailInfo detail = new SettleDetailInfo();
//            detail.setAmount(src.getAmount());
//            detail.setTransIn(src.getTransIn());
//            detail.setSettleEntityType(src.getSettleEntityType());
//            detail.setSummaryDimension(src.getSummaryDimension());
//            detail.setActualAmount(src.getActualAmount());
//            detail.setSettleEntityId(src.getSettleEntityId());
//            detail.setTransInType(src.getTransInType());
//            details.add(detail);
//        }
//        settleInfo.setSettleDetailInfos(details);
//        model.setSettleInfo(settleInfo);
//
//        if (request.getExtendParams() != null) {
//            SettleConfirmExtendParams extendParams = new SettleConfirmExtendParams();
//            extendParams.setRoyaltyFreeze(request.getExtendParams().getRoyaltyFreeze());
//            model.setExtendParams(extendParams);
//        }
//        return model;
//    }

    private static AlipayConfig getAlipayConfig() {
        String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBTOvScNrk0mw+WbR6Qtx2+HrPxB5IU/V2HSPGZUTDNiCiSU9UZcuXlo0UNwMksFYR43btk4BHW9OsZETdr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SnmzrOQQQUoErk40vnm9FiP74VwtWaD6llUZ25ohNeIi9yvHU5x/vAoGAdU2d1JOq85LHtsO+i9+8pyNnAsJ1YqTDtI5CtK2lqKvewswGIrlxOvi//AchVN3ExZmP0QDyfp31BhAs/T8iOl+Vqf7PzVjX+Eszch5aqwlzadmv3ZepnnamCGVE+hAsmkz0R6tebPjqYC7Ds/HbssQFLc4EyVBD5fwE5ZuR+OMCgYAvGHUYpi0dY9uMHXzL721tIopiwUfKCgLAn3yhSH3p7644NxHBqLLaBLVT2q7JAZQUaZUvXlwiyxU1zvo0xmvcbnB/Vd2qp8KbEUkvHyIYVJkM6Fn+9xBosorcrHv+7B2V1XR9WQcXvppxbN/8farWGuAA0anBD+UGrxd8B0/hHg==";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnxevClLpYc6c8A9lwmnftPO2BeU+X6aZ/+b/n1Cvq096VJKiHmqcsRgRbrnSlmPDHRrQpDti4en2Ys0L2lx7CObIr/2xP/jJVwjIO1iWHUj/w/NAbjv7dLW/FFY4SeNp8rU+hlgGgviyUxzonfNfr3v+o8grFqQq27/hiZJAofsQRMQu1dEQqoKdJj7eQLkTstiK5miJMyQ+Y3tLztrEUMBz/zRgaCEfGqmFmRZ2diy2X+1dGaX6H4+0QJ2u50eY2QTBkNuvREGbAn6/lttAgvg/+CywPYKGeC4xOfnl5wP8iA1QXYbXrVJRkZjU097nyOmSNhLy9KvJH2BNpojS1QIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId("2021005196608960");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }
}
