package com.ruoyi.common.pay.ali.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.request.AlipayFundTransMultistepTransferRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransMultistepTransferResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.ruoyi.common.auth.ali.AliConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.pay.BatchTransferAble;
import com.ruoyi.common.utils.ServiceUtil;
import com.wechat.pay.java.service.transferbatch.model.TransferBatchEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.datatransfer.Transferable;
import java.util.ArrayList;
import java.util.List;

/**
 * 支付宝转账API
 * @author wjh
 * 2024/12/11
 */
@Service
@Slf4j
public class AliTransferService {

    @Autowired
    private AliConfig aliConfig;

    @Autowired
    private AlipayClient alipayClient;

    /**
     * 多笔转账
     */
    public boolean batchTransfer(BatchTransferAble batchTransferAble) {

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

        // 设置外部单号
        model.setOutBizNo(batchTransferAble.transferOutBatchNo());

        // 设置产品码：BATCH_API_NO_PWD 批量无密
        model.setProductCode("BATCH_API_NO_PWD");

        // 设置场景码:MULTI_STEP_TRANSFER 多步转账
        model.setBizScene("MULTI_STEP_TRANSFER");

        // 设置总金额（元）
        model.setTotalAmount(batchTransferAble.transferTotalYuan().toString());

        // 设置总数量
        List<MultiStepTransOrderDetailRequest> detailList = batchTransferAble.aliTransferDetailList();
        model.setTotalCount(String.valueOf(detailList.size()));

        // 设置备注
        model.setRemark(batchTransferAble.transferBatchRemark());

        // 设置多步转账明细
        model.setOrderDetails(detailList);

        // TODO 批量设置转账人（官方）
        MultiStepTransferParticipant payerInfo = new MultiStepTransferParticipant();
        payerInfo.setIdentity("chuangtewulian@sina.com");
        payerInfo.setName("福鼎创特物联科技有限公司");
        payerInfo.setIdentityType("ALIPAY_USER_ID");
        for (MultiStepTransOrderDetailRequest detail : detailList) {
            detail.setPayerInfo(payerInfo);
        }

        request.setBizModel(model);
        request.setNotifyUrl(aliConfig.getTransferNotifyUrl());

        try {
            AlipayFundTransMultistepTransferResponse response = alipayClient.certificateExecute(request);
            log.info("转账结果：{}", response.getBody());
            ServiceUtil.assertion(!response.isSuccess(), response.getMsg());
            return true;
        } catch (Exception e) {
            throw new ServiceException("批量转账到支付宝账户失败：" + e.getMessage());
        }
    }

    public boolean transfer(BatchTransferAble batchTransferAble) {

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

        List<MultiStepTransOrderDetailRequest> detailList = batchTransferAble.aliTransferDetailList();
        ServiceUtil.assertion(detailList.size() > 1, "当前接口仅适用于单笔转账");
        MultiStepTransOrderDetailRequest detail = detailList.get(0);

        // 设置商家侧唯一订单号
        model.setOutBizNo(detail.getOutBizNo());

        // 设置订单总金额
        model.setTransAmount(detail.getTransAmount());

        // 设置描述特定的业务场景
        model.setBizScene("DIRECT_TRANSFER");

        // 设置业务产品码
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");

        // 设置转账业务的标题
        model.setOrderTitle(detail.getOrderTitle());

        // 设置收款方信息
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity(detail.getPayeeInfo().getIdentity());
        payeeInfo.setName(detail.getPayeeInfo().getName());
        payeeInfo.setIdentityType(detail.getPayeeInfo().getIdentityType());
        model.setPayeeInfo(payeeInfo);

        // 设置业务备注
        model.setRemark(detail.getRemark());

        request.setBizModel(model);
        request.setNotifyUrl(aliConfig.getTransferNotifyUrl());

        try {
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            ServiceUtil.assertion(!response.isSuccess(), response.getMsg());
            return true;
        } catch (Exception e) {
            throw new ServiceException("转账到支付宝账户失败：" + e.getMessage());
        }
    }

    public AlipayFundTransCommonQueryResponse getTransferBatchByOutNo(String outTradeNo) {
        // 构造请求参数以调用接口
        AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
        AlipayFundTransCommonQueryModel model = new AlipayFundTransCommonQueryModel();

        // 设置销售产品码
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");

        // 设置描述特定的业务场景
        model.setBizScene("DIRECT_TRANSFER");

        // 设置商户转账唯一订单号
        model.setOutBizNo(outTradeNo);

        request.setBizModel(model);

        try {
            AlipayFundTransCommonQueryResponse response = alipayClient.certificateExecute(request);
            ServiceUtil.assertion(!response.isSuccess(), response.getMsg());
            return response;
        } catch (Exception e) {
            log.error("查询支付宝转账单{}失败：{}", outTradeNo, e.getMessage());
            return null;
        }
    }
}
