package demo.helloconsumer;

import demo.hellocommon.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.ConditionalOnRepositoryType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.concurrent.CompletableFuture;

@RestController
public class HelloConsumerController {

    //DubboReference(timeout=3000,retries=3)
    @DubboReference(methods={@Method(name="doTask",async = true)})
    private HelloService helloService;

    @Value("${server.port}")
    private String servicePort;

    @PostConstruct
    public void init(){
         helloService.addListener(servicePort, new MyCallbackListener());
    }

    @GetMapping(value = "/callback/{username}")
    public String testCallback(@PathVariable String username) {
        return helloService.sayHello(username,servicePort);
    }

    @GetMapping(value = "/enter/{username}")
    public String sayHello(@PathVariable String username) {
       //try {

       return helloService.sayHello(username);
       //}catch (Exception ex){
       //    return username+",something is wrong."
       //            +"<br>"+getStackTrace(ex);
       //}
    }

    //获得异常的详细信息
    public static String getStackTrace(Throwable cause) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            cause.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

    @GetMapping(value = "/testuser")
    public Result testUser() {
        Name name = new Name("xiaoming", "zhang");
        User user=new User(1,name);
        return helloService.testUser(user);
    }

    @GetMapping(value = "/testasync")
    public String testAsync() {
        //此方法立即返回null
        helloService.doTask("保存文件");
        CompletableFuture<String> helloFuture = RpcContext.getContext().getCompletableFuture();

        helloFuture.whenComplete((result, exception) -> {
            if (exception == null) {
                System.out.println(result);
            } else {
                exception.printStackTrace();
            }
        });

        return "任务已经下达";
    }
}


/*********************************************************
 * 作者：孙卫琴                                   
 * 来源：《Spring Cloud Alibaba微服务开发零基础入门到实战》源代码  
 * 技术支持网址：www.javathinker.net/alibaba                    
 *********************************************************/
