package com.jeeplus.sys.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.constant.CommonConstants;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.sys.domain.Tenant;
import com.jeeplus.sys.service.TenantService;

import java.util.Date;

public class TenantUtils {


    /**
     * 获取租户Id
     *
     * @return
     */
    public static String getTenantId() {

        /**
         * 如果用户未登录，根据域名获取租户id
         */
        String domain = RequestUtils.getHeader ( "domain" );
        if ( domain == null ) {
            return CommonConstants.DEFAULT_TENANT_ID; // 返回默认租户
        }

        String tenantId = (String) RedisUtils.getInstance ( ).get ( CacheNames.SYS_CACHE_TENANT, domain );
        if ( tenantId == null ) {
            Tenant tenant = SpringUtil.getBean ( TenantService.class ).lambdaQuery ( ).eq ( Tenant::getDomain, domain ).one ( );

            if ( tenant == null ) {
                tenantId = CommonConstants.DEFAULT_TENANT_ID;
                RedisUtils.getInstance ( ).set ( CacheNames.SYS_CACHE_TENANT, domain, CommonConstants.DEFAULT_TENANT_ID );
            } else {
                tenantId = tenant.getId ( );
                if ( !CommonConstants.DEFAULT_TENANT_ID.equals ( tenantId ) && tenant.getBeginDate ( ) != null && DateUtil.compare ( tenant.getBeginDate ( ), new Date ( ) ) > 0 ) {
                    throw new RuntimeException ( "您预订的租户开通时间是：" + DateUtil.format ( tenant.getBeginDate ( ), "YYYY-MM-dd HH:mm:ss" ) + ", 目前租户未开通，暂不能使用!" );
                }
                if ( !CommonConstants.DEFAULT_TENANT_ID.equals ( tenantId ) && tenant.getEndDate ( ) != null && DateUtil.compare ( tenant.getEndDate ( ), new Date ( ) ) < 0 ) {
                    throw new RuntimeException ( "您的租户到期时间是：" + DateUtil.format ( tenant.getEndDate ( ), "YYYY-MM-dd HH:mm:ss" ) + ", 目前已过期，暂不能使用!" );
                }
                if ( CommonConstants.NO.equals ( tenant.getStatus ( ) ) ) {
                    throw new RuntimeException ( "您的系统已经被禁用，请联系平台客服！" );
                }
                RedisUtils.getInstance ( ).set ( CacheNames.SYS_CACHE_TENANT, domain, tenant.getId ( ) );
            }
        }

        return tenantId;


    }

}
