package com.yc.ship.module.trade.framework.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.yc.ship.framework.tenant.core.context.TenantContextHolder;
import com.yc.ship.module.ota.api.OtaDistributorApi;
import com.yc.ship.module.ota.api.dto.DistributorRespDTO;
import com.yc.ship.module.trade.framework.annotation.PlatTenantEnv;
import com.yc.ship.module.trade.framework.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 平台租户环境 AOP 切面
 */
@Component
@Aspect
@Slf4j
public class TradePlatAspect {

    @Resource
    private OtaDistributorApi otaDistributorApi;

    @Around("@annotation(platTenantEnv)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, PlatTenantEnv platTenantEnv) throws Throwable {
        Long tenantId = TenantContextHolder.getTenantId();
        if(tenantId == null) {
            return proceedingJoinPoint.proceed();
        }
        DistributorRespDTO distributorDto = SpringUtil.getBean(TradePlatAspect.class).getDistributor(tenantId);
        if(distributorDto == null) {
            return proceedingJoinPoint.proceed();
        }
        if(ObjectUtil.equal(distributorDto.getSelfSupport(),0) && ObjectUtil.equal(distributorDto.getType(),2)) {
//        //如果是外部旅行社
            try {
                TenantContextHolder.setTenantId(distributorDto.getTenantId());
                ThreadLocalUtil.setAgencyId(distributorDto.getId());
                Object result = proceedingJoinPoint.proceed();
                TenantContextHolder.setTenantId(tenantId);
                return result;
            } catch (Exception e) {
                throw e;
            } finally {
                ThreadLocalUtil.clearAgencyId();
                TenantContextHolder.setTenantId(tenantId);
            }
        }else {
            return proceedingJoinPoint.proceed();
        }
    }

    @Cacheable(cacheNames = "distributor#600",key = "#tenantId")
    public DistributorRespDTO getDistributor(Long tenantId){
        return null;
//        return otaDistributorApi.getDistributorByAccountTenantId(tenantId).getData();
    }

}
