package com.CUST.brain.service.impl;

import com.CUST.brain.common.annotation.RedisCache;
import com.CUST.brain.common.constant.RedisKeyConstants;
import com.CUST.brain.dao.domain.system.SysParamType;
import com.CUST.brain.dao.mapper.SysParamTypeMapper;
import com.CUST.brain.service.SysParamTypeService;
import com.CUST.brain.common.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统参数类型服务实现类
 */
@Service
public class SysParamTypeServiceImpl extends ServiceImpl<SysParamTypeMapper, SysParamType> implements SysParamTypeService {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @RedisCache(key = RedisKeyConstants.SYS_PREFIX + "param:type:list", expire = 86400)
    public List<SysParamType> listAll() {
        LambdaQueryWrapper<SysParamType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysParamType::getFlag, 0)
                .orderByAsc(SysParamType::getSortOrder);
        return list(wrapper);
    }

    @Override
    @RedisCache(key = RedisKeyConstants.SYS_PREFIX + "param:type:name:#{typeName}", expire = 86400)
    public SysParamType getByTypeName(String typeName) {
        LambdaQueryWrapper<SysParamType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysParamType::getTypeName, typeName)
                .eq(SysParamType::getFlag, 0);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateParamType(SysParamType paramType) {
        boolean result = updateById(paramType);
        if (result) {
            // 删除相关缓存
            redisUtils.delete(RedisKeyConstants.SYS_PREFIX + "param:type:list");
            redisUtils.delete(RedisKeyConstants.SYS_PREFIX + "param:type:name:" + paramType.getTypeName());
        }
        return result;
    }
} 