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

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

/**
 * 增值权益
 */
@Component
public class AlipayDownload implements Expansion {

    @Autowired
    private IDownloadOrderService downloadOrderService;
    @Autowired
    private PayOrderService payOrderService;

    @Override
    public JSONObject scanPay(RequestPlaceOrder order) throws Exception {
        DownloadOrder downloadOrderEntity = downloadOrderService.getById(order.getOrderId());
        if (downloadOrderEntity == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        //订单金额为国外金额就报错
        if(downloadOrderEntity.getAbroad() == 1){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8004);
        }
        String subject = Constant.DOWNLOAD_SUBJECT + "：" + downloadOrderEntity.getCount() + "次";
        List<AlipayGoodsDetail> goodsDetailList = new ArrayList<>();
        AlipayGoodsDetail goodsDetail = AlipayGoodsDetail.newInstance(downloadOrderEntity.getOrderSn(), subject, downloadOrderEntity.getAmount().intValue(), 1);
        goodsDetailList.add(goodsDetail);
        String orderSn = downloadOrderEntity.getOrderSn();
        orderSn += "_download";
        String body = subject;
        return payOrderService.aliPayScanPay(orderSn, subject, body, downloadOrderEntity.getAmount(), goodsDetailList);
    }

    @Override
    public JSONObject h5Pay(RequestPlaceOrder order, String ip) throws Exception {
        DownloadOrder downloadOrderEntity = downloadOrderService.getById(order.getOrderId());
        if (downloadOrderEntity == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        //订单金额为国外金额就报错
        if(downloadOrderEntity.getAbroad() == 1){
            throw new BusinessException(ErrorCode.FAILURE_CODE_8004);
        }
        String subject = Constant.DOWNLOAD_SUBJECT + "：" + downloadOrderEntity.getCount() + "次";
        String orderSn = downloadOrderEntity.getOrderSn();
        orderSn += "_increment";
        String body = subject;
        return payOrderService.aliPayH5Pay(orderSn, subject, body, downloadOrderEntity.getAmount());
    }

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