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.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.math.BigDecimal;

@Component
public class WechatDownload implements Expansion {

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

    @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() + "次";
        BigDecimal totalFee = downloadOrderEntity.getAmount().multiply(new BigDecimal(100));
        String orderSn = downloadOrderEntity.getOrderSn();
        String body = subject;
        orderSn += "_download";
        return payOrderService.wechatScanPay(orderSn, subject, body, totalFee);
    }

    @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() + "次";
        BigDecimal totalFee = downloadOrderEntity.getAmount().multiply(new BigDecimal(100));
        String orderSn = downloadOrderEntity.getOrderSn();
        String body = subject;
        orderSn += "_download";
        return payOrderService.wechatH5Pay(orderSn, subject, body, totalFee, ip);
    }

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