package com.yd.csf.api.async;

import com.yd.common.result.Result;
import com.yd.csf.api.service.ApiExpectedFortuneService;
import com.yd.csf.feign.request.expectedfortune.ApiGenerateExpectedFortuneRequest;
import com.yd.csf.feign.response.expectedfortune.ApiGenerateExpectedFortuneResponse;
import com.yd.feign.config.FeignTokenInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class ApiExpectedFortuneAsyncService {

    @Resource
    private ApiExpectedFortuneService apiExpectedFortuneService;

    /**
     * 异步处理
     *
     * @return
     */
    @Async("commonAsyncExecutor")
    public Result execute(String policyNo, String token) {
        // 将 token 设置到 ThreadLocal 中，供 Feign 拦截器使用
        FeignTokenInterceptor.setThreadLocalToken(token);

        HttpServletRequest request1 = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token1 = request1.getHeader("Authorization");
        log.info("异步处理 token==============,{}",token1);

        try {
            ApiGenerateExpectedFortuneRequest request = new ApiGenerateExpectedFortuneRequest();
            request.setPolicyNo(policyNo);
            log.info("生成预计发佣 generateSyncWithLogAndRedis ——> PolicyNo：{}", policyNo);
            Result<ApiGenerateExpectedFortuneResponse> result =
                    apiExpectedFortuneService.generateSyncWithLogAndRedis(request);
            if (result != null && result.getCode() == 200) {
                log.info("新单跟进-同步生成预计出账记录成功: 保单号={}", policyNo);
            }
            return result;
        } finally {
            // 必须清理，防止内存泄漏
            FeignTokenInterceptor.clearThreadLocalToken();
        }
    }

}
