package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysLicense;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LicenseEncryptUtil;
import com.ruoyi.system.mapper.SysLicenseMapper;
import com.ruoyi.system.service.ISysLicenseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 系统许可证Service业务层处理（加密版）
 *
 * @author ruoyi
 * @date 2026-02-09
 */
@Service
public class SysLicenseServiceImpl implements ISysLicenseService
{
    private static final Logger log = LoggerFactory.getLogger(SysLicenseServiceImpl.class);

    @Autowired
    private SysLicenseMapper sysLicenseMapper;


    /**
     * 查询系统许可证（获取第一条记录）
     *
     * @return 系统许可证
     */
    @Override
    public SysLicense selectSysLicense()
    {
        return sysLicenseMapper.selectSysLicense();
    }


    /**
     * 验证许可证是否有效（解密验证）
     *
     * @return true=有效 false=无效
     */
    @Override
    public boolean validateLicense()
    {
        try
        {
            SysLicense license = selectSysLicense();
            if (license == null)
            {
                log.error("许可证不存在");
                return false;
            }


            String encryptedKey = license.getLicenseKey();
            if (encryptedKey == null || encryptedKey.trim().isEmpty())
            {
                log.error("许可证密钥为空");
                return false;
            }

            // 解密并验证许可证
            String decryptedData = LicenseEncryptUtil.decrypt(encryptedKey);
            if (decryptedData == null)
            {
                log.error("许可证密钥解密失败");
                return false;
            }

            // 解析许可证数据：格式为 "激活时间|到期时间|试用天数|校验码"
            String[] parts = decryptedData.split("\\|");
            if (parts.length != 4)
            {
                log.error("许可证数据格式错误");
                return false;
            }

            try
            {
                long activationTimeMs = Long.parseLong(parts[0]);
                long expiryTimeMs = Long.parseLong(parts[1]);
                int trialDays = Integer.parseInt(parts[2]);
                String checksum = parts[3];

                // 验证校验码
                String expectedChecksum = LicenseEncryptUtil.generateChecksum(
                    activationTimeMs, expiryTimeMs, trialDays);
                if (!checksum.equals(expectedChecksum))
                {
                    log.error("许可证校验码验证失败");
                    return false;
                }

                // 检查是否过期
                Date now = new Date();
                Date expiryTime = new Date(expiryTimeMs);

                if (now.after(expiryTime))
                {
                    log.warn("许可证已过期，到期时间: {}", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiryTime));
                    return false;
                }

                log.info("许可证验证通过，到期时间: {}", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiryTime));
                return true;
            }
            catch (NumberFormatException e)
            {
                log.error("许可证数据解析失败", e);
                return false;
            }
        }
        catch (Exception e)
        {
            log.error("验证许可证时发生异常", e);
            return false;
        }
    }

    /**
     * 获取许可证状态信息
     *
     * @return 许可证状态信息
     */
    @Override
    public String getLicenseStatusInfo()
    {
        try
        {
            SysLicense license = selectSysLicense();
            if (license == null)
            {
                return "许可证不存在";
            }

            String encryptedKey = license.getLicenseKey();
            if (encryptedKey == null || encryptedKey.trim().isEmpty())
            {
                return "许可证密钥为空";
            }

            // 解密许可证
            String decryptedData = LicenseEncryptUtil.decrypt(encryptedKey);
            if (decryptedData == null)
            {
                return "许可证密钥无效";
            }

            String[] parts = decryptedData.split("\\|");
            if (parts.length != 5)
            {
                return "许可证数据格式错误";
            }

            try
            {
                long expiryTimeMs = Long.parseLong(parts[1]);
                Date expiryTime = new Date(expiryTimeMs);
                Date now = new Date();

                long diffInMillies = expiryTime.getTime() - now.getTime();
                long diffInDays = diffInMillies / (1000 * 60 * 60 * 24);

                if (diffInDays < 0)
                {
                    return "试用期已过期，请联系管理员续费";
                }
                else if (diffInDays == 0)
                {
                    return "试用期今天到期，请尽快续费";
                }
                else
                {
                    return String.format("试用期剩余 %d 天（到期时间: %s）",
                        diffInDays,
                        DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, expiryTime));
                }
            }
            catch (NumberFormatException e)
            {
                log.error("解析许可证时间失败", e);
                return "许可证数据解析失败";
            }
        }
        catch (Exception e)
        {
            log.error("获取许可证状态信息时发生异常", e);
            return "获取许可证状态失败";
        }
    }
    
    
}
