package com.ruoyi.xq.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.xq.domain.UserBankCard;
import com.ruoyi.xq.dto.app.account.UpdateAliReq;
import com.ruoyi.xq.dto.common.user.MinUser;
import com.ruoyi.xq.lock.LockKey;
import com.ruoyi.xq.mapper.UserBankCardMapper;
import com.ruoyi.xq.service.UserBankCardService;
import com.ruoyi.xq.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户银行卡Service业务层处理
 *
 * @author 77
 * @date 2024-04-21
 */
@RequiredArgsConstructor
@Service
public class UserBankCardServiceImpl extends ServiceImpl<UserBankCardMapper,UserBankCard> implements UserBankCardService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private UserService userService;
    @Override
    public void updateAli(UpdateAliReq req) {
        checkData(req.getUserId());
        this.update(Wrappers.lambdaUpdate(UserBankCard.class)
                .set(UserBankCard::getAliCard,req.getAliCard())
                .set(UserBankCard::getAliName, req.getAliName())
                .eq(UserBankCard::getUserId, req.getUserId()));
    }

    private void checkData(Long userId){
        UserBankCard one = this.getByUserId(userId);
        if(one != null){
            return;
        }
        String key = LockKey.getUserBankCard(userId);
        RLock lock = redissonClient.getLock(key);
        try {
            lock.lock();
            one = this.getByUserId(userId);
            if(one != null){
                return;
            }
            MinUser minUser = userService.getMinUserById(userId);
            UserBankCard card = new UserBankCard();
            card.setUserId(userId);
            card.setUsercode(minUser.getUsercode());
            this.save(card);
        }finally {
            try {
                lock.unlock();
            }catch (Exception e){
                //
            }
        }
    }



    @Override
    public UserBankCard getByUserId(Long userId){
        return this.getOne(Wrappers.lambdaQuery(UserBankCard.class).eq(UserBankCard::getUserId, userId).last("limit 1"));
    }
}
