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.IncrementOrder;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.IIncrementOrderService;
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 AlipayIncrement implements Expansion {

    @Autowired
    private IIncrementOrderService iIncrementOrderService;
    @Autowired
    private PayOrderService payOrderService;

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

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

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