package thyyxxk.webserver.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;

import java.util.HashMap;
import java.util.Map;

public class SqlRunnerAdapter extends SqlRunner {

    public SqlRunnerAdapter() {
        super();
    }

    @Override
    public <E extends IPage<Map<String, Object>>> E selectPage(E page, String sql, Object... args) {
        if (null == page) {
            return null;
        }
        SqlSession sqlSession = sqlSession();
        try {
            page.setRecords(sqlSession.selectList(SELECT_LIST, sqlMap(sql, page, args)));
        }finally {
            closeSqlSession(sqlSession);
        }
        return page;
    }


    private SqlSession sqlSession() {
        return SqlSessionUtils.getSqlSession(SqlHelper.FACTORY);
    }

    private Map<String, Object> sqlMap(String sql, IPage page, Object... args) {
        Map<String, Object> sqlMap = new HashMap<>();
        sqlMap.put(PAGE, page);
        sqlMap.put(SQL, StringUtils.sqlArgsFill(sql, args));
        return sqlMap;
    }

    private static void closeSqlSession(SqlSession sqlSession) {
        SqlSessionFactory sqlSessionFactory = SqlHelper.FACTORY;
        SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
    }
}

