package cn.pluss.platform.encrypt.impl;

import cn.pluss.platform.encrypt.EncryptKeyService;
import cn.pluss.platform.entity.EncryptKey;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.EncryptKeyMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商务密钥存储表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2021-10-28
 */
@Service
public class EncryptKeyServiceImpl extends ServiceImpl<EncryptKeyMapper, EncryptKey> implements EncryptKeyService {

    @Override
    public boolean save(EncryptKey entity) {
        return super.save(entity);
    }

    @Override
    public void enable(String id) {
        long longId;
        try {
            longId = Long.parseLong(id);
        } catch (NumberFormatException e) {
            throw new MsgException("非法的ID");
        }

        EncryptKey encryptKey = getById(longId);

        if (encryptKey == null) {
            throw new MsgException("该记录不存在");
        }

        // 先全部置为无效
        LambdaUpdateWrapper<EncryptKey> uWrapper = Wrappers.lambdaUpdate(EncryptKey.class);
        uWrapper.set(EncryptKey::getStatus, EncryptKey.STATUS_DISABLE);
        update(uWrapper);

        // 使选择的记录生效
        encryptKey.setStatus(EncryptKey.STATUS_ENABLE);
        updateById(encryptKey);
    }
}
