package cn.iocoder.yudao.module.system.dal.mysql.tenantbalance;

import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.tenantbalance.TenantBalanceDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.yudao.module.system.controller.admin.tenantbalance.vo.*;
import org.apache.ibatis.annotations.Param;

/**
 * 租户余额 Mapper
 *
 * @author 总后台
 */
@Mapper
public interface TenantBalanceMapper extends BaseMapperX<TenantBalanceDO> {

    default PageResult<TenantBalanceDO> selectPage(TenantBalancePageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<TenantBalanceDO>()
                .eqIfPresent(TenantBalanceDO::getBalance, reqVO.getBalance())
                .eqIfPresent(TenantBalanceDO::getVersion, reqVO.getVersion())
                .eqIfPresent(TenantBalanceDO::getUpdatedAt, reqVO.getUpdatedAt())
                .orderByDesc(TenantBalanceDO::getId));
    }

    default Integer updateBalanceWithVersion(Long id, int amount, Integer oldVersion) {
        LambdaUpdateWrapper<TenantBalanceDO> wrapper = new LambdaUpdateWrapper<>();

        wrapper.eq(TenantBalanceDO::getId, id);
        wrapper.eq(TenantBalanceDO::getVersion, oldVersion);

        // balance = balance + amount
        wrapper.setSql("balance = balance + " + amount);

        // version = version + 1
        wrapper.setSql("version = version + 1");

        return this.update(null, wrapper);
    }


    IPage<TenantBalanceRespVO> selectPageWithTenantName(IPage<TenantBalanceRespVO> iPage,@Param("req") TenantBalancePageReqVO pageReqVO);

    IPage<TenantBalanceRespVO> selectPageWithSelfSubordinateTenant(@Param("iPage") IPage<TenantBalanceRespVO> iPage, @Param("pageReqVO") TenantBalancePageReqVO pageReqVO, @Param("tenantId") Long tenantId);

    default Integer updateTestAccountNumWithVersion(Long currentTenantId, Integer newTestAccountNum, Integer oldVersion){
        LambdaUpdateWrapper<TenantBalanceDO> wrapper = new LambdaUpdateWrapper<>();

        wrapper.eq(TenantBalanceDO::getId, currentTenantId);
        wrapper.eq(TenantBalanceDO::getVersion, oldVersion);

        // testAccount = testAccount + -1
        wrapper.setSql("test_account_num = test_account_num + " + newTestAccountNum);

        // version = version + 1
        wrapper.setSql("version = version + 1");

        return this.update(null, wrapper);
    }
}