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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.enums.CoinConfigEnableEnum;
import com.seer.teach.pay.app.wallet.service.IAppCoinConfigService;
import com.seer.teach.pay.entity.CoinConfigEntity;
import com.seer.teach.pay.mapper.CoinConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 学豆配置表 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-06-17
 */
@Slf4j
@Service
public class AppCoinConfigServiceImpl extends ServiceImpl<CoinConfigMapper, CoinConfigEntity> implements IAppCoinConfigService {

    @Override
    public boolean create(CoinConfigEntity coinConfigEntity) {
        // 保存新的配置实体
        coinConfigEntity.setIsUsed(CoinConfigEnableEnum.ENABLED.getCode());
        boolean save = super.save(coinConfigEntity);
        log.info("保存结果:{}", save);
        List<CoinConfigEntity> oldCoinConfigEntities = super.list().stream()
                .filter(coinConfig -> coinConfig.getId().intValue() != coinConfigEntity.getId().intValue())
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(oldCoinConfigEntities)) {
            // 批量更新，将原来的配置更新为不可用
            for (CoinConfigEntity coinConfig : oldCoinConfigEntities) {
                coinConfig.setIsUsed(CoinConfigEnableEnum.DISABLED.getCode());
            }
            boolean updateBatchResult = super.updateBatchById(oldCoinConfigEntities);
            log.info("批量更新结果:{}", updateBatchResult);
        }
        return save;
    }

    @Override
    public CoinConfigEntity getActiveAndLatestCoinConfig() {
        return super.getOne(
                new LambdaQueryWrapper<CoinConfigEntity>()
                        .eq(CoinConfigEntity::getIsUsed, 1)
                        .orderByDesc(CoinConfigEntity::getCreateTime)
        );
    }
}