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

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeSettleConfirmModel;
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 com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.interfaces.paychannel.IPayOrderSettService;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.thirdparty.model.ZftpayClientWrapper;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 直付通订单确认结算
 *
 * **/
@Service
public class ZftpayPayOrderSettService implements IPayOrderSettService {

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    /**
     * 直付通确认结算
     * @param payOrder
     * @param channelTradeNo
     * @return
     */
    @Override
    public ChannelRetMsg tradeSettleConfirm(PayOrder payOrder, String channelTradeNo,String settleNo) {
        ZftpayClientWrapper zftpayClientWrapper = configContextQueryService.getZftpayClientWrapper(payOrder.getIsvNo());
        AlipayTradeSettleConfirmRequest request = new AlipayTradeSettleConfirmRequest();
        AlipayTradeSettleConfirmModel model = new AlipayTradeSettleConfirmModel();
        model.setOutRequestNo(settleNo);
        model.setTradeNo(channelTradeNo);
        SettleInfo settleInfo = new SettleInfo();
        List<SettleDetailInfo> list = new ArrayList<>();
        SettleDetailInfo detailInfo = new SettleDetailInfo();
        detailInfo.setTransInType("defaultSettle");
        detailInfo.setAmount(AmountUtil.convertCent2Dollar(payOrder.getFindAmt()));
        detailInfo.setSettleEntityId(payOrder.getChannelMchNo());
        detailInfo.setSettleEntityType("SecondMerchant");
        list.add(detailInfo);
        settleInfo.setSettleDetailInfos(list);
        model.setSettleInfo(settleInfo);
        request.setBizModel(model);
        try {
            AlipayTradeSettleConfirmResponse response = zftpayClientWrapper.getAlipayClient().execute(request);
            if(response.isSuccess()){
                return ChannelRetMsg.confirmSuccess(response.getTradeNo());
            }
            return ChannelRetMsg.confirmFail(response.getTradeNo(),response.getCode(),response.getMsg());
        } catch (AlipayApiException e) {
            return ChannelRetMsg.confirmFail(e.getErrCode(),e.getErrMsg());
        }
    }
}
