package com.njcn.gather.system.cfg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.gather.system.cfg.mapper.SysConfigMapper;
import com.njcn.gather.system.cfg.pojo.param.SysConfigParam;
import com.njcn.gather.system.cfg.pojo.po.SysConfig;
import com.njcn.gather.system.cfg.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统配置服务实现。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    private static final String DEFAULT_CONFIG_ID = "00000000000000000000000000000001";
    private static final String DEFAULT_WAVE_STORAGE_PATH = "D:/";

    @Override
    @Transactional
    public boolean updateConfig(SysConfigParam.UpdateParam param) {
        SysConfig config = getOneConfig();
        if (config == null) {
            config = new SysConfig();
            config.setId(param != null && StringUtils.isNotBlank(param.getId()) ? param.getId().trim() : DEFAULT_CONFIG_ID);
            config.setState(DataStateEnum.ENABLE.getCode());
            config.setWaveStoragePath(DEFAULT_WAVE_STORAGE_PATH);
        }
        if (param != null && StringUtils.isNotBlank(param.getWaveStoragePath())) {
            config.setWaveStoragePath(param.getWaveStoragePath().trim());
        }
        return this.saveOrUpdate(config);
    }

    @Override
    public SysConfig getOneConfig() {
        QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<SysConfig>();
        queryWrapper.eq("state", DataStateEnum.ENABLE.getCode());
        queryWrapper.last("LIMIT 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public String getWaveStoragePath() {
        SysConfig config = getOneConfig();
        if (config == null || StringUtils.isBlank(config.getWaveStoragePath())) {
            return DEFAULT_WAVE_STORAGE_PATH;
        }
        return config.getWaveStoragePath().trim();
    }
}
