package com.usky.sas.service.impl;

import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.sas.domain.SasSystemActivation;
import com.usky.sas.mapper.SasSystemActivationMapper;
import com.usky.sas.service.SasSystemActivationService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 系统激活 服务实现
 */
@Service
public class SasSystemActivationServiceImpl extends AbstractCrudService<SasSystemActivationMapper, SasSystemActivation>
        implements SasSystemActivationService {

    private static final Integer DEFAULT_ID = 1;

    @Override
    public SasSystemActivation activate(String licenseKey) {
        SasSystemActivation activation = this.getById(DEFAULT_ID);
        LocalDateTime now = LocalDateTime.now();
        if (activation == null) {
            activation = new SasSystemActivation();
            activation.setId(DEFAULT_ID);
            activation.setCreateTime(now);
        }
        activation.setLicenseKey(licenseKey);
        activation.setActivationTime(now);
        activation.setUpdateTime(now);
        if (activation.getIsPerpetual() == null) {
            activation.setIsPerpetual(false);
        }
        if (activation.getValidityTime() == null && !Boolean.TRUE.equals(activation.getIsPerpetual())) {
            activation.setValidityTime(now.plusYears(1));
        }
        if (this.getById(DEFAULT_ID) == null) {
            this.save(activation);
        } else {
            this.updateById(activation);
        }
        return activation;
    }

    @Override
    public SasSystemActivation currentActivation() {
        return this.getById(DEFAULT_ID);
    }
}
