package com.seer.teach.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.pay.entity.PayCoinAccountEntity;
import com.seer.teach.pay.mapper.PayCoinAccountMapper;
import com.seer.teach.pay.service.IPayCoinAccountStatusService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Slf4j
@Service
@RequiredArgsConstructor
public class PayCoinAccountStatusService extends ServiceImpl<PayCoinAccountMapper, PayCoinAccountEntity> implements IPayCoinAccountStatusService {

    private static final String USER_COIN_ACCOUNT_STATUS_KEY_PREFIX = "lock:user:coin:account:";

    private final RedisTemplate redisTemplate;

    @Override
    public boolean lockAccount(Integer userId, Integer accountId) {
        log.info("锁定用户 {} 的学豆账户 ID: {}", userId, accountId);
        String key = USER_COIN_ACCOUNT_STATUS_KEY_PREFIX + userId + ":" + accountId;
        Boolean result = redisTemplate.opsForValue().setIfAbsent(
                key,
                String.valueOf(System.currentTimeMillis()),
                3000,
                TimeUnit.MILLISECONDS
        );
        if (!result) {
            log.info("用户 {} 的学豆账户 ID: {} 已经被redis锁定,redis key :{}", userId, accountId,key);
            return false;
        }
        return updateAccountBlockStatus(userId, accountId, CommonConstant.ACCOUNT_LOCKED);
    }

    @Override
    public boolean unlockAccount(Integer userId, Integer accountId) {
        log.info("解锁用户 {} 的学豆账户 ID: {}", userId, accountId);
        String key = USER_COIN_ACCOUNT_STATUS_KEY_PREFIX + userId + ":" + accountId;
        Boolean deleteResult = redisTemplate.delete(key);
        log.info("redis 删除用户 {} 的学豆账户 ID: {} 的锁定状态结果：{}", userId, accountId, deleteResult ? "成功" : "失败");
        return updateAccountBlockStatus(userId, accountId, CommonConstant.ACCOUNT_UNLOCKED);
    }

    /**
     * 更新账户锁定状态
     */
    private boolean updateAccountBlockStatus(Integer userId, Integer accountId, int status) {
        return super.update(new LambdaUpdateWrapper<PayCoinAccountEntity>()
                .eq(PayCoinAccountEntity::getUserId, userId)
                .eq(PayCoinAccountEntity::getId, accountId)
                .set(PayCoinAccountEntity::getIsBlock, status));
    }
}
