package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysConfig;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.mapper.SysConfigMapper;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 参数表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Resource
    CommonCacheService commonCacheService;

    @Override
    public SysConfig getByKey(String key) {
        if (StringUtils.isBlank(key)) {
            throw ExceptionResultEnum.ERROR.exception("key不能为空");
        }
        QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysConfig::getConfigKey, key);
        SysConfig sysConfig = this.baseMapper.selectOne(queryWrapper);
        return sysConfig;
    }

    /**
     * 查询所有系统配置项
     *
     * @return
     */
    @Override
    public List<SysConfig> selectAll() {
        List<SysConfig> sysConfigList = null;
        try {
            QueryWrapper<SysConfig> sysConfigQueryWrapper = new QueryWrapper<>();
            sysConfigQueryWrapper.lambda().isNull(SysConfig::getSchoolId);
            sysConfigList = this.list(sysConfigQueryWrapper);
            if (!CollectionUtils.isEmpty(sysConfigList)) {
                for (SysConfig s : sysConfigList) {
                    commonCacheService.updateSysConfigCacheForDb(s.getConfigKey(), s);
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
        return sysConfigList;
    }
}
