package com.ibiz.web.rt.service;

import com.ibiz.util.feign.FeignRequestInterceptor;
import com.ibiz.util.feign.suport.SearchContextFeignEncode;
import com.ibiz.web.WebApplication;
import com.ibiz.web.rt.domain.SRFFILE;
import com.ibiz.web.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,
        WebApplication.WebClientProperties 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);
    }

}
