package com.jeequan.jeepay.thirdparty.channel.alipay;

import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransCommonQueryModel;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.TransferOrder;
import com.jeequan.jeepay.core.model.openapi.biz.transfer.TransferOrderParam;
import com.jeequan.jeepay.core.model.params.IsvParams;
import com.jeequan.jeepay.core.model.params.alipay.AlipayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.db.entity.TransferSubjectEntity;
import com.jeequan.jeepay.thirdparty.channel.AbstractTransferService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 转账接口： 支付宝官方
 *
 * @author terrfly
 * @date 2021/8/11 14:05
 */
@Slf4j
@Service
public class AlipayTransferService extends AbstractTransferService {

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Override
    public String getIfCode() {
        return CS.IF_CODE.ALIPAY;
    }

    @Override
    public boolean isSupport(String entryType) {

        // 支付宝账户
        if (TransferOrder.ENTRY_ALIPAY_CASH.equals(entryType)) {
            return true;
        }

        return false;
    }

    @Override
    public String preCheck(TransferOrderParam bizRQ, TransferOrder transferOrder) {
        super.preCheck(bizRQ, transferOrder);

        /*
         * 支付宝新版转账接口：不支持服务商模式 （ 不存在 app_auth_token 参数了 ）
         * 旧版文档地址： https://opendocs.alipay.com/open/309/alipay.fund.trans.toaccount.transfer
         * 新版文档地址： https://opendocs.alipay.com/open/02byuo?ref=api&scene=ca56bca529e64125a2786703c6192d41
         */
        if (transferOrder.getMchType() == CS.MCH_TYPE_ISVSUB) {
            return "支付宝子商户暂不支持转账业务";
        }

        return null;
    }

    @Override
    public ChannelRetMsg transfer(TransferOrderParam bizRQ, TransferOrder transferOrder) {

        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        model.setTransAmount(AmountUtil.convertCent2Dollar(transferOrder.getAmount())); //转账金额，单位：元。
        model.setOutBizNo(transferOrder.getTransferId()); //商户转账唯一订单号
        model.setRemark(transferOrder.getTransferDesc()); //转账备注
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");   // 销售产品码。单笔无密转账固定为 TRANS_ACCOUNT_NO_PWD
        model.setBizScene("DIRECT_TRANSFER");           // 业务场景 单笔无密转账固定为 DIRECT_TRANSFER。
        model.setOrderTitle("转账");                     // 转账业务的标题，用于在支付宝用户的账单里显示。
        model.setBusinessParams(transferOrder.getChannelExtra());   // 转账业务请求的扩展参数 {\"payer_show_name_use_alias\":\"xx公司\"}

        Participant accPayeeInfo = new Participant();
        accPayeeInfo.setName(StringUtils.defaultString(transferOrder.getAccountName(), null)); //收款方真实姓名
        accPayeeInfo.setIdentityType("ALIPAY_LOGON_ID");    //ALIPAY_USERID： 支付宝用户ID      ALIPAY_LOGONID:支付宝登录账号
        accPayeeInfo.setIdentity(transferOrder.getAccountNo()); //收款方账户
        model.setPayeeInfo(accPayeeInfo);

        request.setBizModel(model);

        TransferSubjectEntity transferSubjectFq = transferSubjectService.getById(transferOrder.getTransferSubjectIdFq());

        //统一放置 isv接口必传信息
        // 获取支付参数
        AlipayIsvParams isvParams = (AlipayIsvParams) configContextQueryService.queryTransferIsvParams(transferSubjectFq);

        // 服务商信息
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId(isvParams.getPid());

//        if(model instanceof AlipayTradePayModel) {
//            ((AlipayTradePayModel)model).setExtendParams(extendParams);
//        } else if(model instanceof AlipayTradeAppPayModel) {
//            ((AlipayTradeAppPayModel)model).setExtendParams(extendParams);
//        } else if(model instanceof AlipayTradeCreateModel) {
//            ((AlipayTradeCreateModel)model).setExtendParams(extendParams);
//        } else if(model instanceof AlipayTradePagePayModel) {
//            ((AlipayTradePagePayModel)model).setExtendParams(extendParams);
//        } else if(model instanceof AlipayTradePrecreateModel) {
//            ((AlipayTradePrecreateModel)model).setExtendParams(extendParams);
//        } else if(model instanceof AlipayTradeWapPayModel) {
//            ((AlipayTradeWapPayModel)model).setExtendParams(extendParams);
//        }

        request.putOtherTextParam("app_auth_token", isvParams.getAppAuthToken());

        // 调起支付宝接口
        AlipayFundTransUniTransferResponse response;
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        try {
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(isvParams.getConfig());
            response = alipayClient.certificateExecute(request);
            channelRetMsg.setChannelAttach(response.getBody());

            // 调用成功
            if (response.isSuccess()) {
                if ("SUCCESS".equals(response.getStatus())) {
                    channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                    channelRetMsg.setChannelOrderId(response.getOrderId());
                    return channelRetMsg;
                } else if ("FAIL".equals(response.getStatus())) {
                    channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                    channelRetMsg.setChannelErrCode(AlipayKit.appendErrCode(response.getCode(), response.getSubCode()));
                    channelRetMsg.setChannelErrMsg(AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));
                    return channelRetMsg;
                } else {
                    return ChannelRetMsg.waiting();
                }
            } else {
                //若 系统繁忙， 无法确认结果
                if ("SYSTEM_ERROR".equalsIgnoreCase(response.getSubCode())) {
                    return ChannelRetMsg.waiting();
                }

                channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                channelRetMsg.setChannelErrCode(response.getSubCode());
                channelRetMsg.setChannelErrMsg(response.getSubMsg());
            }
        } catch (Exception e) {
            log.info("支付宝请求异常", e);
            channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            channelRetMsg.setChannelErrMsg("支付宝请求异常");
        }


        return channelRetMsg;
    }

    @Override
    public ChannelRetMsg query(TransferOrder transferOrder, IsvParams isvParams) {
        ChannelRetMsg result = new ChannelRetMsg();

        AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
        AlipayFundTransCommonQueryModel model = new AlipayFundTransCommonQueryModel();
        model.setProductCode(TransferOrder.ENTRY_BANK_CARD.equals(transferOrder.getEntryType()) ? "TRANS_BANKCARD_NO_PWD" : "TRANS_ACCOUNT_NO_PWD");
        model.setBizScene("DIRECT_TRANSFER");
        model.setOutBizNo(transferOrder.getTransferId()); // 商户转账唯一订单号

        AlipayIsvParams aliaqfIsvParams = (AlipayIsvParams) isvParams;

        request.setBizModel(model);

        request.putOtherTextParam("app_auth_token", aliaqfIsvParams.getAppAuthToken());

        // 服务商信息
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId(aliaqfIsvParams.getPid());

        try {
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(aliaqfIsvParams.getConfig());
            AlipayFundTransCommonQueryResponse response = alipayClient.certificateExecute(request);

            if (response.isSuccess()) {
                // SUCCESS，明确成功
                if ("SUCCESS".equalsIgnoreCase(response.getStatus())) {
                    return ChannelRetMsg.confirmSuccess(response.getOrderId());
                }
                // REFUND：退票（适用于"单笔转账到银行卡"）； FAIL：失败（适用于"单笔转账到银行卡"）
                else if ("REFUND".equalsIgnoreCase(response.getStatus()) || "FAIL".equalsIgnoreCase(response.getStatus())) {
                    return ChannelRetMsg.confirmFail(response.getErrorCode(), response.getFailReason());
                } else {
                    result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                }
            } else {
                // 如果查询单号对应的数据不存在，那么数据不存在的原因可能是：（1）付款还在处理中；（2）付款处理失败导致付款订单没有落地，务必再次查询确认此次付款的结果。
                if ("ORDER_NOT_EXIST".equalsIgnoreCase(response.getSubCode())) {
                    result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                } else {
                    return ChannelRetMsg.confirmFail(AlipayKit.appendErrCode(response.getCode(), response.getSubCode()), AlipayKit.appendErrMsg(response.getMsg(), response.getSubMsg()));

                }
            }
        } catch (Exception e) {
            log.info("支付宝请求异常", e);
            result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
            result.setChannelErrMsg("支付宝请求异常");
        }

        return result;
    }

}
