package cn.ibizlab.r7.runtime.runtimemgr.rt.service;

import cn.ibizlab.r7.runtime.util.feign.FeignRequestInterceptor;
import cn.ibizlab.r7.runtime.util.feign.suport.SearchContextFeignEncode;
import cn.ibizlab.r7.runtime.runtimemgr.RuntimeMgrApplication;
import cn.ibizlab.r7.runtime.runtimemgr.rt.domain.SRFFILE;
import cn.ibizlab.r7.runtime.runtimemgr.rt.feign.SRFFileFeignClient;
import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.stereotype.Component;
/**
 * 文件上传
 */
@Component
public class SRFFileService {

    SRFFileFeignClient client;

    @Autowired
    public SRFFileService(Decoder decoder, Encoder encoder, Client client, Contract contract, FeignRequestInterceptor feignRequestInterceptor,
        RuntimeMgrApplication.RuntimeMgrClientProperties webClientProperties) {
        if (webClientProperties.getServiceId()!=null) {
            Feign.Builder nameBuilder = Feign.builder()
                    .client(client)
                    .encoder(new SearchContextFeignEncode(encoder))
                    .decoder(decoder)
                    .contract(contract)
                    .requestInterceptor(feignRequestInterceptor)
                    ;
            this.client = nameBuilder.target(SRFFileFeignClient.class,"http://" + webClientProperties.getServiceId() + "/") ;
        } else if (webClientProperties.getServiceUrl()!=null) {
            if (client instanceof LoadBalancerFeignClient) {
                client = ((LoadBalancerFeignClient) client).getDelegate();
            }
            Feign.Builder nameBuilder = Feign.builder()
                    .client(client)
                    .encoder(new SearchContextFeignEncode(encoder))
                    .decoder(decoder)
                    .contract(contract)
                    .requestInterceptor(feignRequestInterceptor)
                    ;
            this.client = nameBuilder.target(SRFFileFeignClient.class, "http://" + webClientProperties.getServiceUrl() + "/") ;
        }
    }

    /**
     * 保存file记录
     * @param fileId
     * @param ibzfile
     * @return
     */
    public boolean save(String fileId, SRFFILE ibzfile) {
        return client.save(fileId, ibzfile);
    }

    /**
     * 获取file记录
     * @param fileId
     * @return
     */
    public SRFFILE get(String fileId) {
        return client.get(fileId);
    }

}
