package cc.iotkit.data.config;

import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.StringUtils;
import com.querydsl.core.types.Predicate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static cn.dev33.satoken.SaManager.log;

@Aspect
@Component
public class TenantAspect {
    @PersistenceContext
    private EntityManager entityManager;
    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /*@Around("@annotation(dataFilter)")
    @Transactional
    public Object doProcess(ProceedingJoinPoint joinPoint, DataFilter dataFilter) throws Throwable {
        System.out.println("进入切面了~~~~~~~~~~~");
        // 从获取RequestAttributes中获取HttpServletRequest的信息
     *//*   HttpServletRequest request= (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
        Map<String, String> rtnMap = converMap(request.getParameterMap());
        String tenantId = rtnMap.get("tenantId");*//*

        try {
            Long tenantId = 111L;
            Session session = entityManager.unwrap(Session.class);
            //!自定义的属性名属性值名，设置值，该值可以是集合类型，可以是基本类型，这里是集合类型
            session.enableFilter("tenantId").setParameter("tenantFilter", tenantId);
            return joinPoint.proceed();
        } catch (Throwable ex) {
            System.out.println("出错了::");
            ex.printStackTrace();
            throw ex;
        } finally {
            System.out.println("最终关闭过滤器");
            entityManager.unwrap(Session.class).disableFilter("tenantId");

        }
    }*/

    @Around("execution(* org.springframework.data.jpa.repository.JpaRepository+.*(..)) || " +
            "execution(* org.springframework.data.repository.query.QueryByExampleExecutor+.*(..))")
    public Object applyTenantFilter(ProceedingJoinPoint pjp) throws Throwable {
      //  System.out.println("111111111111Thread" + TenantContext.isFilterDisabled());
        if(LoginHelper.isSuperAdmin()){
            return pjp.proceed(); // 跳过租户过滤
            // TenantContext.disableTenantFilter();
        }
        if(TenantContext.isFilterDisabled()) {
            return pjp.proceed(); // 跳过租户过滤
        }
        //放开租户
        Long tenantId= LoginHelper.getTenantId();
     //   Long tenantId = 0L; // 实现租户ID获取逻辑
        if(ObjectUtils.isEmpty(tenantId)){
            tenantId = 0L;
        }
        try {
            entityManager.unwrap(Session.class)
                    .enableFilter("tenantFilter")
                    .setParameter("tenantId", tenantId);
            return pjp.proceed();
        } finally {
            entityManager.unwrap(Session.class).disableFilter("tenantFilter");
        }
    }

 /*   @AfterReturning("execution(* org.springframework.data.jpa.repository.JpaRepository+.*(..)) || " +
            "execution(* org.springframework.data.repository.query.QueryByExampleExecutor+.*(..))")
    public void cleanup() {
        TenantContext.enableTenantFilter(); // 确保状态重置
    }*/

}
