package org.dromara.system.service.impl;

import org.dromara.system.domain.UserTransferDTO;
import org.dromara.system.service.IUserTransferService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.redis.utils.RedisUtils;

import org.dromara.system.domain.SysUser;

import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.IUserTransferService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserTransferServiceImpl  implements IUserTransferService {

    private final SysUserMapper baseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean transferBalanceToFreeze(Long fromUserId, Long toUserId, Long amount) {
        // 参数校验
        validateTransferParams(fromUserId, toUserId, amount);

        // 检查用户是否存在且状态正常
        SysUser fromUser = baseMapper.selectById(fromUserId);
        SysUser toUser = baseMapper.selectById(toUserId);

        validateUserStatus(fromUser, toUser);

        // 检查余额是否足够
        if (fromUser.getBalance().compareTo(BigDecimal.valueOf(amount)) < 0) {
            throw new ServiceException("余额不足");
        }

        // 执行转账
        int affectedRows = baseMapper.transferBalanceToFreeze(fromUserId, toUserId, amount);

        return processTransferResult("余额转冻结", fromUserId, toUserId, amount, affectedRows);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean transferFreezeToBalance(Long fromUserId, Long toUserId, Long amount) {
        // 参数校验
        validateTransferParams(fromUserId, toUserId, amount);

        // 检查用户是否存在且状态正常
        SysUser fromUser = baseMapper.selectById(fromUserId);
        SysUser toUser = baseMapper.selectById(toUserId);

        validateUserStatus(fromUser, toUser);

        // 检查冻结资金是否足够
        if (fromUser.getFreeze().compareTo(BigDecimal.valueOf(amount)) < 0) {
            throw new ServiceException("冻结资金不足");
        }

        // 执行转账
        int affectedRows = baseMapper.transferFreezeToBalance(fromUserId, toUserId, amount);

        return processTransferResult("冻结转余额", fromUserId, toUserId, amount, affectedRows);
    }

    /**
     * 更新用户余额
     * @param userId 用户ID
     * @param balance 新余额（分）
     * @return 影响行数
     */
    @Override
    public int updateBalance(Long userId, Long balance){
        return baseMapper.updateBalance(userId, balance);
    }

    /**
     * 校验转账参数
     */
    private void validateTransferParams(Long fromUserId, Long toUserId, Long amount) {
        if (fromUserId == null || toUserId == null || amount == null) {
            throw new ServiceException("参数不能为空");
        }
        if (amount <= 0) {
            throw new ServiceException("转账金额必须大于0");
        }
        // if (fromUserId.equals(toUserId)) {
        //     throw new ServiceException("转出用户和转入用户不能相同");
        // }
    }

    /**
     * 校验用户状态
     */
    private void validateUserStatus(SysUser fromUser, SysUser toUser) {
        if (fromUser == null || !"0".equals(fromUser.getDelFlag()) || !"0".equals(fromUser.getStatus())) {
            throw new ServiceException("转出用户不存在或状态异常");
        }
        if (toUser == null || !"0".equals(toUser.getDelFlag()) || !"0".equals(toUser.getStatus())) {
            throw new ServiceException("转入用户不存在或状态异常");
        }
    }

    /**
     * 处理转账结果
     */
    private boolean processTransferResult(String operation, Long fromUserId, Long toUserId, Long amount, int affectedRows) {
        if (affectedRows == 1 || affectedRows == 2) {
            log.info("{}成功: fromUserId={}, toUserId={}, amount={}分",
                    operation, fromUserId, toUserId, amount);
            return true;
        } else {
            log.error("{}失败: fromUserId={}, toUserId={}, amount={}分, affectedRows={}",
                    operation, fromUserId, toUserId, amount, affectedRows);
            throw new ServiceException("转账失败，请稍后重试");
        }
    }
}
