package com.mortals.xhx.module.license.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.mortals.xhx.base.system.upload.service.UploadService;
import lombok.Getter;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.license.dao.LicenseDao;
import com.mortals.xhx.module.license.model.LicenseEntity;
import com.mortals.xhx.module.license.service.LicenseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * LicenseService
 * 许可证 service实现
 *
 * @author zxfei
 * @date 2024-07-05
 */
@Service("licenseService")
@Slf4j
public class LicenseServiceImpl extends AbstractCRUDServiceImpl<LicenseDao, LicenseEntity, Long> implements LicenseService {

    @Autowired
    private UploadService uploadService;
    @Value("${upload.path}")
    @Getter
    private String filePath;

    @Override
    protected void saveBefore(LicenseEntity entity, Context context) throws AppException {

        if(ObjectUtils.isEmpty(entity.getMac())) throw new AppException("MAC地址不能为空");
        if(ObjectUtils.isEmpty(entity.getIp())) throw new AppException("机器IP地址不能为空");
        long between = DateUtil.between(entity.getStartTime(), entity.getEndTime(), DateUnit.MINUTE);
        if(between <= 0){
            throw new AppException("开始时间必须小于结束时间");
        }
        //存放文件 xxx/
        if (!ObjectUtils.isEmpty(entity.getLicenseCode())) {
            String pubPath = uploadService.getFilePath(entity.getLicenseCode() + "/license.pub");
            entity.setLicensePubPath(pubPath);
            String keyPath = uploadService.getFilePath(entity.getLicenseCode() + "/license.key");
            entity.setLicenseKeyPath(keyPath);
            String priPath = uploadService.getFilePath(entity.getLicenseCode() + "/license.pri");
            entity.setLicensePriPath(priPath);
        }

        entity.setLicenseCode(entity.getMac()+entity.getIp());
        super.saveBefore(entity, context);
    }

    @Override
    protected void updateBefore(LicenseEntity entity, Context context) throws AppException {
        entity.setLicenseCode(entity.getMac()+entity.getIp());
        super.updateBefore(entity, context);
    }
}