package com.izouma.jmrh.service;

import com.izouma.jmrh.domain.SysConfig;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.SysConfigRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.Cacheable;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

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

    @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 str.equals("1");
    }

    @PostConstruct
    public void init() {
        if (!sysConfigRepo.findByName("contact_phone").isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name("contact_phone")
                    .desc("联系电话")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }
        if (!sysConfigRepo.findByName("contact_email").isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name("contact_email")
                    .desc("邮箱")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }
        if (!sysConfigRepo.findByName("contact_address").isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name("contact_address")
                    .desc("地址")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }
        if (!sysConfigRepo.findByName("qr_code").isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name("qr_code")
                    .desc("公众号")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }
    }
}
