package cn.datax.service.data.market.service.impl;

import cn.datax.common.base.BaseServiceImpl;
import cn.datax.service.data.market.api.dto.ApiMaskDto;
import cn.datax.service.data.market.api.entity.ApiMaskEntity;
import cn.datax.service.data.market.api.vo.ApiMaskVo;
import cn.datax.service.data.market.dao.ApiMaskDao;
import cn.datax.service.data.market.mapstruct.ApiMaskMapper;
import cn.datax.service.data.market.service.ApiMaskService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 数据API脱敏信息表 服务实现类
 * </p>
 *
 * @author yuwei
 * @since 2020-04-14
 */
@CacheConfig(cacheNames = "data:api:masks")
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ApiMaskServiceImpl extends BaseServiceImpl<ApiMaskDao, ApiMaskEntity> implements ApiMaskService {

    @Autowired
    private ApiMaskDao apiMaskDao;

    @Autowired
    private ApiMaskMapper apiMaskMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveApiMask(ApiMaskDto apiMaskDto) {
        ApiMaskEntity apiMask = apiMaskMapper.toEntity(apiMaskDto);
        apiMaskDao.insert(apiMask);
    }

    @CachePut(key = "#p0.id")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateApiMask(ApiMaskDto apiMaskDto) {
        ApiMaskEntity apiMask = apiMaskMapper.toEntity(apiMaskDto);
        apiMaskDao.updateById(apiMask);
    }

    @Cacheable(key = "#id")
    public ApiMaskVo getApiMaskById(String id) {
        ApiMaskEntity apiMaskEntity = super.getById(id);
        return apiMaskMapper.toVO(apiMaskEntity);
    }

    @Cacheable(key = "#apiId")
    @Override
    public ApiMaskVo getApiMaskByApiId(String apiId) {
        ApiMaskEntity apiMaskEntity = apiMaskDao.selectOne(new QueryWrapper<ApiMaskEntity>().eq("api_id", apiId));
        return apiMaskMapper.toVO(apiMaskEntity);
    }

    @CacheEvict(key = "#id")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteApiMaskById(String id) {
        apiMaskDao.deleteById(id);
    }
}
