package com.dayou.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.dayou.common.BaseEntity;
import com.dayou.entity.OrderFund;
import com.dayou.enums.MainBusinessEnum;
import com.dayou.mapper.OrderFundMapper;
import com.dayou.service.IFinanceClaimService;
import com.dayou.service.IOrderFundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

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

/**
 * <p>
 * 订单应收款 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2023-12-14
 */
@DS("mbs")
@Service
public class OrderFundServiceImpl extends ServiceImpl<OrderFundMapper, OrderFund> implements IOrderFundService {

    @Autowired
    private OrderFundMapper orderFundMapper;

    @Autowired
    private IFinanceClaimService financeClaimService;

    @Override
    @SuppressWarnings("unchecked")
    public Page<OrderFund> selectPage(Page page,OrderFund orderFund){
        return this.page(page, new QueryWrapper<OrderFund>(orderFund));
    }


    @Override
    public OrderFund detail(Long id){
        return this.getById(id);
    }

    @Override
    public Boolean add(OrderFund orderFund){
        return  this.save(orderFund);
    }

    @Override
    public Boolean update(OrderFund orderFund){
        return  this.updateById(orderFund);
    }

    @Override
    public Boolean delete(Long id){
        //逻辑删除
        return this.removeById(id);
    }

    @Override
    public synchronized BigDecimal residueNotAllotAmount(Long orderFundId) {
        BigDecimal residue = orderFundMapper.residueNotAllotAmount(orderFundId);
        return residue;
    }

    @Override
    public void updateRealAmount(Long orderFundId) {
        BigDecimal totalAmount = financeClaimService.getTotalClaimAmountByOrderFundId(orderFundId);
        this.update(new LambdaUpdateWrapper<OrderFund>().set(OrderFund::getRealAmount,totalAmount)
                .eq(BaseEntity::getId,orderFundId));
    }

    @Override
    public void createOrderFundWhenOpeningOrder(Long id, String orderId, String name, MainBusinessEnum mainBusinessEnum) {
        OrderFund orderFund = new OrderFund();
        orderFund.setBusinessType(mainBusinessEnum.name());
        orderFund.setOrderId(orderId);
        orderFund.setBusinessId(id);
        orderFund.setOrderName(name);
        this.save(orderFund);
    }

    @Override
    public List<OrderFund> getAllOrderFund() {
        return orderFundMapper.getAllOrderFund();
    }


}
