package com.jy.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.framework.model.constants.RedisConstant;
import com.jy.framework.redis.RedisCache;
import com.jy.framework.redis.RedisKey;
import com.jy.framework.utils.AssertUtil;
import com.jy.system.dao.SysDictTypeDao;
import com.jy.system.model.dto.SysDictTypeDto;
import com.jy.system.model.dto.SysDictTypeSelectDto;
import com.jy.system.model.entity.SysDictType;
import com.jy.system.model.vo.SysDictTypeVo;
import com.jy.system.service.SysDictTypeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 字典类型 服务实现类
 * </p>
 *
 * @author
 * @since 2024-06-20
 */
@Service
public class SysDictTypeServiceImpl implements SysDictTypeService {

    @Resource
    private SysDictTypeDao sysDictTypeDao;

    @Override
    public Page<SysDictTypeVo> getPage(SysDictTypeSelectDto dto) {
        return sysDictTypeDao.getPage(dto);
    }

    @Override
    public SysDictTypeVo getDetail(Long id) {
        SysDictTypeVo vo = sysDictTypeDao.getDetail(id);
        AssertUtil.notNull(vo, "未知数据");
        return vo;
    }

    @Override
    public void add(SysDictTypeDto dto) {
        // 验证字典编码是否存在
        boolean codeExists = sysDictTypeDao.codeExists(dto.getCode());
        AssertUtil.eqFalse(codeExists, "字典编码已存在");

        // 保存字典
        sysDictTypeDao.save(dto);
    }

    @Override
    public void edit(SysDictTypeDto dto) {
        // 查询原数据
        SysDictType sysDictType = sysDictTypeDao.getById(dto.getId());
        AssertUtil.notNull(sysDictType, "未知数据");

        // 验证字典编码是否存在
        boolean codeExists = sysDictTypeDao.codeExists(dto.getCode(), dto.getId());
        AssertUtil.eqFalse(codeExists, "字典编码已存在");

        // 删除字典缓存
        RedisCache.delete(RedisKey.getDict(sysDictType.getCode()));

        // 更新字典
        sysDictTypeDao.updateById(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> idList) {
        // 删除字典缓存
        List<SysDictType> sysDictTypeList = sysDictTypeDao.listByIds(idList);
        sysDictTypeList.forEach(item -> RedisCache.delete(RedisKey.getConfig(item.getCode())));

        // 删除字典信息
        sysDictTypeDao.removeByIds(idList);
    }

    @Override
    public void refreshCache() {
        List<String> scan = RedisCache.scan(RedisConstant.DICT_KEY + StringPool.ASTERISK);
        scan.forEach(RedisCache::delete);
    }

}
