package com.ruoyi.web.modules.trading.support;

import java.math.BigDecimal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.trading.domain.BizSupplier;
import com.ruoyi.web.modules.trading.domain.BizSupplierSettlement;
import com.ruoyi.web.modules.trading.domain.BizTradeOrder;
import com.ruoyi.web.modules.trading.mapper.BizSupplierSettlementMapper;

/**
 * 完成支付时生成供应商结算单（费用快照）。
 */
@Component
public class SettlementOnPayService
{
    public static final String SETTLEMENT_STATUS_PENDING = "0";

    @Autowired
    private BizSupplierSettlementMapper bizSupplierSettlementMapper;

    @Autowired
    private SettlementNoGenerator settlementNoGenerator;

    public BizSupplierSettlement createFromOrder(BizTradeOrder order, BizSupplier supplier, String operator)
    {
        if (bizSupplierSettlementMapper.selectByOrderId(order.getId()) != null)
        {
            throw new ServiceException(TradeOrderRules.MSG_SETTLEMENT_EXISTS);
        }
        BigDecimal serviceFee = SettlementFeeCalculator.calcServiceFee(
                supplier, order.getTotalHeads(), order.getTotalAmount());
        BigDecimal payable = SettlementFeeCalculator.calcPayableAmount(order.getTotalAmount(), serviceFee);

        BizSupplierSettlement settlement = new BizSupplierSettlement();
        settlement.setSettlementNo(settlementNoGenerator.allocateNextSettlementNo());
        settlement.setOrderId(order.getId());
        settlement.setOrderNo(order.getOrderNo());
        settlement.setSupplierId(order.getSupplierId());
        settlement.setTotalHeads(order.getTotalHeads());
        settlement.setTotalAmount(order.getTotalAmount());
        settlement.setFeeMethod(supplier.getFeeMethod());
        settlement.setFeeStandard(supplier.getFeeStandard());
        settlement.setTransactionFeeRate(supplier.getTransactionFeeRate());
        settlement.setManagementFeeRate(supplier.getManagementFeeRate());
        settlement.setServiceFeeAmount(serviceFee);
        settlement.setPayableAmount(payable);
        settlement.setSettlementStatus(SETTLEMENT_STATUS_PENDING);
        settlement.setDelFlag(TradeOrderRules.DEL_FLAG_NORMAL);
        Date now = new Date();
        settlement.setCreateBy(operator);
        settlement.setCreateTime(now);
        settlement.setUpdateBy(operator);
        settlement.setUpdateTime(now);
        bizSupplierSettlementMapper.insertBizSupplierSettlement(settlement);
        return settlement;
    }
}
