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.CommerceOrder;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.ICommerceOrderService;
import com.fdkankan.platform.order.service.PayOrderService;
import com.fdkankan.platform.user.factory.Commerce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class AlipayCommerce implements Commerce {

    @Autowired
    private ICommerceOrderService commerceOrderService;
    @Autowired
    private PayOrderService payOrderService;

    @Override
    public JSONObject scanPay(RequestPlaceOrder order) throws Exception {
        CommerceOrder commerce = commerceOrderService.getById(order.getOrderId());
        if (commerce == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        String subject = Constant.COMMERCE_SUBJECT;
        List<AlipayGoodsDetail> goodsDetailList = new ArrayList<>();
        AlipayGoodsDetail goodsDetail = AlipayGoodsDetail.newInstance(commerce.getOrderSn(), subject, commerce.getAmount().intValue(), 1);
        goodsDetailList.add(goodsDetail);
        String orderSn = commerce.getOrderSn();
        orderSn += "_commerce";
        return payOrderService.aliPayScanPay(orderSn, subject, subject, commerce.getAmount(), goodsDetailList);
    }

    @Override
    public JSONObject h5Pay(RequestPlaceOrder order, String ip) throws Exception {
        CommerceOrder commerce = commerceOrderService.getById(order.getOrderId());
        if (commerce == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        String subject = Constant.COMMERCE_SUBJECT;
        String orderSn = commerce.getOrderSn();
        orderSn += "_commerce";
        return payOrderService.aliPayH5Pay(orderSn, subject, subject, commerce.getAmount());
    }

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