package com.fdkankan.platform.user.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.Constant;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.pay.alipay.sdk.AlipayGoodsDetail;
import com.fdkankan.platform.order.entity.VirtualOrder;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.IVirtualOrderService;
import com.fdkankan.platform.order.service.PayOrderService;
import com.fdkankan.platform.user.factory.Recharge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
public class AlipayRecharge implements Recharge {

    @Autowired
    private IVirtualOrderService virtualOrderService;
    @Autowired
    private PayOrderService payOrderService;

    @Override
    public JSONObject scanPay(RequestPlaceOrder order) throws Exception {
        VirtualOrder virtualOrderEntity = virtualOrderService.getById(order.getOrderId());
        if (virtualOrderEntity == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        String subject = Constant.PAY_SUBJECT + "：" + virtualOrderEntity.getPoints();
        List<AlipayGoodsDetail> goodsDetailList = new ArrayList<>();
        AlipayGoodsDetail goodsDetail = AlipayGoodsDetail.newInstance(virtualOrderEntity.getOrderSn(), subject, new BigDecimal(virtualOrderEntity.getPoints()).intValue(), 1);
        goodsDetailList.add(goodsDetail);
        String orderSn = virtualOrderEntity.getOrderSn();
        orderSn += "_recharge";
        return payOrderService.aliPayScanPay(orderSn, subject, subject, new BigDecimal(virtualOrderEntity.getPoints()), goodsDetailList);
    }

    @Override
    public JSONObject h5Pay(RequestPlaceOrder order, String ip) throws Exception {
        VirtualOrder virtualOrderEntity = virtualOrderService.getById(order.getOrderId());
        if (virtualOrderEntity == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        String subject = Constant.PAY_SUBJECT + "：" + virtualOrderEntity.getPoints();
        String orderSn = virtualOrderEntity.getOrderSn();
        orderSn += "_recharge";
        return payOrderService.aliPayH5Pay(orderSn, subject, subject, new BigDecimal(virtualOrderEntity.getPoints()));
    }

    @Override
    public String getType() {
        return "alipay_1";
    }
}
