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 org.springframework.web.context.request.RequestContextHolder;

import java.util.Date;

public class TenantUtils {


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

// 1. 关键：先判断是否有请求上下文，没有就直接返回默认租户
        if (!hasRequest()) {
            return CommonConstants.DEFAULT_TENANT_ID;
        }

        // 2. 下面是你修改后的原有逻辑
        String domain = RequestUtils.getHeader("domain");
        if (domain != null && domain.contains("ydddl")) {
            domain = getDomainOrIp(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;


    }

    // 新增：判断当前是否存在请求上下文
    public static boolean hasRequest() {
        return RequestContextHolder.getRequestAttributes() != null;
    }

    /**
     * 从url中获取ip地址（移动端数据处理）
     * @param url
     * @return
     */
    public static String getDomainOrIp(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        // 1. 去掉 http:// 或 https://
        String withoutHttp = url.replaceFirst("^https?://", "");

        // 2. 截取到第一个 : 或 / 之前（取出纯域名/IP）
        int indexPort = withoutHttp.indexOf(":");
        int indexPath = withoutHttp.indexOf("/");
        int splitIndex = indexPort;

        if (indexPath != -1 && (splitIndex == -1 || indexPath < splitIndex)) {
            splitIndex = indexPath;
        }
        if (splitIndex != -1) {
            withoutHttp = withoutHttp.substring(0, splitIndex);
        }

        // 3. 去掉末尾的 ydddl（只去掉结尾的）
        withoutHttp = withoutHttp.replaceFirst("ydddl$", "");

        return withoutHttp;
    }

}
