package com.yd.csf.api.service.impl;

import com.yd.common.result.Result;
import com.yd.csf.api.service.ApiExpectedFortuneService;
import com.yd.csf.api.service.ApiPolicyFollowService;
import com.yd.csf.feign.request.expectedfortune.ApiGenerateExpectedFortuneRequest;
import com.yd.csf.feign.response.expectedfortune.ApiGenerateExpectedFortuneResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class ApiPolicyFollowServiceImpl implements ApiPolicyFollowService {

    @Autowired
    private ApplicationContext applicationContext;

    private ApiPolicyFollowService getSelf() {
        return applicationContext.getBean(ApiPolicyFollowService.class);
    }

    @Resource
    private ApiExpectedFortuneService apiExpectedFortuneService;

    /**
     * 同步生成预计出账记录
     *
     * @param token 认证Token
     * @param policyNo 保单号
     */
    @Override
    public void generateExpectedFortuneSync(String token, String policyNo) {
        // 设置ThreadLocal Token
//        FeignTokenInterceptor.setThreadLocalToken(token);
        getSelf().execute(token,policyNo);

    }

    /**
     * 异步处理
     *
     * @return
     */
    @Override
    @Async("commonAsyncExecutor")
    public Result execute(String token, String policyNo) {
        // 调用 ApiExpectedFortuneService 的 generateSyncWithLogAndRedis（同步版本，包含日志和Redis处理）
        ApiGenerateExpectedFortuneRequest generateExpectedFortuneRequest = new ApiGenerateExpectedFortuneRequest();
        generateExpectedFortuneRequest.setPolicyNo(policyNo);
        log.info("生成预计发佣generateSyncWithLogAndRedis——>PolicyNo：{}", policyNo);
        Result<ApiGenerateExpectedFortuneResponse> result = apiExpectedFortuneService.generateSyncWithLogAndRedis(generateExpectedFortuneRequest);
        if (result != null && result.getCode() == 200) {
            log.info("新单跟进-同步生成预计出账记录成功:保单号={}", policyNo);
        }
        return Result.success();
    }


}
