package com.jeequan.jeepay.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.entity.TransferOrder;
import com.jeequan.jeepay.db.entity.TransferSubjectEntity;
import com.jeequan.jeepay.db.entity.TransferWalletEntity;
import com.jeequan.jeepay.service.mapper.TransferWalletMapper;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 转账对象钱包 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2024-04-29
 */
@Service
public class TransferWalletService extends ServiceImpl<TransferWalletMapper, TransferWalletEntity> {

    private final TransferSubjectService transferSubjectService;

    public TransferWalletService(TransferSubjectService transferSubjectService) {
        this.transferSubjectService = transferSubjectService;
    }

    public TransferWalletEntity getByApplyId(String transApplyId, String walletApplyId) {
        return lambdaQuery().eq(!ObjUtil.isEmpty(transApplyId), TransferWalletEntity::getTransApplyId, transApplyId)
                .eq(!ObjUtil.isEmpty(walletApplyId), TransferWalletEntity::getTransApplyId, walletApplyId)
                .orderByDesc(TransferWalletEntity::getId).last("limit 1")
                .one();
    }

    public void updateWallet(TransferOrder transferOrder) {
        String transferSubjectIdFq = transferOrder.getTransferSubjectIdFq();

        TransferSubjectEntity transferSubjectFq = transferSubjectService.getById(transferSubjectIdFq);
        TransferWalletEntity wallet = getByApplyId(transferSubjectFq.getTransApplyId(), null);

        Long accountBookBalance = wallet.getAccountBookBalance();
        if (TransferOrder.TRANSFER_TYPE_IN.equals(transferOrder.getTransferType())) {
            // 入账
            accountBookBalance += transferOrder.getAmount();
        }

        if (TransferOrder.TRANSFER_TYPE_OUT.equals(transferOrder.getTransferType())) {
            // 入账
            accountBookBalance -= transferOrder.getAmount();
        }

        transferOrder.setAmount(accountBookBalance);
        updateById(wallet);
    }

    /**
     * 刷新账户余额，同步上游数据
     */
    public void syncWallet(TransferWalletEntity transferWallet) {

    }
}
