package com.yeejoin.amos.kgd.config;

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.context.SpringContextHelper;

import java.io.*;
import java.net.Socket;
import java.util.Objects;

/**
 * @Author: xl
 * @Description:
 * @Date: 2023/10/10 16:21
 */
public class ClientHandler implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);

    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 获取输入流和输出流
            InputStream inputStream = socket.getInputStream();
            // 处理客户端请求
            log.info("收到客户端数据: ");
            String path = this.upload2Maas(inputStream);
            log.info("调用maas服务返回结果: {}", path);
            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 上传maas逻辑写到这⬇⬇⬇⬇⬇⬇⬇，然后把maas返回的资源路径返回，后续作为客户端的回传信息
    private String upload2Maas(InputStream inputStream) {
        AmosRequestContext robotAuthentication = SpringContextHelper.getBean(AmosRequestContext.class);
        if (Objects.nonNull(robotAuthentication)) {
            RequestContext.setAppKey(robotAuthentication.getAppKey());
            RequestContext.setProduct(robotAuthentication.getProduct());
            RequestContext.setToken(robotAuthentication.getToken());
        }

        // 测试案例，上传maas需要token，用机器人账户登录上传，此处修改为真实请求⬇⬇⬇⬇⬇⬇⬇
        FeignClientResult<AgencyUserModel> getme = Privilege.agencyUserClient.getme();
        System.out.println(JSON.toJSONString(getme));
        return null;
    }

    public static void main(String[] args) throws Exception {
        requestInfoToSocketServer();
    }

    private static void requestInfoToSocketServer() {
        try {
            Socket socket = new Socket("127.0.0.1", 7777);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.write("我是客户端");
            out.flush();
            socket.shutdownOutput();
            //开始接收服务端的消息
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            log.info("接收到服务端的回复:" + in.readLine());
        } catch (Exception e) {
            log.info("Socket传输数据异常!" + e.getMessage());
        }
    }
}