package com.ruoyi.info.collection.mapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.parser.defaults.DefaultCountSqlParser;
import com.ruoyi.info.collection.domain.dto.CcdiStaffFmyRelationQueryDTO;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.TypeAliasRegistry;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CcdiStaffFmyRelationMapperTest {

    private static final String RESOURCE = "mapper/info/collection/CcdiStaffFmyRelationMapper.xml";

    @Test
    void selectRelationPage_shouldRenderWhitespaceBeforeDynamicAndClause() throws Exception {
        MappedStatement mappedStatement = loadMappedStatement(
                "com.ruoyi.info.collection.mapper.CcdiStaffFmyRelationMapper.selectRelationPage");

        CcdiStaffFmyRelationQueryDTO queryDTO = new CcdiStaffFmyRelationQueryDTO();
        queryDTO.setPersonId("320101199001010011");
        String sql = renderSql(mappedStatement, Map.of(
                "page", new Page<>(1, 10),
                "query", queryDTO
        ));
        String countSql = normalizeSql(new DefaultCountSqlParser().getSmartCountSql(sql, "0"));

        assertTrue(sql.contains("WHERE 1 = 1 AND r.is_emp_family = 1 AND r.person_id = ?"), sql);
        assertFalse(sql.contains("1AND"), sql);
        assertFalse(countSql.contains("1AND"), countSql);
        assertTrue(sql.contains("r.annual_income"), sql);
    }

    @Test
    void mapperXml_shouldContainAnnualIncomeInBatchInsert() throws Exception {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(RESOURCE)) {
            String xml = new String(inputStream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
            assertTrue(xml.contains("annual_income"), xml);
            assertTrue(xml.contains("#{item.annualIncome}"), xml);
        }
    }

    private MappedStatement loadMappedStatement(String statementId) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setEnvironment(new Environment("test", new JdbcTransactionFactory(), new NoOpDataSource()));
        registerTypeAliases(configuration.getTypeAliasRegistry());
        configuration.getLanguageRegistry().register(XMLLanguageDriver.class);
        configuration.addMapper(CcdiStaffFmyRelationMapper.class);

        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(RESOURCE)) {
            XMLMapperBuilder xmlMapperBuilder =
                    new XMLMapperBuilder(inputStream, configuration, RESOURCE, configuration.getSqlFragments());
            xmlMapperBuilder.parse();
        }
        return configuration.getMappedStatement(statementId);
    }

    private String renderSql(MappedStatement mappedStatement, Map<String, Object> params) {
        BoundSql boundSql = mappedStatement.getBoundSql(new HashMap<>(params));
        return normalizeSql(boundSql.getSql());
    }

    private String normalizeSql(String sql) {
        return sql.replaceAll("\\s+", " ").trim();
    }

    private void registerTypeAliases(TypeAliasRegistry typeAliasRegistry) {
        typeAliasRegistry.registerAlias("map", Map.class);
    }

    private static class NoOpDataSource implements DataSource {

        @Override
        public java.sql.Connection getConnection() {
            throw new UnsupportedOperationException("Not required for SQL rendering tests");
        }

        @Override
        public java.sql.Connection getConnection(String username, String password) {
            throw new UnsupportedOperationException("Not required for SQL rendering tests");
        }

        @Override
        public java.io.PrintWriter getLogWriter() {
            return null;
        }

        @Override
        public void setLogWriter(java.io.PrintWriter out) {
        }

        @Override
        public void setLoginTimeout(int seconds) {
        }

        @Override
        public int getLoginTimeout() {
            return 0;
        }

        @Override
        public java.util.logging.Logger getParentLogger() {
            return java.util.logging.Logger.getGlobal();
        }

        @Override
        public <T> T unwrap(Class<T> iface) {
            throw new UnsupportedOperationException("Not supported");
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) {
            return false;
        }
    }
}
