package com.zm.order.tool.server.component;


import com.zm.order.tool.server.model.OrderSession;
import com.zm.order.tool.server.model.TraceIdentity;

import java.util.Objects;
import java.util.UUID;

/**
 * @Description 线程上下文 先搞一个字段试试 需要加字段就用对象
 * @Author: ph
 * @Date: 2019/11/11 20:10
 */
public class ThreadContext {

    private static ThreadLocal<OrderSession> context = new ThreadLocal<>();

    public static void setContext(OrderSession session) {
        context.set(session);
    }

    public static OrderSession getContext() {
        return context.get();
    }

    public static void removeContext() {
        context.remove();
    }

    public static void setDbSize(int dbSize) {
        OrderSession orderSession = context.get();
        if (Objects.isNull(orderSession)) {
            orderSession = new OrderSession();
        }
        orderSession.setDbSize(dbSize);
        context.set(orderSession);
    }

    public static void setBizType(Integer bizType) {
        OrderSession orderSession = context.get();
        if (Objects.isNull(orderSession)) {
            orderSession = new OrderSession();
        }
        orderSession.setBizType(bizType);
        context.set(orderSession);
    }

    public static Integer getBizType() {
        if (Objects.nonNull(context.get())) {
            return context.get().getBizType();
        }
        return null;
    }


    public static Integer getDbSize() {
        if (Objects.nonNull(context.get())) {
            return context.get().getDbSize();
        }
        return null;
    }

    public static void setRole(Integer role) {
        OrderSession orderSession = context.get();
        if (Objects.isNull(orderSession)) {
            orderSession = new OrderSession();
        }
        orderSession.setRole(role);
        context.set(orderSession);
    }

    public static Integer getRole() {
        if (Objects.nonNull(context.get())) {
            return context.get().getRole();
        }
        return null;
    }

    public static void setTraceIdentity(TraceIdentity traceIdentity) {
        OrderSession orderSession = context.get();
        if (Objects.isNull(orderSession)) {
            orderSession = new OrderSession();
        }
        orderSession.setTraceIdentity(traceIdentity);
        context.set(orderSession);
    }

    public static TraceIdentity getTraceIdentity() {
        if (Objects.isNull(context.get()) || Objects.isNull(context.get().getTraceIdentity())) {
            TraceIdentity traceIdentity = new TraceIdentity();
            traceIdentity.setTraceId("OC" + UUID.randomUUID().toString().replace("-", ""));
            traceIdentity.setTraceSpanId("0");
            return traceIdentity;
        }
        return context.get().getTraceIdentity();
    }
}
