package com.izouma.wenlvju.service;

import com.izouma.wenlvju.domain.SysConfig;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.SysConfigRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.Cacheable;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Service
@AllArgsConstructor
public class SysConfigService {
    private SysConfigRepo sysConfigRepo;

    public Page<SysConfig> all(PageQuery pageQuery) {
        return sysConfigRepo.findAll(JpaUtils.toSpecification(pageQuery, SysConfig.class), JpaUtils.toPageRequest(pageQuery));
    }

    @Cacheable("SysConfigServiceGetBigDecimal")
    public BigDecimal getBigDecimal(String name) {
        return sysConfigRepo.findByName(name).map(sysConfig -> new BigDecimal(sysConfig.getValue()))
                .orElse(BigDecimal.ZERO);
    }

    @Cacheable("SysConfigServiceGetTime")
    public LocalTime getTime(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        return LocalTime.from(dateTimeFormatter.parse(str));
    }

    @Cacheable("SysConfigServiceGetBoolean")
    public boolean getBoolean(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        return "1".equals(str);
    }

    @Cacheable("SysConfigServiceGetInt")
    public int getInt(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        return Integer.parseInt(str);
    }
}
