package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.SysLicense;
import com.ruoyi.system.mapper.SysLicenseMapper;
import com.ruoyi.system.service.ILicenseService;
import org.springframework.stereotype.Service;

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

@Service
public class LicenseServiceImpl implements ILicenseService {

    @Resource
    private SysLicenseMapper licenseMapper;

    private static final String SECRET_KEY = "TangShanKaoKeSecretKey076";

    @Override
    public boolean activateLicense(String licenseKey, Date expireDate) {
        if (StringUtils.isEmpty(licenseKey) || expireDate == null) {
            return false;
        }

        String expectedKey = generateLicenseKey(expireDate);
        if (!expectedKey.equals(licenseKey)) {
            return false;
        }

        SysLicense license = new SysLicense();
        license.setLicenseKey(licenseKey);
        license.setExpireDate(expireDate);
        license.setCreateTime(new Date());

        licenseMapper.deleteLicense();
        return licenseMapper.insertLicense(license) > 0;
    }

    @Override
    public boolean checkLicense() {
        SysLicense license = licenseMapper.selectLicense();
        if (license == null||(!generateLicenseKey( license.getExpireDate()).equals(license.getLicenseKey()))) {
            return false;
        }
        
        return !license.getExpireDate().before(new Date());
    }

    @Override
    public Date getExpireDate() {
        SysLicense license = licenseMapper.selectLicense();
        return license != null ? license.getExpireDate() : null;
    }

    public String generateLicenseKey(Date expireDate) {
        String raw = SECRET_KEY + DateUtils.parseDateToStr("yyyyMMdd", expireDate);
        return Md5Utils.hash(raw);
    }
}
