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

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.IOrderService;
import com.fdkankan.platform.order.service.PayOrderService;
import com.fdkankan.platform.user.factory.Entity;
import com.fdkankan.platform.user.vo.ResponseOrder;
import com.fdkankan.platform.user.vo.ResponseOrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class WechatEntity implements Entity {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private PayOrderService payOrderService;

    @Override
    public JSONObject scanPay(RequestPlaceOrder order) throws Exception {
        ResponseOrder responseOrder = orderService.getOrderDetail(order.getOrderId());
        if (responseOrder.getId() == null) {
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        List<ResponseOrderItem> items = responseOrder.getOrderItems();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < items.size(); i++){
            sb.append(items.get(i).getGoodsCount()).append("*").append(items.get(i).getGoodsName());
            if (i != items.size() - 1){
                sb.append("，");
            }
        }
        BigDecimal totalFee = responseOrder.getTotalAmount().multiply(new BigDecimal(100));
        String orderSn = responseOrder.getOrderSn();
        orderSn += "_entity";
        return payOrderService.wechatScanPay(orderSn, "四维看看官网-商品", sb.toString(), totalFee);
    }

    @Override
    public JSONObject h5Pay(RequestPlaceOrder order, String ip) throws Exception {
        ResponseOrder responseOrder = orderService.getOrderDetail(order.getOrderId());
        if (responseOrder.getId() == null) {
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }

        List<ResponseOrderItem> items = responseOrder.getOrderItems();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < items.size(); i++){
            sb.append(items.get(i).getGoodsCount()).append("*").append(items.get(i).getGoodsName());
            if (i != items.size() - 1){
                sb.append("，");
            }
        }
        BigDecimal totalFee = responseOrder.getTotalAmount().multiply(new BigDecimal(100));
        String orderSn = responseOrder.getOrderSn();
        orderSn += "_entity";
        return payOrderService.wechatH5Pay(orderSn, "四维看看官网-商品", sb.toString(), totalFee, ip);
    }

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