package com.bailuntec.utils;

import com.bailuntec.domain.constant.CommonConstant;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;

public class SessionUtil {
    //当前线程里面存放session
    private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static final ThreadLocal<SqlSession> threadLocalTransction = new ThreadLocal<>();
    private static Reader reader = null;
    private static SqlSessionFactoryBuilder builder = null;
    private static SqlSessionFactory factory = null;

    //不允许对该类进行new操作
    private SessionUtil() {
    }

    static {
        try {
            //1.加载配置文件
            reader = Resources.getResourceAsReader(CommonConstant.MYBATIS_CONFIG);
            //2.得到工厂的创建对象
            builder = new SqlSessionFactoryBuilder();
            //3.得到工厂对象
            factory = builder.build(reader);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("SqlSessionFactory初始化失败, 请检查配置文件路径和内容");
        }
    }

    //获取自动提交session
    public static SqlSession getSession() {
        SqlSession session = threadLocal.get();
        if (session == null) {
            SqlSessionFactory factory = getFactory();
            session = factory.openSession(true);
            threadLocal.set(session);
        }
        return session;
    }

    //获取手动提交session
    public static SqlSession getTranstionSession() {
        SqlSession session = threadLocalTransction.get();
        if (session == null) {
            SqlSessionFactory factory = getFactory();
            session = factory.openSession();
            threadLocalTransction.set(session);
        }
        return session;
    }

    //关闭session
    public static void closeTranstionSession() {
        try {
            SqlSession session = threadLocalTransction.get();
            if (session != null) {
                session.close();
            }
            threadLocalTransction.set(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYSQL关闭Session异常", e);
        }
    }

    //关闭session
    public static void closeSession() {
        try {
            SqlSession session = threadLocal.get();
            if (session != null) {
                session.close();
            }
            threadLocal.set(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYSQL关闭Session异常", e);
        }
    }

    //获得工厂对象
    public static SqlSessionFactory getFactory() {
        if (factory == null) {
            factory = builder.build(reader);
        }
        return factory;
    }
}
